示例#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_InputObject_with_custom_python_name():
    _test(
        {"someField": 3},
        InputObjectType(
            "TestInputObject",
            [InputField("someField", Int, python_name="some_field")],
        ),
        {"some_field": 3},
    )
示例#3
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)
示例#4
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)
示例#5
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))
示例#6
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
        }
        """)
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}}
示例#8
0
def test_accept_input_object_with_input_type(type_):
    schema = _single_type_schema(
        ObjectType(
            "GoodObject",
            [
                Field(
                    "f",
                    String,
                    [
                        Argument(
                            "goodArg",
                            InputObjectType("GoodInput",
                                            [InputField("f", type_)]),
                        )
                    ],
                )
            ],
        ))
    schema.validate()
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)]),
    )
示例#10
0
def test_reject_input_object_with_non_input_type(type_):
    schema = _single_type_schema(
        ObjectType(
            "BadObject",
            [
                Field(
                    "f",
                    String,
                    [
                        Argument(
                            "badArg",
                            InputObjectType("BadInput",
                                            [InputField("f", type_)]),
                        )
                    ],
                )
            ],
        ))
    with pytest.raises(SchemaError) as exc_info:
        validate_schema(schema)

    assert ('Expected input type for field "f" on "BadInput" '
            'but got "%s"' % type_) in str(exc_info.value)
示例#11
0
        ),
        ("FOO", ListType(String), _ast.StringValue(value="FOO")),
    ],
)
def test_ast_node_from_value_with_list_types(value, input_type, expected):
    if isinstance(expected, Exception):
        with pytest.raises(type(expected)) as exc_info:
            ast_node_from_value(value, input_type)
        assert str(expected) == str(exc_info.value)
    else:
        assert ast_node_from_value(value, input_type) == expected


InputObject = InputObjectType(
    "MyInputObj",
    [InputField("foo", Float),
     InputField("bar", NonNullType(Enum))],
)


@pytest.mark.parametrize(
    "value, expected",
    [
        (
            {
                "foo": 3,
                "bar": "HELLO"
            },
            _ast.ObjectValue(fields=[
                _ast.ObjectField(
                    name=_ast.Name(value="foo"),
示例#12
0
def schema():

    Being = InterfaceType(
        "Being", [Field("name", String, [Argument("surname", Boolean)])])

    Pet = InterfaceType(
        "Pet", [Field("name", String, [Argument("surname", Boolean)])])

    Canine = InterfaceType(
        "Canine", [Field("name", String, [Argument("surname", Boolean)])])

    DogCommand = EnumType(
        "DogCommand",
        [EnumValue("SIT", 0),
         EnumValue("HEEL", 1),
         EnumValue("DOWN", 2)],
    )

    FurColor = EnumType(
        "FurColor",
        [
            EnumValue("BROWN", 0),
            EnumValue("BLACK", 1),
            EnumValue("TAN", 2),
            EnumValue("SPOTTED", 3),
            EnumValue("NO_FUR", None),
            EnumValue("UNKNOWN", -1),
        ],
    )

    Dog = ObjectType(
        "Dog",
        [
            Field("name", String, args=[Argument("surname", Boolean)]),
            Field("nickname", String),
            Field("barkVolume", Int),
            Field("barks", Boolean),
            Field("doesKnowCommand", Boolean,
                  [Argument("dogCommand", DogCommand)]),
            Field(
                "isHousetrained",
                Boolean,
                [Argument("atOtherHomes", Boolean, True)],
            ),
            Field(
                "isAtLocation",
                Boolean,
                [Argument("x", Int), Argument("y", Int)],
            ),
        ],
        [Being, Pet, Canine],
    )

    Cat = ObjectType(
        "Cat",
        [
            Field("name", String, args=[Argument("surname", Boolean)]),
            Field("nickname", String),
            Field("meowVolume", Int),
            Field("meows", Boolean),
            Field("furColor", FurColor),
        ],
        [Being, Pet],
    )

    CatOrDog = UnionType("CatOrDog", [Dog, Cat])

    Intelligent = InterfaceType("Intelligent", [Field("iq", Int)])

    Human = ObjectType(
        "Human",
        lambda: [
            Field("name", String, args=[Argument("surname", Boolean)]),
            Field("iq", Int),
            Field("pets", ListType(Pet)),
            Field("relatives", ListType(Human)),
        ],
        [Being, Intelligent],
    )

    Alien = ObjectType(
        "Alien",
        [
            Field("name", String, args=[Argument("surname", Boolean)]),
            Field("iq", Int),
            Field("numEyes", Int),
        ],
        [Being, Intelligent],
    )

    DogOrHuman = UnionType("DogOrHuman", [Dog, Human])

    HumanOrAlien = UnionType("HumanOrAlien", [Human, Alien])

    ComplexInput = InputObjectType(
        "ComplexInput",
        [
            InputField("requiredField", NonNullType(Boolean)),
            InputField(
                "nonNullField", NonNullType(Boolean), default_value=False),
            InputField("intField", Int),
            InputField("stringField", String),
            InputField("booleanField", Boolean),
            InputField("stringListField", ListType(String)),
        ],
    )

    ComplicatedArgs = ObjectType(
        "ComplicatedArgs",
        [
            Field("intArgField", String, [Argument("intArg", Int)]),
            Field(
                "nonNullIntArgField",
                String,
                [Argument("nonNullIntArg", NonNullType(Int))],
            ),
            Field("stringArgField", String, [Argument("stringArg", String)]),
            Field("booleanArgField", String,
                  [Argument("booleanArg", Boolean)]),
            Field("enumArgField", String, [Argument("enumArg", FurColor)]),
            Field("floatArgField", String, [Argument("floatArg", Float)]),
            Field("idArgField", String, [Argument("idArg", ID)]),
            Field(
                "stringListArgField",
                String,
                [Argument("stringListArg", ListType(String))],
            ),
            Field(
                "stringListNonNullArgField",
                String,
                [
                    Argument("stringListNonNullArg",
                             ListType(NonNullType(String)))
                ],
            ),
            Field(
                "complexArgField",
                String,
                [Argument("complexArg", ComplexInput)],
            ),
            Field(
                "multipleReqs",
                String,
                [
                    Argument("req1", NonNullType(Int)),
                    Argument("req2", NonNullType(Int)),
                ],
            ),
            Field(
                "nonNullFieldWithDefault",
                String,
                [Argument("arg", NonNullType(Int), default_value=0)],
            ),
            Field(
                "multipleOpts",
                String,
                [Argument("opt1", Int, 0),
                 Argument("opt2", Int, 0)],
            ),
            Field(
                "multipleOptAndReq",
                String,
                [
                    Argument("req1", NonNullType(Int)),
                    Argument("req2", NonNullType(Int)),
                    Argument("opt1", Int, 0),
                    Argument("opt2", Int, 0),
                ],
            ),
        ],
    )

    def _invalid(*args, **kwargs):
        raise ValueError("Invalid scalar is always invalid")

    def _stringify(value):
        return str(value)

    InvalidScalar = ScalarType("Invalid", _stringify, _invalid, _invalid)
    AnyScalar = ScalarType("Any", _stringify, lambda x: x)  # type: ScalarType

    return Schema(
        ObjectType(
            "QueryRoot",
            [
                Field("human", Human, [Argument("id", ID)]),
                Field("alien", Alien),
                Field("dog", Dog),
                Field("cat", Cat),
                Field("pet", Pet),
                Field("catOrDog", CatOrDog),
                Field("dogOrHuman", DogOrHuman),
                Field("humanOrAlien", HumanOrAlien),
                Field("humanOrAlien", HumanOrAlien),
                Field("complicatedArgs", ComplicatedArgs),
                Field("invalidArg", String, [Argument("arg", InvalidScalar)]),
                Field("anydArg", String, [Argument("arg", AnyScalar)]),
            ],
        ),
        types=[Cat, Dog, Human, Alien],
        directives=[
            Directive("onQuery", ["QUERY"]),
            Directive("onMutation", ["MUTATION"]),
            Directive("onSubscription", ["SUBSCRIPTION"]),
            Directive("onField", ["FIELD"]),
            Directive("onFragmentDefinition", ["FRAGMENT_DEFINITION"]),
            Directive("onFragmentSpread", ["FRAGMENT_SPREAD"]),
            Directive("onInlineFragment", ["INLINE_FRAGMENT"]),
            Directive("onSchema", ["SCHEMA"]),
            Directive("onScalar", ["SCALAR"]),
            Directive("onObject", ["OBJECT"]),
            Directive("onFieldDefinition", ["FIELD_DEFINITION"]),
            Directive("onArgumentDefinition", ["ARGUMENT_DEFINITION"]),
            Directive("onInterface", ["INTERFACE"]),
            Directive("onUnion", ["UNION"]),
            Directive("onEnum", ["ENUM"]),
            Directive("onEnumValue", ["ENUM_VALUE"]),
            Directive("onInputObject", ["INPUT_OBJECT"]),
            Directive("onInputFieldDefinition", ["INPUT_FIELD_DEFINITION"]),
        ],
    )
示例#13
0
def test_it_correctly_updates_references():
    arg_type = InputObjectType("Bar", [InputField("a", Int)])
    schema_with_args = Schema(
        query_type=ObjectType(
            "Query",
            [
                Field(
                    "foo",
                    ObjectType("Foo", [Field("a", Int)]),
                    [Argument("bar", arg_type)],
                )
            ],
        ),
        directives=[Directive("baz", ["FIELD"], [Argument("bar", arg_type)])],
    )

    update_schema = extend_schema(
        schema_with_args,
        """
        extend input Bar {
            b: String
        }

        extend type Foo {
            b: String
        }
        """,
    )

    assert update_schema.to_string() == dedent("""
        directive @baz(bar: Bar) on FIELD

        input Bar {
            a: Int
            b: String
        }

        type Foo {
            a: Int
            b: String
        }

        type Query {
            foo(bar: Bar): Foo
        }
        """)

    query_type = cast(ObjectType, update_schema.get_type("Query"))
    field_type = query_type.field_map["foo"].type
    root_field_type = update_schema.get_type("Foo")

    assert root_field_type is field_type

    field_arg_type = query_type.field_map["foo"].argument_map["bar"].type
    directive_arg_type = (cast(
        Directive,
        update_schema.directives.get("baz")).argument_map["bar"].type)
    root_arg_type = update_schema.get_type("Bar")

    assert field_arg_type is root_arg_type
    assert directive_arg_type is root_arg_type
示例#14
0
    InputField,
    InputObjectType,
    Int,
    InterfaceType,
    ListType,
    ObjectType,
    Schema,
    String,
)

Interface = InterfaceType("Interface", [Field("fieldName", String)])

Implementing = ObjectType("Object", [Field("fieldName", String)],
                          interfaces=[Interface])

DirInput = InputObjectType("DirInput", [InputField("field", String)])

WrappedDirInput = InputObjectType("WrappedDirInput",
                                  [InputField("field", String)])

Dir = Directive(
    "dir",
    ["OBJECT"],
    [
        Argument("arg", DirInput),
        Argument("argList", ListType(WrappedDirInput))
    ],
)

BlogImage = ObjectType(
    "Image", [Field("url", String),
示例#15
0
pytestmark = pytest.mark.asyncio


def _complex_parse(value):
    if value == "SerializedValue":
        return "DeserializedValue"
    raise ValueError(value)


ComplexScalar = ScalarType("ComplexScalar", _complex_parse, _complex_parse)

TestInputObject = InputObjectType(
    "TestInputObject",
    [
        InputField("a", String),
        InputField("b", ListType(String)),
        InputField("c", NonNullType(String)),
        InputField("d", ComplexScalar),
    ],
)

TestNestedInputObject = InputObjectType(
    "TestNestedInputObject",
    [
        InputField("na", NonNullType(TestInputObject)),
        InputField("nb", NonNullType(String)),
    ],
)


def _inspect(name):
示例#16
0
def test_Enum_for_a_known_enum_names():
    _test("FOO", Enum, "InternalFoo")
    _test("BAR", Enum, 123456789)


def test_Enum_raises_for_misspelled_enum_value():
    _test("foo", Enum, None, "Invalid name foo for enum TestEnum")


def test_Enum_raises_for_incorrect_value_type():
    _test(123, Enum, None, "Expected type TestEnum")


Input = InputObjectType(
    "TestInputObject",
    [InputField("foo", NonNullType(Int)), InputField("bar", Int)],
)


def test_InputObject_for_valid_input():
    _test({"foo": 123}, Input, {"foo": 123})


def test_InputObject_raises_for_non_dict_input():
    _test(123, Input, None, "Expected type TestInputObject to be an object")


def test_InputObject_raises_for_invalid_field():
    _test(
        {"foo": "abc"},
        Input,
示例#17
0
    serialize=lambda a: None,
    parse=lambda a: None,
    parse_literal=lambda a, **k: None,
)  # type: ScalarType

SomeObject = ObjectType("SomeObject", [Field("f", String)])

IncompleteObject = ObjectType("IncompleteObject", [])

SomeUnion = UnionType("SomeUnion", [SomeObject])

SomeInterface = InterfaceType("SomeInterface", [Field("f", String)])

SomeEnum = EnumType("SomeEnum", [EnumValue("ONLY")])

SomeInputObject = InputObjectType(
    "SomeInputObject", [InputField("val", String, default_value="hello")])


def _type_modifiers(t):
    return [t, ListType(t), NonNullType(t), NonNullType(ListType(t))]


def _with_modifiers(types):
    out = []  # type: List[GraphQLType]
    for t in types:
        out.extend(_type_modifiers(t))
    return out


output_types = _with_modifiers(
    [String, SomeScalar, SomeEnum, SomeObject, SomeUnion, SomeInterface])