package com.gentics.mesh.core.graphql;

import static com.gentics.mesh.core.data.relationship.GraphPermission.READ_PERM;
import static com.gentics.mesh.test.TestDataProvider.PROJECT_NAME;
import static com.gentics.mesh.test.context.MeshTestHelper.call;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static org.junit.Assert.*;

import org.json.JSONException;
import org.junit.Test;

import com.gentics.mesh.graphdb.NoTx;
import com.gentics.mesh.test.TestSize;
import com.gentics.mesh.test.context.AbstractMeshTest;
import com.gentics.mesh.test.context.MeshTestSetting;
import com.gentics.mesh.util.MeshJSONAssert;

import io.vertx.core.json.JsonObject;

@MeshTestSetting(useElasticsearch = false, testSize = TestSize.FULL, startServer = true)
public class GraphQLEndpointBasicTest extends AbstractMeshTest {

	@Test
	public void testIntrospection() {
		JsonObject response = call(() -> client().graphql(PROJECT_NAME, getGraphQLQuery("introspection-query")));
		assertNotNull(response);
	}

	@Test
	public void testSimpleQuery() throws JSONException {
		JsonObject response = call(() -> client().graphqlQuery(PROJECT_NAME, "{me{firstname}}"));
		MeshJSONAssert.assertEquals("{'data':{'me':{'firstname':'Joe'}}}", response);
	}

	@Test
	public void testEmptyQuery() throws Throwable {
		JsonObject response = call(() -> client().graphqlQuery(PROJECT_NAME, ""), BAD_REQUEST);
		assertFalse("The errors array should not be empty.", response.getJsonArray("errors")
				.isEmpty());
	}

	@Test
	public void testDataFetchingError() throws Throwable {
		try (NoTx noTx = db().noTx()) {
			role().revokePermissions(project(), READ_PERM);
		}
		JsonObject response = call(() -> client().graphqlQuery(PROJECT_NAME, "{project{name}}"), BAD_REQUEST);
		System.out.println(response.encodePrettily());
	}

	@Test
	public void testErrorHandling() throws Throwable {
		JsonObject response = call(() -> client().graphqlQuery(PROJECT_NAME, "{bogus{firstname}}"), BAD_REQUEST);
		assertFalse("The errors array should not be empty.", response.getJsonArray("errors")
				.isEmpty());
	}
}

@@ -386,16 +386,44 @@
 eption;%0A
+import org.json.JSONObject;%0A
 import o
@@ -2119,11 +2119,528 @@
 y());%0A%09%7D
+%0A%0A%09@Test%0A%09public void testVariables() throws Throwable %7B%0A%09%09JsonObject query = new JsonObject()%0A%09%09%09%09.put(%22query%22, %22query test($var: String) %7B content(path: $var) %7B node %7B uuid %7D %7D %7D%22)%0A%09%09%09%09.put(%22variables%22, new JsonObject()%0A%09%09%09%09%09%09.put(%22var%22, %22/News%22)%0A%09%09%09%09);%0A%09%09JsonObject response = call(() -%3E client().graphql(PROJECT_NAME, query.toString()));%0A%09%09String uuid = response.getJsonObject(%22data%22).getJsonObject(%22content%22).getJsonObject(%22node%22).getString(%22uuid%22);%0A%0A%09%09assertTrue(%22There should be a uuid%22, uuid.length() %3E 0);%0A%09%7D
 %0A%7D%0A

Add test for GraphQL variables