def test_custom_validation_rules_function_is_set_and_called_on_query_execution(
        schema, validation_rule):
    get_validation_rules = Mock(return_value=[validation_rule])
    app = GraphQL(schema, validation_rules=get_validation_rules)
    app.execute_query({}, {"query": "{ status }"})
    get_validation_rules.assert_called_once()
    validation_rule.assert_called_once()
Exemple #2
0
def test_middleware_function_result_is_passed_to_query_executor(schema):
    def get_middleware(*_):
        return [middleware]

    app = GraphQL(schema, middleware=get_middleware)
    _, result = app.execute_query({}, {"query": '{ hello(name: "BOB") }'})
    assert result == {"data": {"hello": "**Hello, BOB!**"}}
Exemple #3
0
def test_custom_root_value_function_is_called_with_context_value(schema):
    get_root_value = Mock(return_value=True)
    app = GraphQL(schema,
                  context_value={"test": "TEST-CONTEXT"},
                  root_value=get_root_value)
    app.execute_query({}, {"query": "{ status }"})
    get_root_value.assert_called_once_with({"test": "TEST-CONTEXT"}, ANY)
Exemple #4
0
def test_custom_validation_rules_function_is_set_and_called_on_query_execution(
        mocker, schema, validation_rule):
    spy_validation_rule = mocker.spy(validation_rule, "__init__")
    get_validation_rules = Mock(return_value=[validation_rule])
    app = GraphQL(schema, validation_rules=get_validation_rules)
    app.execute_query({}, {"query": "{ status }"})
    get_validation_rules.assert_called_once()
    spy_validation_rule.assert_called_once()
Exemple #5
0
def test_custom_validation_rules_function_is_called_with_context_value(
        schema, validation_rule):
    get_validation_rules = Mock(return_value=[validation_rule])
    app = GraphQL(
        schema,
        context_value={"test": "TEST-CONTEXT"},
        validation_rules=get_validation_rules,
    )
    app.execute_query({}, {"query": "{ status }"})
    get_validation_rules.assert_called_once_with({"test": "TEST-CONTEXT"}, ANY,
                                                 ANY)
Exemple #6
0
def test_extensions_function_result_is_passed_to_query_executor(schema):
    def get_extensions(*_):
        return [CustomExtension]

    app = GraphQL(schema, extensions=get_extensions)
    client = TestClient(app)
    response = client.post("/", json={"query": '{ hello(name: "BOB") }'})
    assert response.json() == {"data": {"hello": "hello, bob!"}}
Exemple #7
0
def test_middlewares_and_extensions_are_combined_in_correct_order(schema):
    def test_middleware(next_fn, *args, **kwargs):
        value = next_fn(*args, **kwargs)
        return f"*{value}*"

    app = GraphQL(schema,
                  extensions=[CustomExtension],
                  middleware=[test_middleware])
    client = TestClient(app)
    response = client.post("/", json={"query": '{ hello(name: "BOB") }'})
    assert response.json == {"data": {"hello": "=*Hello, BOB!*="}}
Exemple #8
0
def test_allowed_methods_list_returned_for_options_request_excludes_get(
        app_mock, middleware_request, start_response, schema):
    middleware_request["REQUEST_METHOD"] = "OPTIONS"
    server = GraphQL(schema, introspection=False)
    middleware = GraphQLMiddleware(app_mock, server)
    middleware(middleware_request, start_response)
    start_response.assert_called_once_with(
        HTTP_STATUS_200_OK,
        [
            ("Content-Type", CONTENT_TYPE_TEXT_PLAIN),
            ("Content-Length", 0),
            ("Allow", "OPTIONS, POST"),
        ],
    )
Exemple #9
0
def build_app():

    if "PGCONN" not in os.environ:
        raise Exception("Sorry, I need a connection string!")

    else:

        pgconn = psycopg2.connect(os.environ["PGCONN"])

        schema = make_executable_schema(
            load_schema_from_path("bogus_schema.graphql"),
            query)

        app = GraphQL(schema, debug=True,
            context_value=dict(pgconn=pgconn))

        return app
Exemple #10
0
def test_custom_logger_is_used_to_log_error(schema, mocker):
    logging_mock = mocker.patch("ariadne.logger.logging")
    app = GraphQL(schema, logger="custom")
    execute_failing_query(app)
    logging_mock.getLogger.assert_called_once_with("custom")
Exemple #11
0
def test_custom_context_value_is_passed_to_resolvers(schema):
    app = GraphQL(schema, context_value={"test": "TEST-CONTEXT"})
    _, result = app.execute_query({}, {"query": "{ testContext }"})
    assert result == {"data": {"testContext": "TEST-CONTEXT"}}
Exemple #12
0
def server(schema):
    return GraphQL(schema)
Exemple #13
0
def test_default_logger_is_used_to_log_error_if_custom_is_not_set(
        schema, mocker):
    logging_mock = mocker.patch("ariadne.logger.logging")
    app = GraphQL(schema)
    execute_failing_query(app)
    logging_mock.getLogger.assert_called_once_with("ariadne")
Exemple #14
0
def test_custom_root_value_is_passed_to_resolvers(schema):
    app = GraphQL(schema, root_value={"test": "TEST-ROOT"})
    _, result = app.execute_query({}, {"query": "{ testRoot }"})
    assert result == {"data": {"testRoot": "TEST-ROOT"}}
Exemple #15
0
def test_custom_root_value_function_is_set_and_called_by_app(schema):
    get_root_value = Mock(return_value=True)
    app = GraphQL(schema, root_value=get_root_value)
    app.execute_query({}, {"query": "{ status }"})
    get_root_value.assert_called_once()
def test_custom_validation_rule_is_called_by_query_validation(
        schema, validation_rule):
    app = GraphQL(schema, validation_rules=[validation_rule])
    app.execute_query({}, {"query": "{ status }"})
    validation_rule.assert_called_once()
Exemple #17
0
def test_custom_context_value_function_is_called_with_request_value(schema):
    get_context_value = Mock(return_value=True)
    app = GraphQL(schema, context_value=get_context_value)
    request = {"CONTENT_TYPE": DATA_TYPE_JSON}
    app.execute_query(request, {"query": "{ status }"})
    get_context_value.assert_called_once_with(request)
Exemple #18
0
def test_middlewares_are_passed_to_query_executor(schema):
    app = GraphQL(schema, middleware=[middleware])
    _, result = app.execute_query({}, {"query": '{ hello(name: "BOB") }'})
    assert result == {"data": {"hello": "**Hello, BOB!**"}}
""")

query = QueryType()


@query.field("hello")
def resolve_hello(_, info):
    # the two lines below does not work. use HTTP_USER_AGENT.
    ##request = info.context["request"]
    ##user_agent = request.headers.get("user-agent", "guest")
    user_agent = info.context["HTTP_USER_AGENT"]
    return "Hello, %s!..." % user_agent  #


schema = make_executable_schema(type_defs, query)
application = GraphQL(schema, debug=True)


def main():
    '''
        send a query in playground:
            query { hello }
            
        or send a query via curl:
            curl 'http://localhost:8051/graphql' \\
                   -H 'Accept-Encoding: gzip, deflate, br' \\
                   -H 'Content-Type: application/json' \\
                   -H 'Accept: application/json' -H 'Connection: keep-alive' \\
                   -H 'DNT: 1' -H 'Origin: http://localhost:8051' \\
                   --data-binary '{"query":"{hello}"}' --compressed
    '''
Exemple #20
0
def test_custom_error_formatter_is_used_to_format_error(schema):
    error_formatter = Mock(return_value=True)
    app = GraphQL(schema, error_formatter=error_formatter)
    execute_failing_query(app)
    error_formatter.assert_called_once()
Exemple #21
0
def test_extension_from_option_are_passed_to_query_executor(schema):
    app = GraphQL(schema, extensions=[CustomExtension])
    client = TestClient(app)
    response = client.post("/", json={"query": '{ hello(name: "BOB") }'})
    assert response.json() == {"data": {"hello": "hello, bob!"}}
Exemple #22
0
def test_custom_validation_rule_is_called_by_query_validation(
        mocker, schema, validation_rule):
    spy_validation_rule = mocker.spy(validation_rule, "__init__")
    app = GraphQL(schema, validation_rules=[validation_rule])
    app.execute_query({}, {"query": "{ status }"})
    spy_validation_rule.assert_called_once()
Exemple #23
0
def test_error_formatter_is_called_with_debug_enabled_flag(schema):
    error_formatter = Mock(return_value=True)
    app = GraphQL(schema, debug=True, error_formatter=error_formatter)
    execute_failing_query(app)
    error_formatter.assert_called_once_with(ANY, True)
Exemple #24
0
    def __init__(self, text: str = '') -> None:
        self.text = text

    def __str__(self) -> str:
        return self.text


# Correct type returned
@query.field("hello")
def resolve_hello(_: Union[object, None], info: GraphQLResolveInfo) -> str:
    user_agent = info.context["HTTP_USER_AGENT"]
    return f"heyo, {user_agent}!"


# Incorrect type returned. GraphQL returns error on method call
@query.field("goodbye")
def buhbye(*_: Union[object, None]) -> dict:
    return {"I": "am not a string"}


# Incorrect type returned. mypy sees no errors. GraphQL returns error on method call
@query.field("farewell")
def solong(*_: Union[object, None]) -> NotAString:
    return NotAString(text='Not a string tho')


schema = make_executable_schema(type_defs, query)

app = GraphQL(schema, debug=True)