Example #1
0
async def test_subscription(
    client, headers, subscription_query, mutation_city, city_name
):
    request = GraphQLRequest(query=subscription_query, headers=headers)
    m = []

    def callback(data):
        assert "city" in data
        m.append(data)
        if len(m) > 1:
            city = data.get("city")[0]
            assert city.get("name") == city_name
            subscription.unsubscribe()

    callbacks = CallbackRegistry()
    callbacks.register(
        GraphQLSubscriptionEventType.DATA, lambda event: callback(event.payload.data)
    )

    subscription: GraphQLSubscription = await client.subscribe(
        request=request, callbacks=callbacks, headers=headers,
    )

    await asyncio.sleep(0.1)

    request = GraphQLRequest(query=mutation_city, headers=headers)
    _ = await client.query(request)

    try:
        await asyncio.wait_for(subscription.task, timeout=1)
        assert len(m) == 2
    except asyncio.TimeoutError:
        pytest.fail("Subscriptions timed out before receiving expected messages")
async def _get_repositories(login: str, cursor: str = None) -> GraphQLResponse:
    """Get Repositories and their labels based on a cursor."""
    token = os.getenv("GITHUB_ACCESS_TOKEN")
    client = GraphQLClient(endpoint="https://api.github.com/graphql",
                           headers={"Authorization": f"Bearer {token}"})

    if cursor is not None:
        request = GraphQLRequest(
            query=ALL_REPOSITORIES_INCLUDING_LABELS_CURSOR.substitute(
                login=login, cursor=cursor))
    else:
        request = GraphQLRequest(
            query=ALL_REPOSITORIES_INCLUDING_LABELS.substitute(login=login))

    return await client.query(request=request)
Example #3
0
async def test_no_headers(server, client, query_city):
    graphql_request = GraphQLRequest(query=query_city)
    with pytest.raises(GraphQLIntrospectionException):
        response = await client.post(graphql_request)
        assert isinstance(response, GraphQLResponse)
        assert not response.data
        assert response.errors
Example #4
0
async def _get_repositories(login: str, cursor: str = None) -> GraphQLResponse:
    """Get Repositories and their labels based on a cursor."""
    global endpoint
    global token

    client = GraphQLClient(endpoint=f"{endpoint}/graphql",
                           headers={"Authorization": f"Bearer {token}"})

    if cursor is not None:
        request = GraphQLRequest(
            query=ALL_REPOSITORIES_INCLUDING_LABELS_CURSOR.substitute(
                login=login, cursor=cursor))
    else:
        request = GraphQLRequest(
            query=ALL_REPOSITORIES_INCLUDING_LABELS.substitute(login=login))

    return await client.query(request=request)
Example #5
0
async def test_unsuccessful_request(client, headers, query_city, query_output):
    # hasura does not support GET requests, we use this to test this case
    request = GraphQLRequest(query=query_city, headers=headers)
    with pytest.raises(GraphQLRequestException) as excinfo:
        _ = await client.get(request)
    assert (
        'Request failed with response {"path":"$","error":"resource does not exist","code":"not-found"}'
        in str(excinfo.value))
Example #6
0
async def reconcile_labels(repo: dict):
    """Reconcile Labels of the given Repository."""
    global endpoint
    global token

    _LOGGER.info("reconciling labels of {0}".format(repo["name"]))

    _LOGGER.debug(
        "total number of labels: '{0}', hasNextPage: {1}".format(
            repo["labels"]["totalCount"],
            repo["labels"]["pageInfo"]["hasNextPage"],
        ), )

    if repo["labels"]["pageInfo"]["hasNextPage"]:
        _LOGGER.error("for {0} we didnt get all labels!".format(repo["name"]))

    expectedLabels = {l["name"] for l in DEFAULT_LABELS}
    presentLabels = {l["name"] for l in repo["labels"]["nodes"]}
    _LOGGER.debug("expected labels: {0}".format(expectedLabels))
    _LOGGER.debug("labels present: {0}".format(presentLabels))

    missingLabels = expectedLabels - presentLabels
    _LOGGER.debug("missing labels: {0}".format(missingLabels))

    if len(missingLabels) == 0:
        _LOGGER.info("{0} does not need label reconciliation".format(
            repo["name"]))

    client = GraphQLClient(
        endpoint=f"{endpoint}/graphql",
        headers={
            "Authorization": f"Bearer {token}",
            "Accept": "application/vnd.github.bane-preview+json"
        },
    )

    for label in DEFAULT_LABELS:
        if label["name"] in missingLabels:
            mutation = CREATE_LABEL.substitute(
                id=repo["id"],
                name=label["name"],
                color=label["color"],
                desc=label["description"],
            )
            _LOGGER.debug("updating {0} in {1}, mutation: {2}".format(
                label["name"], repo["name"], mutation))

            request = GraphQLRequest(query=mutation, operation="AddLabel")
            _LOGGER.debug(request)

            response = await client.query(request=request)
            _LOGGER.debug(response)
Example #7
0
def test_request_container_overrides():
    request = GraphQLRequest(query="{}")
    headers = {"Authorization": "Bearer token"}
    operation = "operationName"
    variables = {"foo": "bar"}
    container = GraphQLRequestContainer(request=request,
                                        headers=headers,
                                        operation=operation,
                                        variables=variables)
    assert container.request != request
    assert container.request.headers == headers
    assert container.request.operationName == operation
    assert container.request.variables == variables
Example #8
0
async def test_invalid_query_schema(client, headers, invalid_query_schema):
    request = GraphQLRequest(query=invalid_query_schema, headers=headers)
    with pytest.raises(GraphQLClientValidationException) as excinfo:
        _ = await client.query(request)
    message = str(excinfo.value)
    assert ("""Query validation failed

Cannot query field 'citeee' on type 'query_root'. Did you mean 'city'?

GraphQL request:3:11
2 |         query{
3 |           citeee {
  |           ^
4 |             id""" == message)
Example #9
0
    async def v4_request(self,
                         token_type,
                         request_string,
                         installation_id=None):

        client = GraphQLClient(
            endpoint='https://api.github.com/graphql',
            headers={
                'Authorization':
                f'Bearer {await self._get_token_for_request(token_type, installation_id)}'
            },
            schema=_V4_SCHEMA,
        )
        request = GraphQLRequest(query=request_string)
        return (await client.query(request=request)).data
def test_subscription_init_with_callback_dict(mocker):
    subscription = GraphQLSubscription(
        request=GraphQLRequest(query="{}"),
        callbacks={
            GraphQLSubscriptionEventType.KEEP_ALIVE: mocker.Mock(),
            GraphQLSubscriptionEventType.DATA: [mocker.Mock(),
                                                mocker.Mock()],
        },
    )
    registry = subscription.callbacks

    assert isinstance(registry, CallbackRegistry)
    assert len(registry.callbacks(
        GraphQLSubscriptionEventType.KEEP_ALIVE)) == 1
    assert len(registry.callbacks(GraphQLSubscriptionEventType.DATA)) == 2
Example #11
0
async def test_subscription_on_data_on_error_callbacks(
    client, subscription_query, headers
):
    request = GraphQLRequest(query=subscription_query, headers=headers)

    async def event_on_data(_):
        pass

    def event_on_error(_):
        pass

    subscription: GraphQLSubscription = await client.subscribe(
        request=request,
        headers=headers,
        on_data=event_on_data,
        on_error=event_on_error,
    )
    registry = subscription.callbacks
    assert registry.exists(GraphQLSubscriptionEventType.DATA, event_on_data)
    assert registry.exists(GraphQLSubscriptionEventType.ERROR, event_on_error)
    await subscription.unsubscribe_and_wait()
Example #12
0
def test_request_payload_coerce():
    assert GraphQLRequest._coerce_value(True) == 1
    assert GraphQLRequest._coerce_value({}) == "{}"

    request = GraphQLRequest(query="{}",
                             variables={
                                 "foo": "bar",
                                 "baz": False
                             })
    assert request.payload(coerce=True) == {
        "query": "{}",
        "variables": '{"foo":"bar","baz":false}',
    }
    assert request.payload(coerce=False) == {
        "query": "{}",
        "variables": {
            "baz": False,
            "foo": "bar"
        },
    }
Example #13
0
async def test_mutation(client, headers, mutation_city, mutation_output):
    request = GraphQLRequest(query=mutation_city, headers=headers)
    response = await client.query(request)
    assert response.data == mutation_output
Example #14
0
async def test_invalid_method(client, headers, query_city):
    request = GraphQLRequest(query=query_city, headers=headers)
    with pytest.raises(GraphQLClientException):
        _ = await client.query(method="PUT", request=request)
Example #15
0
async def test_invalid_query_syntax(client, headers, invalid_query_syntax):
    request = GraphQLRequest(query=invalid_query_syntax, headers=headers)
    with pytest.raises(GraphQLSyntaxError):
        _ = await client.query(request)
Example #16
0
async def test_simple_anonymous_query(client, headers, query_city, query_output):
    request = GraphQLRequest(query=query_city, headers=headers)
    response = await client.query(request)
    assert response.data == query_output
Example #17
0
_LOGGER = logging.getLogger("aicoe.sesheta.github.graphql")
_LOGGER.setLevel(logging.DEBUG if bool(int(os.getenv("DEBUG", 0))) else logging.INFO)
_LOGGER.info(__version__)


request = GraphQLRequest(
    query="""
query {
  search(query: "is:open is:issue archived:false user:thoth-station label:priority/critical-urgent label:lifecycle/active sort:created-asc created:<2022-01-03", type: ISSUE, first: 100) {
    issueCount
    edges {
      node {
        ... on Issue {
          number
          title
          repository {
            nameWithOwner
          }
          createdAt
          url
        }
      }
    }
  }
}
""",
)


async def main():
    """Call this to run the main method."""
    client = GraphQLClient(
def test_subscription_init_with_callback_default():
    subscription = GraphQLSubscription(request=GraphQLRequest(query="{}"))
    assert isinstance(subscription.callbacks, CallbackRegistry)
    assert not subscription.callbacks.callbacks()
Example #19
0
def test_request_container_init_string():
    request = GraphQLRequest(query="{}")
    # noinspection PyTypeChecker
    container = GraphQLRequestContainer(request="{}")
    assert container.request == request
    assert id(container.request) != id(request)
Example #20
0
def test_request_container():
    request = GraphQLRequest(query="{}")
    container = GraphQLRequestContainer(request=request)
    assert container.request == request
    assert id(container.request) != id(request)
Example #21
0
async def test_request_headers(server, headers, post, query_city):
    client = GraphQLClient(endpoint=server)
    graphql_request = GraphQLRequest(query=query_city, headers=headers)
    response = await post(client, graphql_request)
    assert isinstance(response, GraphQLResponse)
Example #22
0
async def test_post_headers(server, headers, client, query_city):
    graphql_request = GraphQLRequest(query=query_city)
    response = await client.post(graphql_request, headers=headers)
    assert isinstance(response, GraphQLResponse)
    assert response.data
    assert not response.errors