Exemple #1
0
def test_simple_query_with_optional_argument():

    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info, name: str = "world") -> str:
        return "Hello {}".format(name)

    # ----------------------------------------------------------------

    result = schema.execute("{hello}")

    assert result.data == {"hello": "Hello world"}
    assert result.errors is None

    # ----------------------------------------------------------------

    result = schema.execute(
        """
    query hello($name: String!) {
        hello(name: $name)
    }
    """,
        variable_values={"name": "WROLD!!1"},
    )

    assert result.data == {"hello": "Hello WROLD!!1"}
    assert result.errors is None
Exemple #2
0
def test_simple_query_with_mandatory_argument():

    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info, name: str) -> str:
        return "Hello {}".format(name)

    # ----------------------------------------------------------------

    result = schema.execute("{hello}")

    assert result.data is None
    assert len(result.errors) == 1
    assert isinstance(result.errors[0], GraphQLError)
    assert result.errors[0].message == (
        "Field 'hello' argument 'name' of type 'String!' "
        "is required, but it was not provided.")

    # ----------------------------------------------------------------

    result = schema.execute(
        """
    query hello($name: String!) {
        hello(name: $name)
    }
    """,
        variable_values={"name": "WROLD!!1"},
    )

    assert result.data == {"hello": "Hello WROLD!!1"}
    assert result.errors is None
def test_basic_schema():
    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info, argument: str = "stranger") -> str:
        return "Hello " + argument

    result = schema.execute("{ hello }")
    assert result.data == {"hello": "Hello stranger"}
    assert result.errors is None

    result = schema.execute('{ hello (argument: "world") }')
    assert result.data == {"hello": "Hello world"}
    assert result.errors is None
def test_nested_objects():

    Baz = Object("Baz")

    @Baz.field("val")
    def resolve_baz_val(root, info) -> str:
        return "BAZ-VALUE!"

    Bar = Object("Bar", {"baz": Baz})

    @Bar.field("baz")
    def resolve_bar_baz(root, info) -> Baz:
        return Baz()

    Foo = Object("Foo", {"bar": Bar})

    @Foo.field("bar")
    def resolve_foo_bar(root, info) -> Bar:
        return Bar()

    Query = Object("Query", {"foo": Foo})

    @Query.field("foo")
    def resolve_query_foo(root, info) -> Foo:
        return Foo()

    schema = Schema(query=Query)

    result = schema.execute("{foo {bar {baz {val}}}}")

    assert result.errors is None
    assert result.data == {"foo": {"bar": {"baz": {"val": "BAZ-VALUE!"}}}}
def test_base_scalars_output():

    Example = Object(
        "Example",
        fields={
            "my_str": str,
            "my_int": int,
            "my_float": float,
            "my_bool": bool,
            "my_id": ID,
        },
    )

    schema = Schema()

    @schema.query.field("example")
    def resolve_example(root, info) -> Example:
        return Example(
            my_str="Some string", my_int=42, my_float=3.14, my_bool=True, my_id="1234"
        )

    result = schema.execute("{ example { myStr, myInt, myFloat, myBool, myId } }")
    assert result.errors is None
    assert result.data == {
        "example": {
            "myStr": "Some string",
            "myInt": 42,
            "myFloat": 3.14,
            "myBool": True,
            "myId": "1234",
        },
    }
Exemple #6
0
def test_input_objects_field_names_are_converted():

    # See issue #13: https://github.com/rshk/pyql/issues/13

    MyInput = InputObject(
        "MyInput",
        fields={
            "some_field_name": str,
        },
    )

    # Need at least one query, for some reason...
    schema = Schema(query=Object("Query", {"q": str}))

    @schema.mutation.field("do_something")
    def resolve_do_something(root, info, obj: MyInput) -> str:
        return obj.some_field_name

    result = schema.execute(
        """
    mutation doSomething($obj: MyInput!) {
        doSomething(obj: $obj)
    }
    """,
        variable_values={"obj": {
            "someFieldName": "HELLO"
        }},
    )

    assert result.errors is None
    assert result.data == {"doSomething": "HELLO"}
Exemple #7
0
def test_field_names_can_be_camelcase_in_python():

    MyInput = InputObject(
        "MyInput",
        fields={
            "someFieldName": str,
        },
    )

    # Need at least one query, for some reason...
    schema = Schema(query=Object("Query", {"q": str}))

    @schema.mutation.field("do_something")
    def resolve_do_something(root, info, obj: MyInput) -> str:
        with pytest.raises(AttributeError):
            obj.some_field_name
        return obj.someFieldName

    result = schema.execute(
        """
    mutation doSomething($obj: MyInput!) {
        doSomething(obj: $obj)
    }
    """,
        variable_values={"obj": {
            "someFieldName": "HELLO"
        }},
    )

    assert result.errors is None
    assert result.data == {"doSomething": "HELLO"}
def test_list_output():
    schema = Schema()

    @schema.query.field("example")
    def resolve_example(root, info) -> typing.List[str]:
        return ["foo", "bar", "baz"]

    result = schema.execute("{example}")

    assert result.errors is None
    assert result.data == {"example": ["foo", "bar", "baz"]}
def test_list_input():
    schema = Schema()

    @schema.query.field("reverse")
    def resolve_reverse(root, info, lst: typing.List[str]) -> typing.List[str]:
        return list(reversed(lst))

    result = schema.execute('{reverse (lst: ["foo", "bar", "baz"])}')

    assert result.errors is None
    assert result.data == {"reverse": ["baz", "bar", "foo"]}
def test_non_null_input_provided():
    schema = Schema()

    @schema.query.field("example")
    def resolve_example(root, info, foo: str) -> bool:
        return foo is not None

    result = schema.execute('{example(foo:"BAR")}')

    assert result.errors is None
    assert result.data == {"example": True}
def test_datetime_input():

    schema = Schema()

    @schema.query.field("format_date")
    def resolve_my_datetime(root, info, dt: datetime) -> str:
        return dt.strftime("%a %b %d, %Y %H:%M")

    result = schema.execute('{ formatDate (dt: "2018-12-11T14:28:00") }')

    assert result.errors is None
    assert result.data == {"formatDate": "Tue Dec 11, 2018 14:28"}
def test_datetime_output():

    schema = Schema()

    @schema.query.field("my_datetime")
    def resolve_my_datetime(root, info) -> datetime:
        return datetime(2018, 12, 11, 14, 28)

    result = schema.execute("{ myDatetime }")

    assert result.errors is None
    assert result.data == {"myDatetime": "2018-12-11T14:28:00"}
Exemple #13
0
def test_create_basic_schema():

    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info) -> str:
        return "Hello world"

    # ----------------------------------------------------------------

    result = schema.execute("{hello}")

    assert result.data == {"hello": "Hello world"}
    assert result.errors is None
Exemple #14
0
def test_input_objects():

    Post = Object(
        "Post",
        fields={
            "id": ID,
            "title": str,
            "body": str,
        },
    )

    PostInput = InputObject(
        "PostInput",
        fields={
            "title": NonNull(str),
            "body": str,
        },
    )

    Query = Object("Query", fields={"dummy": str})
    Mutation = Object("Mutation")

    @Mutation.field("create_post")
    def resolve_create_post(root, info, post: PostInput) -> Post:
        return Post(id="1", title=post.title, body=post.body)

    schema = Schema(query=Query, mutation=Mutation)

    result = schema.execute(
        """
    mutation createPost($post: PostInput!) {
      createPost(post: $post) {
        id, title, body
      }
    }
    """,
        variable_values={"post": {
            "title": "Hello",
            "body": "Hello world"
        }},
    )

    assert result.errors is None
    assert result.data == {
        "createPost": {
            "id": "1",
            "title": "Hello",
            "body": "Hello world",
        }
    }
Exemple #15
0
def test_objects_can_reference_each_other():

    Foo = Object("Foo", {"name": str})
    Bar = Object("Bar", {"name": str})

    @Foo.field("bar")
    def resolve_foo_bar(root, info) -> Bar:
        return Bar(name="{} bar".format(root.name))

    @Bar.field("foo")
    def resolve_bar_foo(root, info) -> Foo:
        return Foo(name="{} foo".format(root.name))

    schema = Schema()

    @schema.query.field("foo")
    def resolve_query_foo(root, info) -> Foo:
        return Foo(name="FOO")

    @schema.query.field("bar")
    def resolve_query_bar(root, info) -> Bar:
        return Bar(name="BAR")

    result = schema.execute("""
    query {
        foo {
            name
            bar {
                name
                foo {
                    name
                }
            }
        }
    }
    """)

    assert result.errors is None
    assert result.data == {
        "foo": {
            "name": "FOO",
            "bar": {
                "name": "FOO bar",
                "foo": {
                    "name": "FOO bar foo"
                }
            },
        }
    }
def test_enum_argument():
    """Accept enum value as field argument"""

    schema = Schema()

    @schema.query.field("episode")
    def resolve_episode(root, info, episode: Episode) -> str:

        episode = Episode(episode)  # FIXME: this needs to happen in caller!

        return ({Episode.NEWHOPE: "A new hope"}).get(episode, "Unknown episode")

    result = schema.execute("{ episode (episode: NEWHOPE) }")
    assert result.errors is None
    assert result.data == {"episode": "A new hope"}

    result = schema.execute("{ episode (episode: FOOBAR) }")

    assert result.errors is not None
    assert [x.message for x in result.errors] == [
        "Expected value of type 'Episode!', found FOOBAR; "
        "'FOOBAR' is not a valid Episode",
    ]
    assert result.data is None
def test_non_null_output_nulled():

    schema = Schema()

    @schema.query.field("example")
    def resolve_example(root, info) -> NonNull(str):
        return None  # Will fail

    result = schema.execute("{example}")

    assert len(result.errors) == 1
    assert result.errors[0].message == (
        "Cannot return null for non-nullable field Query.example."
    )
    assert result.data is None
def test_non_null_input_nulled():
    schema = Schema()

    @schema.query.field("example")
    def resolve_example(root, info, foo: str) -> bool:
        return foo is not None

    result = schema.execute("{example}")

    assert len(result.errors) == 1
    assert result.errors[0].message == (
        "Field 'example' argument 'foo' of type 'String!' "
        "is required, but it was not provided."
    )
    assert result.data is None
def test_resolver_can_return_dict():

    schema = Schema()

    Foo = Object("Foo", {"text": str})

    @schema.query.field("foo")
    def resolve_foo(root, info) -> Foo:
        return {"text": "a"}

    result = schema.execute("""
    { foo { text } }
    """)

    assert result.errors is None
    assert result.data == {"foo": {"text": "a"}}
def test_returning_an_incompatible_object_fails():

    schema = Schema()

    Foo = Object("Foo", {"text": str})
    Spam = namedtuple("Spam", ("spam", ))

    @schema.query.field("foo")
    def resolve_foo(root, info) -> Foo:
        return Spam(spam="SPAM" * 10)

    result = schema.execute("""
    { foo { text } }
    """)

    assert result.data == {"foo": {"text": None}}
    assert result.errors is None
Exemple #21
0
def test_optional_argument_can_be_omitted():
    # This works fine, even with issue #7

    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info, some_arg: str = "DEFAULT") -> str:
        return "Hello {}".format(some_arg)

    # ----------------------------------------------------------------

    result = schema.execute("""
        query {
            hello
        }
        """)

    assert result.errors is None
    assert result.data == {"hello": "Hello DEFAULT"}
def test_resolver_can_return_compatible_object():
    """
    Still a duck.
    """

    schema = Schema()

    Foo = Object("Foo", {"text": str})
    AnotherFoo = namedtuple("AnotherFoo", ("text", ))

    @schema.query.field("foo")
    def resolve_foo(root, info) -> Foo:
        return AnotherFoo(text="a")

    result = schema.execute("""
    { foo { text } }
    """)

    assert result.errors is None
    assert result.data == {"foo": {"text": "a"}}
Exemple #23
0
def test_get_argument_names_from_snake_case():

    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info, some_arg_name: str) -> str:
        return some_arg_name

    # ----------------------------------------------------------------

    result = schema.execute(
        """
        query {
            hello(someArgName: "A VALUE")
        }
        """
    )

    assert result.errors is None
    assert result.data == {"hello": "A VALUE"}
def test_enum_output():
    """Return value from an Enum"""

    Card = Object(
        "Card",
        fields={
            "name": str,
            "color": Color,
        },
    )

    schema = Schema()

    @schema.query.field("random_card")
    def resolve_random_card(root, info) -> Card:
        return Card(name="Hello", color=Color.RED)

    result = schema.execute("{ randomCard { name, color } }")
    assert result.errors is None
    assert result.data == {"randomCard": {"name": "Hello", "color": "RED"}}
Exemple #25
0
def test_schema_fields_are_converted_to_camel_case():

    schema = Schema()

    @schema.query.field("some_field_name")
    def resolve_some_field_name(root, info) -> str:
        return "A VALUE"

    # ----------------------------------------------------------------

    result = schema.execute(
        """
        query  {
            someFieldName
        }
        """
    )

    assert result.errors is None
    assert result.data == {"someFieldName": "A VALUE"}
Exemple #26
0
def test_optional_argument_can_be_none():
    # Test for issue #7 (https://github.com/rshk/pyql/issues/7)

    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info, some_arg: str = None) -> str:
        if some_arg is None:
            return "DEFAULT VALUE"
        return "Hello {}".format(some_arg)

    # ----------------------------------------------------------------

    result = schema.execute("""
        query {
            hello
        }
        """)

    assert result.errors is None
    assert result.data == {"hello": "DEFAULT VALUE"}
Exemple #27
0
def test_arguments_are_converted_to_snake_case():
    # Test for issue #5 (https://github.com/rshk/pyql/issues/5)

    schema = Schema()

    @schema.query.field("hello")
    def resolve_hello(root, info, some_arg_name: str) -> str:
        return some_arg_name

    # ----------------------------------------------------------------

    result = schema.execute(
        """
        query ($arg: String!) {
            hello(someArgName: $arg)
        }
        """,
        variable_values={"arg": "IT WORKS"},
    )

    assert result.errors is None
    assert result.data == {"hello": "IT WORKS"}
Exemple #28
0
def test_omitted_fields_are_filled_with_none():

    schema = Schema()

    MyObj = Object(
        "MyObj",
        fields={
            "foo": str,
            "bar": str,
        },
    )

    @schema.query.field("my_obj")
    def resolve_my_obj(root, info) -> MyObj:
        return MyObj(foo="FOO")

    # ----------------------------------------------------------------

    result = schema.execute("{ myObj { foo, bar } }")

    assert result.errors is None
    assert result.data == {"myObj": {"foo": "FOO", "bar": None}}
Exemple #29
0
def test_schema_with_nested_objects():

    schema = Schema()

    Post = Object(
        "Post",
        fields={
            "title": str,
            "body": str,
        },
    )

    @schema.query.field("post")
    def resolve_posts(root, info) -> Post:
        return Post(title="One", body="First post")

    # ----------------------------------------------------------------

    result = schema.execute("{post {title, body}}")

    assert result.data == {"post": {"title": "One", "body": "First post"}}
    assert result.errors is None
def test_mutation():

    # ...graphql-core forces us to have at least a query
    Query = Object("Query", fields={"foo": str})

    Mutation = Object("Mutation")

    @Mutation.field("example")
    def resolve_mutate_something(root, info, text: str) -> bool:
        return True

    schema = Schema(query=Query, mutation=Mutation)

    result = schema.execute(
        """
    mutation foo {
        example(text: "HEY")
    }
    """
    )

    assert result.errors is None
    assert result.data == {"example": True}