import json
from webtest import TestApp as Client
from wsgi_graphql import wsgi_graphql

from graphql.core.type import (
    GraphQLObjectType,
    GraphQLField,
    GraphQLArgument,
    GraphQLNonNull,
    GraphQLSchema,
    GraphQLString,
)


def raises(*_):
    raise Exception("Raises!")


TestSchema = GraphQLSchema(
    query=GraphQLObjectType(
        'Root',
        fields=lambda: {
            'test': GraphQLField(
                GraphQLString,
                args={
                    'who': GraphQLArgument(
                        type=GraphQLString
                    )
                },
                resolver=lambda root, args, *_: 'Hello ' + (args['who'] or 'World')
            ),
            'thrower': GraphQLField(
                GraphQLNonNull(GraphQLString),
                resolver=raises
            )
        }
    )
)


def test_allows_GET_with_query_param():
    wsgi = wsgi_graphql(TestSchema)

    c = Client(wsgi)
    response = c.get('/', {'query': '{test}'})
    assert response.json == {
        'data': {
            'test': 'Hello World'
        }
    }


def test_allows_GET_with_variable_values():
    wsgi = wsgi_graphql(TestSchema)

    c = Client(wsgi)
    response = c.get('/', {
        'query': 'query helloWho($who: String){ test(who: $who) }',
        'variables': json.dumps({'who': 'Dolly'})
    })

    assert response.json == {
        'data': {
            'test': 'Hello Dolly'
        }
    }

@@ -1433,24 +1433,583 @@
  Dolly'%0A        %7D%0A    %7D%0A
+%0A%0Adef test_allows_GET_with_operation_name():%0A    wsgi = wsgi_graphql(TestSchema)%0A%0A    c = Client(wsgi)%0A    response = c.get('/', %7B%0A        'query': '''%5C%0Aquery helloYou %7B test(who: %22You%22), ...shared %7D%0Aquery helloWorld %7B test(who: %22World%22), ...shared %7D%0Aquery helloDolly %7B test(who: %22Dolly%22), ...shared %7D%0Afragment shared on Root %7B%0A  shared: test(who: %22Everyone%22)%0A%7D'''%0A        ,%0A        'operationName': 'helloWorld'%0A    %7D)%0A%0A    assert response.json == %7B%0A        'data': %7B%0A            'test': 'Hello World',%0A            'shared': 'Hello Everyone'%0A        %7D%0A    %7D%0A

Test that operation name argument works.