Example #1
0
def test_when_field_value_in_input_object_in_input_object_is_not_set_then_default_is_used():
    Input = schema.InputObjectType(
        "Input",
        fields=(
            schema.input_field("field0", type=schema.Int, default=42),
        ),
    )
    OuterInput = schema.InputObjectType(
        "OuterInput",
        fields=(
            schema.input_field("value", type=Input),
        ),
    )

    Root = g.ObjectType(
        "Root",
        fields=(
            g.field("one", type=g.Int, params=[
                g.param("arg", type=OuterInput),
            ]),
        ),
    )

    graphql_query = """
        query {
            one(arg: {value: {}})
        }
    """

    object_query = _document_text_to_graph_query(graphql_query, query_type=Root)
    assert_that(object_query.field_queries[0].args.arg, has_attrs(
        value=has_attrs(
            field0=42,
        ),
    ))
def test_when_there_are_fewer_edges_than_requested_then_all_edges_are_fetched(
):
    graph = create_graph({
        42: "Leave it to Psmith",
    })

    result = graph.resolve(
        Query(
            g.key(
                "books",
                Query.fields.books_connection(
                    Query.fields.books_connection.params.first(2),
                    g.key(
                        "edges",
                        BooksConnection.fields.edges(
                            g.key(
                                "node",
                                BookEdge.fields.node(
                                    g.key("title",
                                          Book.fields.title()), )), )),
                    g.key(
                        "page_info",
                        BooksConnection.fields.page_info(
                            g.key("has_next_page",
                                  PageInfo.fields.has_next_page()), )),
                )), ))

    assert_that(
        result.books,
        has_attrs(
            edges=contains_exactly(
                has_attrs(node=has_attrs(title="Leave it to Psmith")), ),
            page_info=has_attrs(has_next_page=False),
        ))
def test_when_there_are_no_edges_then_connection_is_empty():
    graph = create_graph({})

    result = graph.resolve(
        Query(
            g.key(
                "books",
                Query.fields.books_connection(
                    Query.fields.books_connection.params.first(2),
                    g.key(
                        "edges",
                        BooksConnection.fields.edges(
                            g.key(
                                "node",
                                BookEdge.fields.node(
                                    g.key("title",
                                          Book.fields.title()), )), )),
                    g.key(
                        "page_info",
                        BooksConnection.fields.page_info(
                            g.key("end_cursor", PageInfo.fields.end_cursor()),
                            g.key("has_next_page",
                                  PageInfo.fields.has_next_page()),
                        )),
                )), ))

    assert_that(
        result.books,
        has_attrs(
            edges=contains_exactly(),
            page_info=has_attrs(end_cursor=None, has_next_page=False),
        ))
def test_nodes_can_be_fetched_directly():
    graph = create_graph({
        42: "Leave it to Psmith",
        43: "The Gentleman's Guide to Vice and Virtue",
        44: "Catch-22",
    })

    result = graph.resolve(
        Query(
            g.key(
                "books",
                Query.fields.books_connection(
                    Query.fields.books_connection.params.first(2),
                    g.key(
                        "nodes",
                        BooksConnection.fields.nodes(
                            g.key("title", Book.fields.title()), )),
                    g.key(
                        "page_info",
                        BooksConnection.fields.page_info(
                            g.key("has_next_page",
                                  PageInfo.fields.has_next_page()), )),
                )), ))

    assert_that(
        result.books,
        has_attrs(nodes=contains_exactly(
            has_attrs(title="Leave it to Psmith"),
            has_attrs(title="The Gentleman's Guide to Vice and Virtue"),
        ), ))
Example #5
0
def test_can_recursively_resolve():
    Root = g.ObjectType(
        "Root",
        fields=lambda: [
            g.field("books", type=g.ListType(Book)),
        ],
    )

    Book = g.ObjectType(
        "Book",
        fields=lambda: [
            g.field("title", type=g.String),
        ],
    )

    @g.resolver(Root)
    def resolve_root(graph, query):
        return query.create_object(iterables.to_dict(
            (field_query.key, graph.resolve(field_query.type_query))
            for field_query in query.field_queries
        ))

    @g.resolver(g.ListType(Book))
    def resolve_book(graph, query):
        books = [
            dict(title="Leave it to Psmith"),
            dict(title="Pericles, Prince of Tyre"),
        ]
        return [
            query.element_query.create_object(iterables.to_dict(
                (field_query.key, book[field_query.field.name])
                for field_query in query.element_query.field_queries
            ))
            for book in books
        ]

    resolvers = [resolve_root, resolve_book]

    query = Root(
        g.key("books", Root.fields.books(
            g.key("title", Book.fields.title()),
        )),
    )
    result = g.create_graph(resolvers).resolve(query)

    assert_that(result, has_attrs(
        books=contains_exactly(
            has_attrs(title="Leave it to Psmith"),
            has_attrs(title="Pericles, Prince of Tyre"),
        ),
    ))
Example #6
0
def test_can_get_fields_backed_by_expressions():
    Base = sqlalchemy.ext.declarative.declarative_base()

    class BookRow(Base):
        __tablename__ = "book"

        c_id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
        c_title = sqlalchemy.Column(sqlalchemy.Unicode, nullable=False)

    engine = sqlalchemy.create_engine("sqlite:///:memory:")

    Base.metadata.create_all(engine)

    session = sqlalchemy.orm.Session(engine)
    session.add(BookRow(c_title="Leave it to Psmith"))
    session.add(BookRow(c_title="Pericles, Prince of Tyre"))
    session.commit()

    Book = g.ObjectType(
        "Book",
        fields=lambda: [
            g.field("title", type=g.String),
        ],
    )

    book_resolver = gsql.sql_table_resolver(
        Book,
        BookRow,
        fields={
            Book.fields.title: gsql.expression(BookRow.c_title),
        },
    )

    resolvers = [book_resolver]

    query = gsql.select(
        g.ListType(Book)(g.key("title", Book.fields.title()), ))
    graph_definition = g.define_graph(resolvers)
    graph = graph_definition.create_graph({
        sqlalchemy.orm.Session: session,
    })
    result = graph.resolve(query)

    assert_that(
        result,
        contains_exactly(
            has_attrs(title="Leave it to Psmith", ),
            has_attrs(title="Pericles, Prince of Tyre", ),
        ))
Example #7
0
def matches_when_properties_all_match():
    matcher = has_attrs(
        username=equal_to("bob"),
        email_address=equal_to("*****@*****.**"),
    )

    assert_equal(matched(), matcher.match(User("bob", "*****@*****.**")))
def test_can_get_scalar_from_root():
    Root = g.ObjectType(
        "Root",
        fields=[
            g.field("one", type=g.Int),
            g.field("two", type=g.Int),
        ],
    )

    @g.resolver(Root)
    def resolve_root(graph, query):
        values = dict(
            one=1,
            two=2,
        )

        return query.create_object(
            iterables.to_dict((field_query.key, values[field_query.field.name])
                              for field_query in query.fields))

    resolvers = [resolve_root]

    query = Root(g.key("value", Root.fields.one()), )
    result = g.create_graph(resolvers).resolve(query)

    assert_that(result, has_attrs(value=1))
Example #9
0
    def test_diff_with_render_true_renders_content(self):
        # TODO: handle rendering when last_render is out of date
        content = dedent("""
            --- old
            +++ new

            @@ -1,2 +1,2 @@
            -x = 1
            +x = 2
             print(x)

        """)
        element = parser.Diff(
            name="example",
            content=content,
            render=True,
        )
        state = {
            "example": compiler.Code(
                language="python",
                content="x = 1\nprint(x)\n",
                pending_lines=(),
            ),
        }

        new_state, new_element = _execute(state, element)
        assert_that(new_element, is_literal_block(content=content))
        assert_that(new_state["example"], has_attrs(pending_lines=is_sequence()))
    def test_object_builder_getters_access_value_directly(self):
        User = g.ObjectType("User",
                            fields=(
                                g.field("name", type=g.String),
                                g.field("email_address", type=g.String),
                            ))

        object_builder = g.create_object_builder(
            User(
                g.key("n", User.fields.name()),
                g.key("e", User.fields.email_address()),
            ))

        @object_builder.getter(User.fields.name)
        def resolve_name(user):
            return user["name"]

        @object_builder.getter(User.fields.email_address)
        def resolve_email_address(user):
            return user["emailAddress"]

        result = object_builder({
            "name": "Bob",
            "emailAddress": "*****@*****.**"
        })
        assert_that(result, has_attrs(
            n="Bob",
            e="*****@*****.**",
        ))
def matches_when_properties_all_match():
    matcher = has_attrs(
        username=equal_to("bob"),
        email_address=equal_to("*****@*****.**"),
    )
    
    assert_equal(matched(), matcher.match(User("bob", "*****@*****.**")))
Example #12
0
def test_when_field_value_in_input_object_in_list_is_not_set_then_default_is_used(
):
    Input = schema.InputObjectType(
        "Input",
        fields=(schema.input_field("field0", type=schema.Int, default=42), ),
    )

    Root = g.ObjectType(
        "Root",
        fields=(g.field("one",
                        type=g.Int,
                        params=[
                            g.param("arg", type=g.ListType(Input)),
                        ]), ),
    )

    graphql_query = """
        query ($value: Int!) {
            one(arg: [{}])
        }
    """

    object_query = _document_text_to_graph_query(graphql_query,
                                                 query_type=Root)
    assert_that(object_query.fields[0].args.arg,
                is_sequence(has_attrs(field0=42, ), ))
def submatcher_is_coerced_to_matcher():
    matcher = has_attrs(username="******")
    
    assert_equal(
        unmatched("attribute username was 'bobbity'"),
        matcher.match(User("bobbity", None))
    )
    def test_object_builder_creates_object_using_field_resolvers(self):
        User = g.ObjectType("User",
                            fields=(g.field("name",
                                            type=g.String,
                                            params=(g.param(
                                                "truncate",
                                                type=g.Int,
                                                default=None), )), ))

        object_builder = g.create_object_builder(
            User(
                g.key("name", User.fields.name()),
                g.key("initial",
                      User.fields.name(User.fields.name.params.truncate(1))),
            ))

        @object_builder.field(User.fields.name)
        def resolve_name(field_query):
            if field_query.args.truncate is None:
                return lambda user: user["name"]
            else:
                return lambda user: user["name"][:field_query.args.truncate]

        result = object_builder({"name": "Bob"})
        assert_that(result, has_attrs(
            name="Bob",
            initial="B",
        ))
Example #15
0
    def test_diff_with_render_false_renders_nothing(self):
        element = parser.Diff(
            name="example",
            content=dedent("""
                --- old
                +++ new

                @@ -1,2 +1,2 @@
                -x = 1
                +x = 2
                 print(x)

            """),
            render=False,
        )
        state = {
            "example": compiler.Code(
                language="python",
                content="x = 1\nprint(x)\n",
                pending_lines=(),
            ),
        }

        new_state, new_element = _execute(state, element)
        assert_that(new_element, is_empty_element)
        assert_that(new_state["example"], has_attrs(pending_lines=is_sequence("x = 2")))
Example #16
0
def can_pass_properties_as_dictionary():
    matcher = has_attrs({
        "username": equal_to("bob"),
    })

    assert_equal("object with attributes:\n * username: '******'",
                 matcher.describe())
    def test_when_type_is_object_then_typename_field_is_resolved(self):
        User = g.ObjectType("User", fields=(g.field("name", type=g.String), ))

        object_builder = g.create_object_builder(
            User(g.key("type", schema.typename_field()), ))

        result = object_builder({})
        assert_that(result, has_attrs(type="User", ))
Example #18
0
def is_graphql_argument(type=None):
    if type is None:
        type = anything

    return all_of(
        is_instance(graphql.GraphQLArgument),
        has_attrs(type=type),
    )
Example #19
0
def mismatches_when_property_is_missing():
    matcher = has_attrs(
        ("username", equal_to("bob")),
        ("email_address", equal_to("*****@*****.**")),
    )

    assert_equal(unmatched("was missing attribute username"),
                 matcher.match("bobbity"))
def can_pass_properties_as_dictionary():
    matcher = has_attrs({
        "username": equal_to("bob"),
    })
    
    assert_equal(
        "object with attributes:\n * username: '******'",
        matcher.describe()
    )
def description_contains_descriptions_of_properties():
    matcher = has_attrs(
        username=equal_to("bob"),
    )
    
    assert_equal(
        "object with attributes:\n * username: '******'",
        matcher.describe()
    )
Example #22
0
def explanation_of_mismatch_contains_mismatch_of_property():
    matcher = has_attrs(
        username=equal_to("bob"),
        email_address=equal_to("*****@*****.**"),
    )

    assert_equal(
        unmatched("attribute email_address was '*****@*****.**'"),
        matcher.match(User("bob", "*****@*****.**")))
Example #23
0
def can_pass_properties_as_list_of_tuples():
    matcher = has_attrs(
        ("username", equal_to("bob")),
        ("email_address", equal_to("*****@*****.**")),
    )

    assert_equal(
        "object with attributes:\n * username: '******'\n * email_address: '*****@*****.**'",
        matcher.describe())
def can_pass_properties_as_list_of_tuples():
    matcher = has_attrs(
        ("username", equal_to("bob")),
        ("email_address", equal_to("*****@*****.**")),
    )
    
    assert_equal(
        "object with attributes:\n * username: '******'\n * email_address: '*****@*****.**'",
        matcher.describe()
    )
def mismatches_when_property_is_missing():
    matcher = has_attrs(
        ("username", equal_to("bob")),
        ("email_address", equal_to("*****@*****.**")),
    )
    
    assert_equal(
        unmatched("was missing attribute username"),
        matcher.match("bobbity")
    )
def explanation_of_mismatch_contains_mismatch_of_property():
    matcher = has_attrs(
        username=equal_to("bob"),
        email_address=equal_to("*****@*****.**"),
    )
    
    assert_equal(
        unmatched("attribute email_address was '*****@*****.**'"),
        matcher.match(User("bob", "*****@*****.**"))
    )
Example #27
0
def is_graphql_field(type=None, args=None):
    if type is None:
        type = anything

    if args is None:
        args = anything

    return all_of(
        is_instance(graphql.GraphQLField),
        has_attrs(type=type, args=args),
    )
Example #28
0
def is_graphql_interface_type(name, fields=None):
    if fields is None:
        fields = anything

    return all_of(
        is_instance(graphql.GraphQLInterfaceType),
        has_attrs(
            name=name,
            fields=fields,
        ),
    )
Example #29
0
def test_given_no_mutation_type_is_defined_when_operation_is_mutation_then_error_is_raised():
    QueryRoot = g.ObjectType(
        "Query",
        (
            g.field("query_value", type=g.Int),
        ),
    )

    graphql_query = """
        mutation {
            queryValue
        }
    """

    error = pytest.raises(
        GraphQLError,
        lambda: _document_text_to_graph_query(graphql_query, query_type=QueryRoot),
    )

    assert_that(error.value.message, equal_to("unsupported operation: mutation"))
    assert_that(error.value.nodes, is_sequence(has_attrs(operation=has_attrs(value="mutation"))))
Example #30
0
    def test_start_with_render_false_renders_nothing(self):
        element = parser.Start(
            name="example",
            language="python",
            content="x = 1\nprint(x)",
            render=False,
        )
        state = {}

        new_state, new_element = _execute(state, element)
        assert_that(new_element, is_empty_element)
        assert_that(new_state["example"], has_attrs(pending_lines=is_sequence("x = 1", "print(x)")))
    def test_field_resolvers_can_be_defined_using_field_name(self):
        User = g.ObjectType("User", fields=(g.field("name", type=g.String), ))

        object_builder = g.create_object_builder(
            User(g.key("n", User.fields.name()), ))

        @object_builder.getter("name")
        def resolve_name(user):
            return user["name"]

        result = object_builder({"name": "Bob"})
        assert_that(result, has_attrs(n="Bob", ))
Example #32
0
def test_run_operator_can_be_created():
    run_operator = SpellRunOperator(
        spell_conn_id="testing-spell-run-operator",
        task_id="testing-task-id",
    )

    assert_that(
        run_operator,
        has_attrs(
            spell_conn_id="testing-spell-run-operator",
            task_id="testing-task-id",
        ),
    )
Example #33
0
def is_graphql_input_object_type(name=None, fields=None):
    if name is None:
        name = anything
    if fields is None:
        fields = anything

    return all_of(
        is_instance(graphql.GraphQLInputObjectType),
        has_attrs(
            name=name,
            fields=fields,
        ),
    )
Example #34
0
def is_query(query):
    if isinstance(query, schema.ScalarQuery):
        return is_instance(schema.ScalarQuery)

    elif isinstance(query, schema.EnumQuery):
        return is_instance(schema.EnumQuery)

    elif isinstance(query, schema.FieldQuery):
        return has_attrs(
            key=query.key,
            field=query.field,
            type_query=is_query(query.type_query),
            args=has_attrs(_values=is_mapping(query.args._values)),
        )

    elif isinstance(query, schema.ListQuery):
        return has_attrs(
            type=query.type,
            element_query=is_query(query.element_query),
        )

    elif isinstance(query, schema.NullableQuery):
        return has_attrs(
            type=query.type,
            element_query=is_query(query.element_query),
        )

    elif isinstance(query, schema.ObjectQuery):
        return has_attrs(
            type=query.type,
            field_queries=is_sequence(
                *
                [is_query(field_query)
                 for field_query in query.field_queries]),
        )

    else:
        raise Exception("Unhandled query type: {}".format(type(query)))
Example #35
0
def test_given_input_field_has_default_when_input_field_is_not_set_then_default_is_used():
    Input = schema.InputObjectType(
        "Input",
        fields=(
            schema.input_field("field0", type=schema.Int, default=None),
            schema.input_field("field1", type=schema.Int, default=42),
        ),
    )
    
    input_value = Input()
    assert_that(input_value, has_attrs(
        field0=None,
        field1=42,
    ))
Example #36
0
    def test_render_does_not_change_code_content(self):
        element = parser.Render(
            name="example",
            content="print(x)",
        )
        state = {
            "example": _create_code(
                language="python",
                content="x = 1\nprint(x)",
            ),
        }

        new_state, new_element = _execute(state, element)
        assert_that(new_state["example"], has_attrs(content="x = 1\nprint(x)"))
Example #37
0
    def test_start_with_render_true_renders_content(self):
        element = parser.Start(
            name="example",
            language="python",
            content="x = 1",
            render=True,
        )
        state = {}

        new_state, new_element = _execute(state, element)
        assert_that(new_element, is_code_block(
            language="python",
            content="x = 1",
        ))
        assert_that(new_state["example"], has_attrs(pending_lines=is_sequence()))
def is_text(value):
    return all_of(
        instance_of(documents.Text),
        has_attrs(value=value),
    )
 def matcher(**kwargs):
     return all_of(
         instance_of(element_type),
         has_attrs(**kwargs),
     )