repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
strawberry
tests/experimental/pydantic/schema/test_defaults.py
.py
import textwrap import pydantic import strawberry from strawberry.printer import print_schema from tests.conftest import skip_if_gql_32 from tests.experimental.pydantic.utils import needs_pydantic_v2 def test_field_type_default(): class User(pydantic.BaseModel): name: str = "James" nickname: str...
259
5,897
strawberry
tests/experimental/pydantic/schema/test_mutation.py
.py
import pydantic import strawberry from strawberry.experimental.pydantic._compat import IS_PYDANTIC_V2 def test_mutation(): class User(pydantic.BaseModel): name: pydantic.constr(min_length=2) @strawberry.experimental.pydantic.input(User) class CreateUserInput: name: strawberry.auto @...
222
6,011
strawberry
tests/experimental/pydantic/schema/test_1_and_2.py
.py
import importlib import sys import textwrap import warnings import pytest import strawberry from tests.experimental.pydantic.utils import needs_pydantic_v2 @pytest.mark.skipif( sys.version_info >= (3, 14), reason="Pydantic v1 is not compatible with Python 3.14+", ) @needs_pydantic_v2 def test_can_use_both_p...
153
3,623
strawberry
tests/experimental/pydantic/schema/test_federation.py
.py
from pydantic import BaseModel import strawberry from strawberry.federation.schema_directives import Key def test_fetch_entities_pydantic(): class ProductInDb(BaseModel): upc: str name: str # @strawberry.federation.type(keys=["upc"]) @strawberry.experimental.pydantic.type( model=...
52
1,307
strawberry
tests/experimental/pydantic/schema/test_forward_reference.py
.py
from __future__ import annotations import textwrap import pydantic import strawberry def test_auto_fields(): global User class UserModel(pydantic.BaseModel): age: int password: str | None other: float @strawberry.experimental.pydantic.type(UserModel) class User: ag...
50
914
strawberry
tests/experimental/pydantic/schema/test_computed.py
.py
import textwrap import pydantic import pytest from pydantic.version import VERSION as PYDANTIC_VERSION import strawberry IS_PYDANTIC_V2: bool = PYDANTIC_VERSION.startswith("2.") if IS_PYDANTIC_V2: from pydantic import computed_field @pytest.mark.skipif( not IS_PYDANTIC_V2, reason="Requires Pydantic v2 for...
73
1,618
strawberry
tests/http/test_graphql_ide.py
.py
from typing import Literal import pytest from tests.views.schema import schema from .clients.base import HttpClient @pytest.mark.parametrize("header_value", ["text/html", "*/*"]) @pytest.mark.parametrize("graphql_ide", ["graphiql", "apollo-sandbox", "pathfinder"]) async def test_renders_graphql_ide( header_val...
58
1,804
strawberry
tests/http/test_streaming.py
.py
import json from collections.abc import AsyncGenerator from strawberry.http.base import BaseView from strawberry.http.streaming import ( MultipartSubscriptionTransport, MultipartTransport, ) from strawberry.subscriptions import MULTIPART_SUBSCRIPTION_PROTOCOL def test_multipart_transport_encode_multipart_dat...
140
4,476
strawberry
tests/http/test_process_result.py
.py
from __future__ import annotations from typing import Literal import pytest from strawberry.http import GraphQLHTTPResponse from strawberry.types import ExecutionResult from tests.views.schema import schema from .clients.base import HttpClient def process_result(result: ExecutionResult) -> GraphQLHTTPResponse: ...
37
911
strawberry
tests/http/test_async_base_view.py
.py
import asyncio from asyncio import sleep from collections import Counter from collections.abc import AsyncGenerator from random import random import pytest from strawberry.http.streaming import merge_stream_with_heartbeat @pytest.mark.parametrize( "expected", [ pytest.param(["last"], id="single_item...
98
3,308
strawberry
tests/http/test_sse.py
.py
import asyncio import contextlib import json from collections.abc import AsyncIterable from typing import Literal import pytest import strawberry from strawberry.http.base import BaseView from strawberry.http.streaming import SSETransport from strawberry.schema.config import StrawberryConfig from strawberry.subscript...
885
26,324
strawberry
tests/http/test_mutation.py
.py
from .clients.base import HttpClient async def test_mutation(http_client: HttpClient): response = await http_client.query( query="mutation { hello }", headers={ "Content-Type": "application/json", }, ) data = response.json["data"] assert response.status_code == 200...
16
396
strawberry
tests/http/test_query_batching.py
.py
import pytest import strawberry from strawberry.schema.config import StrawberryConfig from tests.conftest import skip_if_gql_32 from tests.http.clients.base import HttpClient from tests.views.schema import Mutation, MyExtension, Query, Subscription @pytest.fixture def batching_http_client(http_client_class: type[Htt...
207
6,430
strawberry
tests/http/test_upload.py
.py
import contextlib import json import uuid from io import BytesIO import pytest from tests.views.schema import schema from .clients.base import HttpClient def _encode_multipart_formdata(fields, boundary=None): # Do we really need this? # Copied from urllib3: https://github.com/urllib3/urllib3/blob/main/src/...
303
8,665
strawberry
tests/http/context.py
.py
def get_context(context: object) -> dict[str, object]: assert isinstance(context, dict) request = context.get("request") headers = getattr(request, "headers", {}) if request is not None else {} authorization = headers.get("authorization") or headers.get("Authorization") extra_context = {"custom_va...
13
480
strawberry
tests/http/test_http.py
.py
import json from typing import Literal import pytest from strawberry.http.base import BaseView from .clients.base import HttpClient @pytest.mark.parametrize("method", ["delete", "head", "put", "patch"]) async def test_does_only_allow_get_and_post( method: Literal["delete", "head", "put", "patch"], http_cli...
61
1,911
strawberry
tests/http/test_graphql_over_http_spec.py
.py
""" This file essentially mirrors the GraphQL over HTTP audits: https://github.com/graphql/graphql-http/blob/main/src/audits/server.ts """ import pytest from .clients.base import JSON, HttpClient try: from tests.http.clients.chalice import ChaliceHttpClient except ImportError: ChaliceHttpClient = type(None) ...
804
23,389
strawberry
tests/http/test_parse_content_type.py
.py
import pytest from strawberry.http.parse_content_type import parse_content_type @pytest.mark.parametrize( ("content_type", "expected"), [ ("application/json", ("application/json", {})), ("", ("", {})), ("application/json; charset=utf-8", ("application/json", {"charset": "utf-8"})), ...
57
1,756
strawberry
tests/http/test_query.py
.py
from typing import Literal import pytest from graphql import GraphQLError from pytest_mock import MockFixture from tests.conftest import skip_if_gql_32 from .clients.base import HttpClient @pytest.mark.parametrize("method", ["get", "post"]) async def test_graphql_query(method: Literal["get", "post"], http_client: ...
376
10,739
strawberry
tests/http/test_query_via_get.py
.py
from tests.views.schema import schema from .clients.base import HttpClient async def test_sending_get_with_content_type_passes(http_client_class): http_client = http_client_class(schema) response = await http_client.query( method="get", query="query {hello}", headers={ "C...
47
1,393
strawberry
tests/http/conftest.py
.py
import importlib from collections.abc import Generator from typing import Any import pytest from tests.views.schema import schema from .clients.base import HttpClient def _get_http_client_classes() -> Generator[Any, None, None]: for client, module, marks in [ ("AioHttpClient", "aiohttp", [pytest.mark.a...
59
1,930
strawberry
tests/http/clients/chalice.py
.py
from __future__ import annotations import urllib.parse from io import BytesIO from json import dumps from typing import Any, Literal from chalice.app import Chalice from chalice.app import Request as ChaliceRequest from chalice.test import Client from strawberry import Schema from strawberry.chalice.views import Gra...
161
5,033
strawberry
tests/http/clients/flask.py
.py
from __future__ import annotations import asyncio import contextvars import functools import json import urllib.parse from io import BytesIO from typing import Any, Literal from flask import Flask from flask import Request as FlaskRequest from flask import Response as FlaskResponse from strawberry.flask.views import ...
167
5,237
strawberry
tests/http/clients/sanic.py
.py
from __future__ import annotations from collections.abc import Sequence from io import BytesIO from json import dumps from random import randint from typing import Any, Literal from sanic import Sanic from sanic.request import Request as SanicRequest from strawberry.http import GraphQLHTTPResponse from strawberry.ht...
166
5,109
strawberry
tests/http/clients/aiohttp.py
.py
from __future__ import annotations import contextlib import json from collections.abc import AsyncGenerator, Mapping, Sequence from datetime import timedelta from io import BytesIO from typing import Any, Literal from aiohttp import web from aiohttp.client_ws import ClientWebSocketResponse from aiohttp.http_websocket...
233
7,632
strawberry
tests/http/clients/channels.py
.py
from __future__ import annotations import contextlib import json as json_module from collections.abc import AsyncGenerator, Mapping, Sequence from datetime import timedelta from io import BytesIO from typing import Any, Literal from channels.testing import HttpCommunicator, WebsocketCommunicator from urllib3 import e...
362
11,751
strawberry
tests/http/clients/asgi.py
.py
from __future__ import annotations import contextlib import json from collections.abc import AsyncGenerator, Mapping, Sequence from datetime import timedelta from io import BytesIO from typing import Any, Literal from starlette.requests import Request from starlette.responses import Response as StarletteResponse from...
246
7,805
strawberry
tests/http/clients/async_django.py
.py
from __future__ import annotations from collections.abc import AsyncIterable, Sequence from django.core.exceptions import BadRequest, SuspiciousOperation from django.http import Http404, HttpRequest, HttpResponse, StreamingHttpResponse from strawberry.django.views import AsyncGraphQLView as BaseAsyncGraphQLView from...
93
3,140
strawberry
tests/http/clients/django.py
.py
from __future__ import annotations from io import BytesIO from json import dumps from typing import Any, Literal from django.core.exceptions import BadRequest, SuspiciousOperation from django.core.files.uploadedfile import SimpleUploadedFile from django.http import Http404, HttpRequest, HttpResponse from django.test....
183
5,819
strawberry
tests/http/clients/quart.py
.py
import contextlib import json import urllib.parse from collections.abc import AsyncGenerator, Sequence from datetime import timedelta from io import BytesIO from typing import Any, Literal from quart import Quart from quart import Request as QuartRequest from quart import Response as QuartResponse from quart import We...
218
7,262
strawberry
tests/http/clients/async_flask.py
.py
from __future__ import annotations from collections.abc import Sequence from typing import Any from flask import Flask from flask import Request as FlaskRequest from flask import Response as FlaskResponse from strawberry.flask.views import AsyncGraphQLView as BaseAsyncGraphQLView from strawberry.http import GraphQLHT...
84
2,684
strawberry
tests/http/clients/base.py
.py
import abc import contextlib import json import logging from collections.abc import AsyncGenerator, AsyncIterable, Callable, Mapping, Sequence from dataclasses import dataclass from datetime import timedelta from functools import cached_property from io import BytesIO from typing import Any, Literal, Optional, Union f...
378
11,736
strawberry
tests/http/clients/fastapi.py
.py
from __future__ import annotations import contextlib import json from collections.abc import AsyncGenerator, Sequence from datetime import timedelta from io import BytesIO from typing import Any, Literal from fastapi import BackgroundTasks, Depends, FastAPI, Request, WebSocket from fastapi.testclient import TestClien...
198
6,182
strawberry
tests/http/clients/litestar.py
.py
from __future__ import annotations import contextlib import json from collections.abc import AsyncGenerator, Mapping, Sequence from datetime import timedelta from io import BytesIO from typing import Any, Literal from litestar import Litestar, Request from litestar.exceptions import WebSocketDisconnect from litestar....
256
8,249
strawberry
tests/http/incremental/test_stream.py
.py
import contextlib import pytest from inline_snapshot import snapshot from tests.conftest import skip_if_gql_32 from tests.http.clients.base import HttpClient pytestmark = skip_if_gql_32("GraphQL 3.3.0 is required for incremental execution") async def test_basic_stream(http_client: HttpClient): response = await...
76
2,009
strawberry
tests/http/incremental/test_multipart_subscription.py
.py
import contextlib from typing import Literal import pytest import strawberry from strawberry.http.base import BaseView from strawberry.schema.config import StrawberryConfig from strawberry.subscriptions import MULTIPART_SUBSCRIPTION_PROTOCOL from tests.http.clients.base import HttpClient from tests.views.schema impor...
192
5,964
strawberry
tests/http/incremental/test_defer.py
.py
import contextlib from typing import Literal import pytest from inline_snapshot import snapshot import strawberry from strawberry.extensions.mask_errors import MaskErrors from strawberry.schema.config import StrawberryConfig from tests.conftest import skip_if_gql_32 from tests.http.clients.base import HttpClient from...
107
3,191
strawberry
tests/http/incremental/conftest.py
.py
import contextlib import pytest from tests.http.clients.base import HttpClient from tests.views.schema import schema @pytest.fixture def incremental_http_client_class( http_client_class: type[HttpClient], ) -> type[HttpClient]: with contextlib.suppress(ImportError): from tests.http.clients.django im...
48
1,643
strawberry
tests/asgi/test_async.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import pytest import strawberry if TYPE_CHECKING: from starlette.testclient import TestClient @pytest.fixture def test_client() -> TestClient: from starlette.testclient import TestClient from strawberry.asgi import GraphQL @stra...
34
782
strawberry
tests/benchmarks/test_parse_execute_large_query.py
.py
from pathlib import Path import pytest from graphql import parse from pytest_codspeed.plugin import BenchmarkFixture from strawberry import Schema from .api import Query ROOT = Path(__file__).parent / "queries" large_query = (ROOT / "large_items.graphql").read_text() @pytest.mark.benchmark def test_parse_large_qu...
43
956
strawberry
tests/benchmarks/test_complex_schema.py
.py
import asyncio import pytest from pytest_codspeed.plugin import BenchmarkFixture from .schema import schema query = """ fragment AuthorFragment on User { id username email role } fragment PostFragment on Post { id content title author { ...AuthorFragment } comments { edges { node...
102
1,594
strawberry
tests/benchmarks/test_subscriptions.py
.py
import asyncio from collections.abc import AsyncIterator import pytest from graphql import ExecutionResult from pytest_codspeed.plugin import BenchmarkFixture from .api import schema @pytest.mark.benchmark def test_subscription(benchmark: BenchmarkFixture): s = """ subscription { something } ...
51
1,305
strawberry
tests/benchmarks/test_execute_sync.py
.py
from pathlib import Path import pytest from pytest_codspeed.plugin import BenchmarkFixture from .api import schema, schema_with_directives ROOT = Path(__file__).parent / "queries" basic_query = (ROOT / "simple.graphql").read_text() many_fields_query = (ROOT / "many_fields.graphql").read_text() many_fields_query_dir...
44
1,390
strawberry
tests/benchmarks/schema.py
.py
from __future__ import annotations from enum import Enum from typing import Annotated import strawberry @strawberry.enum class Role(Enum): ADMIN = "ADMIN" USER = "USER" GUEST = "GUEST" @strawberry.interface class Node: id: strawberry.ID @strawberry.type class PageInfo: has_next_page: bool ...
179
3,822
strawberry
tests/benchmarks/test_stadium.py
.py
"""Benchmark for a complex nested query with a large stadium dataset. This benchmark tests Strawberry's performance when dealing with deeply nested objects and large result sets. The stadium query generates approximately 50,000 seat objects across multiple stands, each with multiple labels and coordinates. """ import...
206
5,143
strawberry
tests/benchmarks/test_execute_with_extensions.py
.py
import asyncio from inspect import isawaitable from pathlib import Path from typing import Any import pytest from pytest_codspeed.plugin import BenchmarkFixture import strawberry from strawberry.extensions.base_extension import SchemaExtension from strawberry.utils.await_maybe import AwaitableOrValue from .api impor...
56
1,507
strawberry
tests/benchmarks/test_generic_input.py
.py
import asyncio from typing import Generic, TypeVar from pytest_codspeed.plugin import BenchmarkFixture import strawberry T = TypeVar("T") @strawberry.input(description="Filter for GraphQL queries") class GraphQLFilter(Generic[T]): """EXTERNAL Filter for GraphQL queries""" eq: T | None = None in_: list...
76
1,374
strawberry
tests/benchmarks/test_exception_handlers.py
.py
import pytest from pytest_codspeed.plugin import BenchmarkFixture import strawberry class ValidationError(Exception): pass @strawberry.type class ErrorResult: message: str @strawberry.type class Value: amount: int class Handler(strawberry.ExceptionHandler[ValidationError, ErrorResult]): def han...
87
2,568
strawberry
tests/benchmarks/api.py
.py
from collections.abc import AsyncIterator import strawberry from strawberry.directive import DirectiveLocation, DirectiveValue @strawberry.type class Item: name: str index: int @strawberry.type class Person: name: str age: int description: str address: str prop_a: str prop_b: str ...
91
2,037
strawberry
tests/benchmarks/test_arguments.py
.py
import pytest from pytest_codspeed import BenchmarkFixture from strawberry.schema.config import StrawberryConfig from strawberry.schema.types.scalar import DEFAULT_SCALAR_REGISTRY from strawberry.types.arguments import convert_argument from strawberry.types.base import StrawberryList @pytest.mark.parametrize("ntypes...
22
693
strawberry
tests/benchmarks/test_execute.py
.py
import asyncio import datetime import random from datetime import date from typing import cast import pytest from pytest_codspeed.plugin import BenchmarkFixture import strawberry from strawberry.scalars import ID @pytest.mark.benchmark def test_execute(benchmark: BenchmarkFixture): birthday = datetime.datetime....
112
2,463
strawberry
tests/websockets/views.py
.py
from strawberry import UNSET from strawberry.exceptions import ConnectionRejectionError from strawberry.http.async_base_view import AsyncBaseHTTPView from strawberry.http.typevars import ( Request, Response, SubResponse, WebSocketRequest, WebSocketResponse, ) from strawberry.types.unset import Unset...
46
1,385
strawberry
tests/websockets/test_graphql_ws.py
.py
from __future__ import annotations import asyncio import json from collections.abc import AsyncGenerator from typing import TYPE_CHECKING from unittest import mock import pytest import pytest_asyncio from strawberry.subscriptions import GRAPHQL_WS_PROTOCOL from strawberry.subscriptions.protocols.graphql_ws.types imp...
1,064
34,413
strawberry
tests/websockets/test_websockets.py
.py
from strawberry.http.async_base_view import AsyncBaseHTTPView from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL from strawberry.subscriptions.protocols.graphql_transport_ws.types import ( ConnectionAckMessage, ) from tests.http.clients.base import HttpClient from tests.views.sc...
124
4,170
strawberry
tests/websockets/test_graphql_transport_ws.py
.py
from __future__ import annotations import asyncio import contextlib import json import time from collections.abc import AsyncGenerator from datetime import timedelta from typing import TYPE_CHECKING from unittest.mock import AsyncMock, Mock, patch import pytest import pytest_asyncio from graphql import parse from pyt...
1,750
56,515
strawberry
tests/websockets/conftest.py
.py
import importlib from collections.abc import Generator from typing import Any import pytest from tests.http.clients.base import HttpClient from tests.views.schema import schema def _get_http_client_classes() -> Generator[Any, None, None]: for client, module, marks in [ ("AioHttpClient", "aiohttp", [pyte...
46
1,380
strawberry
tests/relay/test_exceptions.py
.py
import pytest import strawberry from strawberry import Info, relay from strawberry.relay import GlobalID from strawberry.relay.exceptions import ( NodeIDAnnotationError, RelayWrongAnnotationError, RelayWrongResolverAnnotationError, ) @strawberry.type class NonNodeType: foo: str def test_raises_erro...
156
4,099
strawberry
tests/relay/test_connection.py
.py
from collections.abc import Iterable from typing import Annotated, Any, Optional from typing_extensions import Self import pytest import strawberry from strawberry.permission import BasePermission from strawberry.relay import Connection, Node, PageInfo, to_base64 from strawberry.relay.types import Edge, ListConnectio...
270
6,680
strawberry
tests/relay/schema_future_annotations.py
.py
from __future__ import annotations import dataclasses from collections.abc import ( AsyncGenerator, AsyncIterable, AsyncIterator, Generator, Iterable, Iterator, ) from typing import ( Annotated, Any, NamedTuple, cast, ) from typing_extensions import Self import strawberry from ...
355
10,112
strawberry
tests/relay/schema.py
.py
import dataclasses from collections.abc import ( AsyncGenerator, AsyncIterable, AsyncIterator, Generator, Iterable, Iterator, ) from typing import ( Annotated, Any, NamedTuple, TypeAlias, cast, ) from typing_extensions import Self import strawberry from strawberry import rel...
362
10,422
strawberry
tests/relay/test_custom_edge.py
.py
import textwrap from typing import Any from typing_extensions import Self import pytest import strawberry from strawberry import Schema, relay from strawberry.relay import NodeType, to_base64 @pytest.fixture def schema() -> Schema: @strawberry.type class Fruit(relay.Node): code: relay.NodeID[int] ...
197
5,175
strawberry
tests/relay/test_fields.py
.py
import dataclasses import textwrap import warnings from collections.abc import Iterable from typing_extensions import Self import pytest from pytest_mock import MockerFixture import strawberry from strawberry import relay from strawberry.annotation import StrawberryAnnotation from strawberry.relay.fields import Conne...
1,752
51,425
strawberry
tests/relay/test_id.py
.py
from __future__ import annotations from inline_snapshot import snapshot import strawberry from strawberry.relay import GlobalID from strawberry.schema.config import StrawberryConfig @strawberry.type class Book: id: GlobalID title: str debug: str @strawberry.type class Query: @strawberry.field ...
258
6,343
strawberry
tests/relay/test_types.py
.py
from collections.abc import AsyncGenerator, AsyncIterable from typing import Any, Optional, Union, cast from typing_extensions import assert_type from unittest.mock import MagicMock import pytest import strawberry from strawberry import relay from strawberry.relay.utils import to_base64 from strawberry.types.info imp...
325
9,200
strawberry
tests/relay/test_utils.py
.py
from __future__ import annotations import sys from typing import Any from unittest import mock import pytest from strawberry.relay.types import PREFIX from strawberry.relay.utils import ( SliceMetadata, from_base64, to_base64, ) from strawberry.schema.config import StrawberryConfig from strawberry.types....
225
6,105
strawberry
tests/relay/test_schema.py
.py
import pathlib import textwrap from pytest_snapshot.plugin import Snapshot import strawberry from strawberry import relay from strawberry.relay.utils import to_base64 from .schema import schema from .schema_future_annotations import schema as schema_future_annotations SNAPSHOTS_DIR = pathlib.Path(__file__).parent /...
363
9,511
strawberry
tests/utils/test_logging.py
.py
import logging from graphql.error import GraphQLError from strawberry.utils.logging import StrawberryLogger def test_strawberry_logger_error(caplog): caplog.set_level(logging.ERROR, logger="strawberry.execution") exc = GraphQLError("test exception") StrawberryLogger.error(exc) assert caplog.record...
17
405
strawberry
tests/utils/test_arguments_converter.py
.py
from enum import Enum from typing import Annotated, Optional import pytest import strawberry from strawberry.annotation import StrawberryAnnotation from strawberry.exceptions import UnsupportedTypeError from strawberry.schema.config import StrawberryConfig from strawberry.schema.types.scalar import DEFAULT_SCALAR_REG...
442
10,873
strawberry
tests/utils/test_get_first_operation.py
.py
from graphql import OperationType, parse from strawberry.utils.operation import get_first_operation def test_document_without_operation_definition_nodes(): document = parse( """ fragment Test on Query { hello } """ ) assert get_first_operation(document) is None...
44
929
strawberry
tests/utils/test_inspect.py
.py
from typing import Generic, TypeVar import pytest import strawberry from strawberry.utils.inspect import get_specialized_type_var_map _T = TypeVar("_T") _K = TypeVar("_K") @pytest.mark.parametrize("value", [object, type(None), int, str, type("Foo", (), {})]) def test_get_specialized_type_var_map_non_generic(value:...
152
3,299
strawberry
tests/utils/test_typing_forward_refs.py
.py
from __future__ import annotations import typing from typing import ClassVar, ForwardRef, Optional, Union from strawberry.scalars import JSON from strawberry.utils.typing import eval_type, is_classvar def test_eval_type(): class Foo: ... assert eval_type(ForwardRef("Foo | None"), globals(), locals()) == Op...
58
1,887
strawberry
tests/utils/test_typing.py
.py
import typing from typing import Annotated, ClassVar, ForwardRef, Optional, Union import strawberry from strawberry.types.lazy_type import LazyType from strawberry.utils.typing import eval_type, get_optional_annotation, is_classvar @strawberry.type class Fruit: ... def test_get_optional_annotation(): # Pair Un...
110
3,381
strawberry
tests/utils/test_get_operation_type.py
.py
import pytest from graphql import parse from strawberry.types.graphql import OperationType from strawberry.utils.operation import get_operation_type mutation_collision = parse(""" fragment UserAgent on UserAgentType { id } mutation UserAgent { setUserAgent { ...UserAgent } } """) query_collision = parse("...
111
2,210
strawberry
tests/utils/test_importer.py
.py
import pytest from strawberry.utils.importer import import_module_symbol from tests.fixtures.sample_package.sample_module import sample_instance, schema def test_symbol_import(): selector = "tests.fixtures.sample_package.sample_module:schema" schema_symbol = import_module_symbol(selector) assert schema_s...
42
1,374
strawberry
tests/utils/test_locate_definition.py
.py
from pathlib import Path from inline_snapshot import snapshot from strawberry.utils.importer import import_module_symbol from strawberry.utils.locate_definition import locate_definition from tests.typecheckers.utils.marks import skip_on_windows pytestmark = skip_on_windows def _simplify_path(path: str) -> str: ...
124
3,560
strawberry
tests/fixtures/sample_package/sample_module.py
.py
from enum import Enum from typing import Annotated, NewType import strawberry ExampleScalar = strawberry.scalar( NewType("ExampleScalar", object), serialize=lambda v: v, parse_value=lambda v: v, ) @strawberry.type class A: name: str @strawberry.type class B: a: A UnionExample = Annotated[A |...
61
997
strawberry
tests/enums/test_enum.py
.py
from enum import Enum, IntEnum from typing import Annotated import pytest import strawberry from strawberry.exceptions import ObjectIsNotAnEnumError from strawberry.types.base import get_object_definition from strawberry.types.enum import StrawberryEnumDefinition def test_basic_enum(): @strawberry.enum clas...
317
8,804
strawberry
tests/cli/test_codegen.py
.py
from pathlib import Path import pytest from typer import Typer from typer.testing import CliRunner from strawberry.cli.commands.codegen import ConsolePlugin from strawberry.codegen import CodegenFile, CodegenResult, QueryCodegenPlugin from strawberry.codegen.types import GraphQLOperation, GraphQLType class ConsoleT...
305
7,564
strawberry
tests/cli/test_upgrade.py
.py
from pathlib import Path from pytest_snapshot.plugin import Snapshot from typer import Typer from typer.testing import CliRunner HERE = Path(__file__).parent def test_upgrade_returns_error_code_if_codemod_does_not_exist( cli_app: Typer, cli_runner: CliRunner ): result = cli_runner.invoke( cli_app, ...
67
1,804
strawberry
tests/cli/test_export_schema.py
.py
from inline_snapshot import snapshot from typer import Typer from typer.testing import CliRunner def test_schema_export(cli_app: Typer, cli_runner: CliRunner): selector = "tests.fixtures.sample_package.sample_module:schema" result = cli_runner.invoke(cli_app, ["export-schema", selector]) assert result.ex...
150
3,492
strawberry
tests/cli/test_schema_codegen.py
.py
from pathlib import Path import pytest from typer import Typer from typer.testing import CliRunner schema = """ type Query { hello: String! } """ expected_output = """ from __future__ import annotations import strawberry @strawberry.type class Query: hello: str schema = strawberry.Schema(query=Query) """.s...
66
1,669
strawberry
tests/cli/test_dev.py
.py
import re import sys from unittest.mock import MagicMock import pytest from pytest_mock import MockerFixture, MockFixture from starlette.testclient import TestClient from typer import Typer from typer.testing import CliRunner # UTF-8 chars are not supported by default console on Windows BOOT_MSG_END = " 🍓\n" if sys....
118
3,731
strawberry
tests/cli/test_locate_definition.py
.py
from pathlib import Path from inline_snapshot import snapshot from typer import Typer from typer.testing import CliRunner from tests.typecheckers.utils.marks import skip_on_windows pytestmark = skip_on_windows def _simplify_path(path: str) -> str: path = Path(path) root = Path(__file__).parents[1] re...
63
2,062
strawberry
tests/cli/conftest.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import pytest from typer.testing import CliRunner from strawberry.cli.constants import DEV_SERVER_SCHEMA_ENV_VAR_KEY if TYPE_CHECKING: from starlette.testclient import TestClient from typer import Typer @pytest.fixture def cli_runner() ->...
39
788
strawberry
tests/cli/snapshots/unions.py
.py
import strawberry from typing import Annotated # create a few types and then a union type @strawberry.type class Foo: a: str @strawberry.type class Bar: b: str @strawberry.type class Baz: c: str @strawberry.type class Qux: d: str # this is the union type Union1 = Annotated[Foo | Bar | Baz | ...
31
421
strawberry
tests/cli/snapshots/unions_typing_extension.py
.py
import strawberry from typing_extensions import Annotated # create a few types and then a union type @strawberry.type class Foo: a: str @strawberry.type class Bar: b: str @strawberry.type class Baz: c: str @strawberry.type class Qux: d: str # this is the union type Union1 = Annotated[Foo | B...
31
432
strawberry
tests/cli/fixtures/unions.py
.py
import strawberry # create a few types and then a union type @strawberry.type class Foo: a: str @strawberry.type class Bar: b: str @strawberry.type class Baz: c: str @strawberry.type class Qux: d: str # this is the union type Union1 = strawberry.union(name="Union1", types=(Foo, Bar, Baz, Qux...
30
382
strawberry
tests/test/test_client.py
.py
from contextlib import nullcontext import pytest from strawberry.utils.await_maybe import await_maybe @pytest.mark.parametrize( ("assert_no_errors", "expectation"), [(True, pytest.raises(AssertionError)), (False, nullcontext())], ) async def test_query_with_assert_no_errors_option( graphql_client, asser...
21
522
strawberry
tests/test/conftest.py
.py
from __future__ import annotations from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import TYPE_CHECKING import pytest from tests.views.schema import schema if TYPE_CHECKING: from strawberry.test import BaseGraphQLTestClient @asynccontextmanager async def aioht...
69
2,011
strawberry
tests/objects/test_object_instantiation.py
.py
import strawberry def test_can_instantiate_types_directly(): @strawberry.type class User: username: str @strawberry.field def email(self) -> str: return self.username + "@somesite.com" user = User(username="abc") assert user.username == "abc" assert user.email...
16
345
strawberry
tests/objects/test_inheritance.py
.py
import strawberry def test_inherited_fields(): @strawberry.type class A: a: str = strawberry.field(default="") @strawberry.type class B(A): b: str | None = strawberry.field(default=None) assert strawberry.Schema(query=B)
14
261
strawberry
tests/objects/test_types.py
.py
import pytest import strawberry from strawberry.exceptions import ObjectIsNotClassError @pytest.mark.raises_strawberry_exception( ObjectIsNotClassError, match=( r"strawberry.type can only be used with class types. Provided " r"object .* is not a type." ), ) def test_raises_error_when_usin...
44
1,073
strawberry
tests/objects/test_interfaces.py
.py
import strawberry def test_defining_interface(): @strawberry.interface class Node: id: strawberry.ID definition = Node.__strawberry_definition__ assert definition.name == "Node" assert len(definition.fields) == 1 assert definition.fields[0].python_name == "id" assert definition....
119
3,264
strawberry
tests/objects/generics/test_names.py
.py
import textwrap from typing import Annotated, Generic, NewType, TypeVar import pytest import strawberry from strawberry.schema.config import StrawberryConfig from strawberry.types.base import StrawberryList, StrawberryOptional from strawberry.types.enum import StrawberryEnumDefinition from strawberry.types.union impo...
141
3,438
strawberry
tests/objects/generics/test_generic_objects.py
.py
import datetime from typing import Annotated, Generic, TypeVar import pytest import strawberry from strawberry.types.base import ( StrawberryList, StrawberryOptional, StrawberryTypeVar, get_object_definition, ) from strawberry.types.union import StrawberryUnion T = TypeVar("T") def test_basic_gener...
645
17,647
strawberry
tests/typecheckers/test_type.py
.py
from inline_snapshot import snapshot from .utils.marks import requires_mypy, requires_pyright, requires_ty, skip_on_windows from .utils.typecheck import Result, typecheck pytestmark = [skip_on_windows, requires_pyright, requires_mypy, requires_ty] CODE = """ import strawberry from strawberry.types.base import Strawb...
189
5,789
strawberry
tests/typecheckers/test_fields_resolver.py
.py
from inline_snapshot import snapshot from .utils.marks import requires_mypy, requires_pyright, requires_ty, skip_on_windows from .utils.typecheck import Result, typecheck pytestmark = [skip_on_windows, requires_pyright, requires_mypy, requires_ty] CODE = """ import strawberry def get_user_age() -> int: return ...
106
2,768
strawberry
tests/typecheckers/test_fields_input.py
.py
from inline_snapshot import snapshot from .utils.marks import requires_mypy, requires_pyright, requires_ty, skip_on_windows from .utils.typecheck import Result, typecheck pytestmark = [skip_on_windows, requires_pyright, requires_mypy, requires_ty] CODE = """ import strawberry @strawberry.input class User: nam...
102
2,673
strawberry
tests/typecheckers/test_fastapi.py
.py
from inline_snapshot import snapshot from .utils.marks import requires_mypy, requires_pyright, requires_ty, skip_on_windows from .utils.typecheck import Result, typecheck pytestmark = [skip_on_windows, requires_pyright, requires_mypy, requires_ty] CODE_ROUTER_WITH_CONTEXT = """ import strawberry from strawberry.fas...
210
4,490
strawberry
tests/typecheckers/test_enum.py
.py
from inline_snapshot import snapshot from .utils.marks import requires_mypy, requires_pyright, requires_ty, skip_on_windows from .utils.typecheck import Result, typecheck pytestmark = [skip_on_windows, requires_pyright, requires_mypy, requires_ty] CODE_WITH_DECORATOR = """ from enum import Enum import strawberry @...
404
10,584