示例#1
0
def test_Schema_includes_nested_input_objects_in_the_map():
    NestedInputObject = InputObjectType("NestedInputObject",
                                        [InputField("value", String)])
    SomeInputObject = InputObjectType(
        "SomeInputObject", [InputField("nested", NestedInputObject)])
    SomeMutation = ObjectType(
        "SomeMutation",
        [
            Field(
                "mutateSomething",
                BlogArticle,
                [Argument("input", SomeInputObject)],
            )
        ],
    )
    SomeSubscription = ObjectType(
        "SomeSubscription",
        [
            Field(
                "subscribeToSomething",
                BlogArticle,
                [Argument("input", SomeInputObject)],
            )
        ],
    )

    schema = Schema(
        BlogQuery,
        mutation_type=SomeMutation,
        subscription_type=SomeSubscription,
    )

    assert schema.types.get("NestedInputObject") is NestedInputObject
示例#2
0
def test_string_field_with_multiple_args():
    schema = _single_field_schema(
        String, args=[Argument("argOne", Int),
                      Argument("argTwo", String)])
    assert print_schema(schema, indent="    ") == dedent("""
        type Query {
            singleField(argOne: Int, argTwo: String): String
        }
        """)
示例#3
0
def test_reject_object_fields_with_incorrectly_typed_interface_argument():
    iface = InterfaceType("IFace",
                          [Field("f", String, [Argument("arg", String)])])
    obj = ObjectType("Obj", [Field("f", String, [Argument("arg", Int)])],
                     interfaces=[iface])
    schema = _single_type_schema(obj)
    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert ('Interface field argument "IFace.f.arg" expects '
            'type "String" but "Obj.f.arg" is type "Int"'
            in str(exc_info.value))
示例#4
0
 def schema(self) -> Schema:
     return _single_type_schema(
         ObjectType(
             "Object",
             [
                 Field(
                     "field",
                     String,
                     [
                         Argument("a", String),
                         Argument("b", NonNullType(String)),
                         Argument("c", String, default_value="c"),
                     ],
                 )
             ],
         ))
示例#5
0
def test_string_field_with_int_arg():
    schema = _single_field_schema(String, args=[Argument("argOne", Int)])
    assert print_schema(schema, indent="    ") == dedent("""
        type Query {
            singleField(argOne: Int): String
        }
        """)
示例#6
0
async def test_forwarded_resolver_arguments(mocker, assert_execution):

    resolver = mocker.Mock(return_value="foo")
    context = mocker.Mock()
    root = mocker.Mock()

    field = Field("test", String, [Argument("arg", String)], resolver=resolver)
    query_type = ObjectType("Test", [field])
    doc = parse("query ($var: String) { result: test(arg: $var) }")
    schema = Schema(query_type)

    result = assert_execution(
        schema,
        doc,
        context_value=context,
        initial_value=root,
        variables={"var": 123},
    )

    if isawaitable(result):
        await result

    (parent_value, ctx, info), args = resolver.call_args

    assert info.field_definition is field
    assert info.parent_type is query_type
    assert info.path == ["result"]
    assert info.variables == {"var": "123"}
    assert info.schema is schema

    assert ctx is context
    assert parent_value is root

    assert args == {"arg": "123"}
示例#7
0
def test_accept_field_args_with_correct_names():
    schema = _single_type_schema(
        ObjectType(
            "SomeObject",
            [Field("field", String, [Argument("goodArg", String)])],
        ))
    schema.validate()
示例#8
0
async def test_get_directive_arguments_missing(mocker):
    CustomDirective = Directive(
        "custom", ["FIELD"],
        [Argument("a", String), Argument("b", Int)])

    resolver = mocker.Mock(return_value=42)

    execute(
        Schema(test_type, directives=[CustomDirective]),
        parse("{ a }"),
        initial_value=_obj(a=resolver),
    )

    (_, info), _ = resolver.call_args

    assert info.get_directive_arguments("custom") is None
示例#9
0
def test_accept_input_type():
    schema = _single_type_schema(
        ObjectType(
            "Object",
            [Field("field", String, [Argument("arg", SomeInputObject)])],
        ))
    schema.validate()
示例#10
0
async def test_get_directive_arguments_unknown(mocker):
    CustomDirective = Directive(
        "custom", ["FIELD"],
        [Argument("a", String), Argument("b", Int)])

    resolver = mocker.Mock(return_value=42)

    execute(
        Schema(test_type, directives=[CustomDirective]),
        parse('{ a @custom(a: "foo", b: 42) }'),
        initial_value=_obj(a=resolver),
    )

    (_, info), _ = resolver.call_args

    with pytest.raises(KeyError):
        info.get_directive_arguments("foo")
示例#11
0
def test_string_field_with_int_arg_with_null_default_value():
    schema = _single_field_schema(
        String, args=[Argument("argOne", Int, default_value=None)])
    assert print_schema(schema, indent="    ") == dedent("""
        type Query {
            singleField(argOne: Int = null): String
        }
        """)
示例#12
0
def test_accept_object_which_implements_interface_along_with_nullable_args():
    schema = _single_type_schema(
        ObjectType(
            "SomeObject",
            [Field("f", String, [Argument("arg", String)])],
            interfaces=[SomeInterface],
        ))
    schema.validate()
示例#13
0
def test_reject_input_object_with_no_field():
    arg = Argument("badArg", InputObjectType("BadInput", []))
    schema = _single_type_schema(
        ObjectType("BadObject", [Field("f", String, [arg])]))
    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert 'Type "BadInput" must define at least one field' in str(
        exc_info.value)
示例#14
0
def test_reject_argument_with_non_input_type(type_):
    schema = _single_type_schema(
        ObjectType("BadObject",
                   [Field("f", String, [Argument("badArg", type_)])]))
    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert ('Expected input type for argument "badArg" on "BadObject.f" '
            'but got "%s"' % type_) in str(exc_info.value)
def test_provided_unknown_variable_without_default_non_nullable():
    arg = Argument("foo", NonNullType(Int))
    field = Field("test", Int, [arg])
    node = _test_node(_var("bar"))
    with pytest.raises(CoercionError) as exc_info:
        coerce_argument_values(field, node)
    assert str(exc_info.value) == (
        'Argument "foo" of required type "Int!" was provided the missing '
        'variable "$bar"'
    )
示例#16
0
def schema() -> Schema:
    Object = InterfaceType("Object", fields=[Field("id", NonNullType(ID))])

    Person = ObjectType(
        "Person",
        fields=[
            Field("id", NonNullType(ID)),
            Field("name", NonNullType(String)),
            Field("pets", NonNullType(ListType(lambda: Animal))),
        ],
        interfaces=[Object],
    )

    Animal = ObjectType(
        "Animal",
        fields=[
            Field("id", NonNullType(ID)),
            Field("name", NonNullType(String)),
            Field("owner", Person),
        ],
        interfaces=[Object],
    )

    LivingBeing = UnionType("LivingBeing", [Person, Animal])

    CreatePersonInput = InputObjectType(
        "CreatePersonInput",
        [InputField("id", ID),
         InputField("name", NonNullType(String))],
    )

    return Schema(
        query_type=ObjectType(
            "Query",
            fields=[
                Field("person", Person, args=[Argument("id", ID)]),
                Field("pet", Animal, args=[Argument("id", ID)]),
                Field("living_being", LivingBeing, args=[Argument("id", ID)]),
            ],
        ),
        mutation_type=ObjectType(
            "Mutation", fields=[Field("createPerson", CreatePersonInput)]),
    )
def test_missing_non_nullable_arg_without_default():
    arg = Argument("foo", NonNullType(Int))
    field = Field("test", Int, [arg])
    node = _test_node()
    with pytest.raises(CoercionError) as exc_info:
        coerce_argument_values(field, node)
    assert (
        str(exc_info.value)
        == 'Argument "foo" of required type "Int!" was not provided'
    )
def test_provided_invalid_value():
    arg = Argument("foo", Int)
    field = Field("test", Int, [arg])
    node = _test_node(_ast.StringValue(value="foo"))
    with pytest.raises(CoercionError) as exc_info:
        assert coerce_argument_values(field, node)
    assert str(exc_info.value) == (
        'Argument "foo" of type "Int" was provided invalid value "foo" '
        "(Invalid literal StringValue)"
    )
示例#19
0
def test_string_field_with_string_arg_with_default_value():
    schema = _single_field_schema(
        String,
        args=[Argument("argOne", String, default_value="tes\t de\fault")],
    )
    assert print_schema(schema, indent="    ") == dedent("""
        type Query {
            singleField(argOne: String = "tes\\t de\\fault"): String
        }
        """)
示例#20
0
def test_reject_object_fields_with_missing_interface_argument():
    iface = InterfaceType("IFace",
                          [Field("f", String, [Argument("arg", String)])])
    obj = ObjectType("Obj", [Field("f", String)], interfaces=[iface])
    schema = _single_type_schema(obj)
    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert ('Interface field argument "IFace.f.arg" is not provided by "Obj.f"'
            in str(exc_info.value))
示例#21
0
def test_reject_input_type_with_no_fields():
    EmptyInput = InputObjectType("EmptyInput", [])
    schema = _single_type_schema(
        ObjectType("Object",
                   [Field("field", String, [Argument("arg", EmptyInput)])]))

    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert 'Type "EmptyInput" must define at least one field' in str(
        exc_info.value)
示例#22
0
def test_reject_field_args_with_incorrect_names():
    schema = _single_type_schema(
        ObjectType(
            "SomeObject",
            [Field("field", String, [Argument("bad-arg", String)])],
        ))

    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert 'Invalid name "bad-arg"' in str(exc_info.value)
示例#23
0
def test_reject_input_type_with_incorectly_typed_fields():
    BadInput = InputObjectType("BadInput", [InputField("f", SomeObject)])
    schema = _single_type_schema(
        ObjectType("Object",
                   [Field("field", String, [Argument("arg", BadInput)])]))

    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert ('Expected input type for field "f" on "BadInput" '
            'but got "SomeObject"' in str(exc_info.value))
示例#24
0
async def test_get_directive_arguments_known_with_variables(mocker):
    CustomDirective = Directive(
        "custom", ["FIELD"],
        [Argument("a", String), Argument("b", Int)])

    resolver = mocker.Mock(return_value=42)

    execute(
        Schema(test_type, directives=[CustomDirective]),
        parse('query ($b: Int!) { a @custom(a: "foo", b: $b) }'),
        initial_value=_obj(a=resolver),
        variables={"b": 42},
    )

    (_, info), _ = resolver.call_args

    assert info.get_directive_arguments("custom") == {
        "a": "foo",
        "b": 42,
    }
def test_custom_python_name_in_input_object():
    arg = Argument(
        "foo",
        NonNullType(
            InputObjectType(
                "Foo",
                [InputField("field", NonNullType(Int), python_name="value")],
            )
        ),
    )
    field = Field("test", Int, [arg])
    node = _test_node(parse_value("{ field: 42 }"))
    assert coerce_argument_values(field, node) == {"foo": {"value": 42}}
示例#26
0
def test_input_type():
    Input = InputObjectType("InputType", [InputField("int", Int)])
    Query = ObjectType("Query",
                       [Field("str", String, [Argument("argOne", Input)])])
    assert print_schema(Schema(Query), indent="    ") == dedent("""
        input InputType {
            int: Int
        }

        type Query {
            str(argOne: InputType): String
        }
        """)
示例#27
0
def test_reject_object_which_implements_interface_along_with_required_args():
    iface = InterfaceType("IFace", [Field("f", String)])
    schema = _single_type_schema(
        ObjectType(
            "SomeObject",
            [Field("f", String, [Argument("arg", NonNullType(String))])],
            interfaces=[iface],
        ))
    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert ('Object field argument "SomeObject.f.arg" is of required '
            'type "String!" but is not provided by interface field "IFace.f"'
            ) in str(exc_info.value)
示例#28
0
def test_custom_directive():
    directive = Directive(
        "customDirective",
        locations=["FIELD"],
        args=[Argument("argOne", String)],
    )
    schema = Schema(ObjectType("Query", [Field("foo", String)]),
                    directives=[directive])
    assert print_schema(schema, indent="    ") == dedent("""
        directive @customDirective(argOne: String) on FIELD

        type Query {
            foo: String
        }
        """)
示例#29
0
async def test_raises_on_missing_subscription_resolver(starwars_schema):
    schema = subscription_schema(
        Field(
            "counter",
            NonNullType(Int),
            args=[Argument("delay", NonNullType(Float))],
            resolver=lambda event, *_, **__: event,
        )
    )

    with pytest.raises(RuntimeError):
        subscribe(
            schema,
            parse("subscription { counter(delay: 0.001) }"),
            runtime=AsyncIORuntime(),
        )
示例#30
0
async def test_raises_on_unsupported_runtime():
    schema = subscription_schema(
        Field(
            "counter",
            NonNullType(Int),
            args=[Argument("delay", NonNullType(Float))],
            subscription_resolver=lambda *_, delay: AsyncCounter(delay, 10),
            resolver=lambda event, *_, **__: event,
        )
    )

    with pytest.raises(RuntimeError):
        subscribe(
            schema,
            parse("subscription { counter(delay: 0.001) }"),
            runtime=BlockingRuntime(),  # type: ignore
        )