示例#1
0
def test_options_response_excludes_get_if_introspection_is_disabled(schema):
    app = GraphQL(schema, introspection=False)
    client = TestClient(app)

    response = client.options("/")
    assert response.status_code == 200
    assert response.headers["Allow"] == "OPTIONS, POST"
示例#2
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])
    client = TestClient(app)
    client.post("/", json={"query": "{ status }"})
    spy_validation_rule.assert_called_once()
示例#3
0
def test_unsupported_method_response_excludes_get_if_introspection_is_disabled(
        schema):
    app = GraphQL(schema, introspection=False)
    client = TestClient(app)

    response = client.patch("/")
    assert response.status_code == 405
    assert response.headers["Allow"] == "OPTIONS, POST"
示例#4
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)
    client = TestClient(app)
    client.post("/", json={"query": "{ status }"})
    get_root_value.assert_called_once_with({"test": "TEST-CONTEXT"}, ANY)
示例#5
0
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)
    client = TestClient(app)
    client.post("/", json={"query": "{ status }"})
    get_validation_rules.assert_called_once()
    validation_rule.assert_called_once()
示例#6
0
def test_async_extensions_function_result_is_passed_to_query_executor(schema):
    async 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!"}}
示例#7
0
def test_async_middleware_function_result_is_passed_to_query_executor(schema):
    async def get_middleware(*_):
        return [middleware]

    app = GraphQL(schema, middleware=get_middleware)
    client = TestClient(app)
    response = client.post("/", json={"query": '{ hello(name: "BOB") }'})
    assert response.json() == {"data": {"hello": "**Hello, BOB!**"}}
示例#8
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!*="}}
示例#9
0
    def __init__(self, debug=True):

        type_defs = load_schema_from_path("graphql_server/schema/")
        schema = make_executable_schema(type_defs, query, mutation, user)

        self._server = CORSMiddleware(GraphQL(schema, debug=debug),
                                      allow_origins=["*"],
                                      allow_headers=["*"],
                                      allow_methods=["*"])
示例#10
0
def test_async_context_value_function_result_is_awaited_before_passing_to_resolvers(
    schema, ):
    async def get_context_value(*_):
        return {"test": "TEST-ASYNC-CONTEXT"}

    app = GraphQL(schema, context_value=get_context_value)
    client = TestClient(app)
    response = client.post("/", json={"query": "{ testContext }"})
    assert response.json() == {"data": {"testContext": "TEST-ASYNC-CONTEXT"}}
示例#11
0
def test_benchmark_complex_query_resolved_to_500_dicts(benchmark, schema, raw_data):
    app = GraphQL(schema, root_value=raw_data)
    client = TestClient(app)

    def api_call():
        return client.post("/", json={"query": COMPLEX_QUERY})

    result = benchmark(api_call)
    assert result.status_code == 200
示例#12
0
def test_benchmark_complex_query_resolved_to_one_object(
    benchmark, schema, hydrated_data_one_item
):
    app = GraphQL(schema, root_value={"users": hydrated_data_one_item})
    client = TestClient(app)

    def api_call():
        return client.post("/", json={"query": COMPLEX_QUERY})

    result = benchmark(api_call)
    assert result.status_code == 200
示例#13
0
def test_error_in_custom_websocket_on_connect_is_handled(schema):
    def on_connect(websocket, payload):
        raise ValueError("Oh No!")

    app = GraphQL(schema, on_connect=on_connect)
    client = TestClient(app)

    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ERROR
        assert response["payload"] == {"message": "Unexpected error has occurred."}
示例#14
0
def test_error_in_custom_websocket_on_disconnect_is_handled(schema):
    async def on_disconnect(websocket):
        raise ValueError("Oh No!")

    app = GraphQL(schema, on_disconnect=on_disconnect)
    client = TestClient(app)

    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ACK
        ws.send_json({"type": GQL_CONNECTION_TERMINATE})
示例#15
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,
    )
    client = TestClient(app)
    client.post("/", json={"query": "{ status }"})
    get_validation_rules.assert_called_once_with({"test": "TEST-CONTEXT"}, ANY,
                                                 ANY)
示例#16
0
def test_custom_websocket_connection_error_in_custom_websocket_on_connect_is_handled(
    schema,
):
    def on_connect(websocket, payload):
        raise WebSocketConnectionError({"msg": "Token required", "code": "auth_error"})

    app = GraphQL(schema, on_connect=on_connect)
    client = TestClient(app)

    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ERROR
        assert response["payload"] == {"msg": "Token required", "code": "auth_error"}
示例#17
0
def test_custom_websocket_on_disconnect_is_awaited_if_its_async(schema):
    async def on_disconnect(websocket):
        websocket.scope["on_disconnect"] = True

    app = GraphQL(schema, on_disconnect=on_disconnect)
    client = TestClient(app)

    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ACK
        ws.send_json({"type": GQL_CONNECTION_TERMINATE})
        assert "on_disconnect" not in ws.scope

    assert ws.scope["on_disconnect"] is True
示例#18
0
def test_custom_error_formatter_is_used_to_format_subscription_syntax_error(schema):
    error_formatter = Mock(return_value=True)
    app = GraphQL(schema, error_formatter=error_formatter)
    client = TestClient(app)
    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        ws.send_json(
            {"type": GQL_START, "id": "test1", "payload": {"query": "subscription {"}}
        )
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ACK
        response = ws.receive_json()
        assert response["type"] == GQL_ERROR
        assert response["id"] == "test1"
        error_formatter.assert_called_once()
示例#19
0
def test_custom_websocket_on_connect_is_awaited_if_its_async(schema):
    test_payload = {"test": "ok"}

    async def on_connect(websocket, payload):
        assert payload == test_payload
        websocket.scope["payload"] = payload

    app = GraphQL(schema, on_connect=on_connect)
    client = TestClient(app)

    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT, "payload": test_payload})
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ACK
        assert ws.scope["payload"] == test_payload
        ws.send_json({"type": GQL_CONNECTION_TERMINATE})
示例#20
0
文件: gql.py 项目: linuseing/hub
 async def setup(self):
     schema = make_executable_schema(self.type_defs, self.query,
                                     self.subscription, self.mutations)
     app = CORSMiddleware(
         GraphQL(schema),
         allow_origins=["*"],
         allow_methods=("GET", "POST", "OPTIONS"),
     )
     conf = Config()
     conf.bind = ["0.0.0.0:8006"]
     conf.loglevel = "fatal"  # to suppress lifespan error
     LOGGER.info("starting GQL API")
     try:  # also to suppress lifespan error
         await serve(app, conf)
     except Exception as e:
         print(e)
示例#21
0
    async def dummy_client(self, ):
        """
        Client for a dummy server
        """
        type_defs = ariadne.gql("""
            scalar JSON

            type Query {
                headers: JSON
                hello: String
                value_error_required: String!
                value_error: String
                type_error: String
                unauthenticated_error: String
                unauthorized_error: String
            }

            """)
        query = ariadne.QueryType()

        @query.field("hello")
        def hello(parent: Any, info: GraphQLResolveInfo):
            return "👋"

        @query.field("value_error")
        @query.field("value_error_required")
        def value_error(parent: Any, info: GraphQLResolveInfo):
            raise ValueError("this is a value error")

        @query.field("type_error")
        def type_error(parent: Any, info: GraphQLResolveInfo):
            raise TypeError("this is a type error")

        @query.field("unauthenticated_error")
        def unauthenticated_error(parent: Any, info: GraphQLResolveInfo):
            raise Unauthenticated("this is an unauthenticated error")

        @query.field("unauthorized_error")
        def unauthorized_error(parent: Any, info: GraphQLResolveInfo):
            raise Unauthorized("this is an unauthorized error")

        schema = make_executable_schema(type_defs, query)
        app = Starlette()
        app.mount("/", GraphQL(schema))
        async with httpx.Client(app=app,
                                base_url="http://prefect.io") as dummy_client:
            yield dummy_client
示例#22
0
def create_app(
    config: Config,
    database: Database,
    schema: GraphQLSchema,
) -> Starlette:
    debug = config("DEBUG", cast=bool, default=False)

    app = Starlette(
        debug=debug,
        routes=[
            Mount("/graphql", GraphQL(schema=schema, debug=debug)),
        ],
        on_startup=[database.connect],
        on_shutdown=[database.disconnect],
    )

    return app
示例#23
0
def test_custom_root_value_is_passed_to_subscription_resolvers(schema):
    app = GraphQL(schema, root_value={"test": "TEST-ROOT"})
    client = TestClient(app)
    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        ws.send_json({
            "type": GQL_START,
            "id": "test1",
            "payload": {
                "query": "subscription { testRoot }"
            },
        })
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ACK
        response = ws.receive_json()
        assert response["type"] == GQL_DATA
        assert response["payload"] == {"data": {"testRoot": "TEST-ROOT"}}
示例#24
0
def test_custom_root_value_function_is_called_by_subscription(schema):
    get_root_value = Mock(return_value=True)
    app = GraphQL(schema, root_value=get_root_value)
    client = TestClient(app)
    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        ws.send_json({
            "type": GQL_START,
            "id": "test1",
            "payload": {
                "query": "subscription { ping }"
            },
        })
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ACK
        response = ws.receive_json()
        assert response["type"] == GQL_DATA
        get_root_value.assert_called_once()
示例#25
0
def test_custom_logger_is_used_to_log_subscription_resolver_error(schema, mocker):
    logging_mock = mocker.patch("ariadne.logger.logging")
    app = GraphQL(schema, logger="custom")
    client = TestClient(app)
    with client.websocket_connect("/", "graphql-ws") as ws:
        ws.send_json({"type": GQL_CONNECTION_INIT})
        ws.send_json(
            {
                "type": GQL_START,
                "id": "test1",
                "payload": {"query": "subscription { resolverError }"},
            }
        )
        response = ws.receive_json()
        assert response["type"] == GQL_CONNECTION_ACK
        response = ws.receive_json()
        assert response["type"] == GQL_DATA
        logging_mock.getLogger.assert_called_once_with("custom")
示例#26
0
    def start(self):
        query = QueryType()
        query.set_field('echo', self._echo_resolver())

        mutation = MutationType()
        mutation.set_field('createTable', self._create_table_resolver())
        mutation.set_field('addPlayer', self._add_player_resolver())
        mutation.set_field('takeAction', self._take_action_resolver())
        mutation.set_field('startGame', self._start_game_resolver())
        mutation.set_field('stopGame', self._stop_game_resolver())
        mutation.set_field('reset', self._reset_resolver())

        subscription = SubscriptionType()
        subscription.set_field('subscribe', self._subscribe_resolver())
        subscription.set_source('subscribe', self._subscribe_generator())

        resolvers = [query, mutation, subscription]

        executable_schema = make_executable_schema(self._schema_str, resolvers)
        self._app = GraphQL(executable_schema, debug=True)
示例#27
0
def bootstrap(**dependencies) -> Starlette:
    """
    Boostraps a starlette app setting context_value in the GraphQL config
    """
    def context_value(request):
        return {**dependencies, 'request': request}

    gql_app = GraphQL(api.schema,
                      debug=DEBUG,
                      context_value=context_value,
                      middleware=[encode_id_middleware])
    routes = [Route("/graphql", gql_app)]

    middleware = [
        Middleware(CORSMiddleware,
                   allow_origins=ALLOW_ORIGINS,
                   allow_methods=['*'],
                   allow_headers=['*']),
        Middleware(request_state_middleware(**dependencies)),
    ]
    return Starlette(routes=routes, debug=DEBUG, middleware=middleware)
示例#28
0
def setup(project_settings: str = None, database: bool = False) -> GraphQL:
    """Load Turbulette applications and return the GraphQL route."""
    project_settings_module = (get_project_settings_by_env()
                               if not project_settings else
                               import_module(project_settings))

    # The database connection has to be initialized before the LazySettings object to be setup
    # so we have to connect to the database before the registry to be setup
    if database:
        get_gino_instance()

    registry = Registry(project_settings_module=project_settings_module)
    conf.registry.__setup__(registry)
    schema = registry.setup()
    # At this point, settings are now available through `settings` from `turbulette.conf` module
    settings = conf.settings

    # Now that the database connection is established, we can use `settings`

    cache.__setup__(Cache(settings.CACHE))

    extensions: List[Type[Extension]] = [PolicyExtension]
    for ext in settings.ARIADNE_EXTENSIONS:
        module_class = ext.rsplit(".", 1)
        extensions.append(
            getattr(
                import_module(module_class[0]),
                module_class[1],
            ))

    graphql_route = GraphQL(
        schema,
        debug=settings.DEBUG,
        extensions=extensions,
        error_formatter=error_formatter,
    )
    return graphql_route
示例#29
0
from db import db
from db import models

models.Base.metadata.create_all(bind=db.engine)


def seed():
    session = db.Session()
    # import pdb; pdb.set_trace()
    bram = models.Person(name="Bram")
    session.add(bram)
    dtc = models.Project(name="dtc")
    session.add(dtc)
    session.commit()


# seed()

app = FastAPI()


@app.middleware("http")
async def db_session_middleware(request, call_next):
    request.state.db = db.Session()
    response = await call_next(request)
    request.state.db.close()
    return response


app.mount("/graphql", GraphQL(schema, debug=True))
示例#30
0
from ariadne import make_executable_schema, load_schema_from_path
from ariadne.asgi import GraphQL
from resolvers import query, skill, person

# import schema from GraphQL file
type_defs = load_schema_from_path("./schema.gql")

schema = make_executable_schema(type_defs, query, skill, person)
app = GraphQL(schema, debug=True)