def test_error_when_registering_duplicate_scalar(): with pytest.raises(ScalarAlreadyRegisteredError) as error: strawberry.scalar(uuid.UUID, name="UUID", serialize=str, parse_value=uuid.UUID) assert str(error.value) == "Scalar `UUID` has already been registered"
def test_override_built_in_scalars(): EpochDateTime = strawberry.scalar( datetime, serialize=lambda value: int(value.timestamp()), parse_value=lambda value: datetime.fromtimestamp( int(value), timezone.utc), ) @strawberry.type class Query: @strawberry.field def current_time(self) -> datetime: return datetime(2021, 8, 11, 12, 0, tzinfo=timezone.utc) @strawberry.field def isoformat(self, input_datetime: datetime) -> str: return input_datetime.isoformat() schema = strawberry.Schema( Query, scalar_overrides={ datetime: EpochDateTime, }, ) result = schema.execute_sync(""" { currentTime isoformat(inputDatetime: 1628683200) } """) assert not result.errors assert result.data["currentTime"] == 1628683200 assert result.data["isoformat"] == "2021-08-11T12:00:00+00:00"
def test_can_register_python_types(): strawberry.scalar(uuid.UUID, name="UUID", serialize=str, parse_value=uuid.UUID) @strawberry.type class Query: @strawberry.field def answer(self, info) -> uuid.UUID: return uuid.UUID(int=1) schema = strawberry.Schema(Query) result = schema.execute_sync("{ answer }") assert not result.errors assert result.data["answer"] == "00000000-0000-0000-0000-000000000001"
def test_duplicate_scalars(): MyCustomScalar = strawberry.scalar( str, name="MyCustomScalar", ) MyCustomScalar2 = strawberry.scalar( int, name="MyCustomScalar", ) @strawberry.type class Query: scalar_1: MyCustomScalar scalar_2: MyCustomScalar2 with pytest.raises( TypeError, match="Scalar `MyCustomScalar` has already been registered"): strawberry.Schema(Query)
def test_override_unknown_scalars(): Duration = strawberry.scalar( timedelta, name="Duration", serialize=timedelta.total_seconds, parse_value=lambda s: timedelta(seconds=s), ) @strawberry.type class Query: @strawberry.field def duration(self, value: timedelta) -> timedelta: return value schema = strawberry.Schema(Query, scalar_overrides={timedelta: Duration}) result = schema.execute_sync("{ duration(value: 10) }") assert not result.errors assert result.data == {"duration": 10}
import base64 from typing import NewType import strawberry Base64Encoded = strawberry.scalar( NewType("Base64Encoded", bytes), serialize=base64.b64encode, parse_value=base64.b64decode, ) @strawberry.scalar(serialize=lambda x: 42, parse_value=lambda x: Always42()) class Always42: pass MyStr = strawberry.scalar(NewType("MyStr", str)) def test_custom_scalar_serialization(): @strawberry.type class Query: @strawberry.field def custom_scalar_field(self) -> Base64Encoded: return Base64Encoded(b"decoded value") schema = strawberry.Schema(Query) result = schema.execute_sync("{ customScalarField }")
If the string is empty afterward, a ValueError will be raised. (since this function is intended to be used as a scalar; strawberry will convert the value error into a validation error on the field) """ fixed = WHITESPACE_REGEX.sub(" ", title.strip()) if fixed: return fixed else: raise ValueError("PostTitle cannot contain only whitespace.") PostTitle = strawberry.scalar( NewType("PostTitle", str), description= "A post title, within which all whitespace is collapsed: e.g. ' foo bar ' -> 'foo bar'", parse_value=parse_title, ) @strawberry.type(name="Post_") class Post(AppPost): id: int author_id: strawberry.ID title: str content: str created: datetime updated: datetime @strawberry.field async def author(self, info: Info[AppContext, AppRequest]) -> Person:
import strawberry from time import sleep from enum import Enum from functools import lru_cache from skema.cli import Gen from typing import * import json Json = strawberry.scalar(NewType("Json", Any), serialize=lambda x: x, parse_value=lambda x: x) @strawberry.enum class LanguageName(Enum): python = "python" typescript = "typescript" jsonschema = "jsonschema" graphql = "grphql" gen = Gen() def get_schema(language): func = getattr(Gen, language) if not func: raise Exception(f"lang {language} not found") skema: str = func.__doc__ skema = skema.strip() if not skema:
from .result import Result @strawberry.interface class AppError: message: str GraphQLErrorType = TypeVar("GraphQLErrorType", bound=AppError) ValueType = TypeVar("ValueType") GraphQLResult = Result[ValueType, GraphQLErrorType] ID = strawberry.scalar( NewType("ID", str), serialize=lambda v: base64.b64encode(v.encode("utf-8")).decode("utf-8"), parse_value=lambda v: base64.b64decode(v.encode("utf-8")).decode("utf-8"), ) @strawberry.type class InternalError(AppError): def __init__(self, original_exception: Optional[Exception] = None): self.original_exception = original_exception if original_exception: logging.error(f"Operation failed: {str(original_exception)}") logging.error( "".join(traceback.format_tb(original_exception.__traceback__)) )
from typing import Generic, List, NewType, TypeVar import pytest import strawberry from strawberry.enum import EnumDefinition from strawberry.lazy_type import LazyType from strawberry.schema.config import StrawberryConfig from strawberry.type import StrawberryList, StrawberryOptional from strawberry.union import StrawberryUnion T = TypeVar("T") Enum = EnumDefinition(None, name="Enum", values=[], description=None) # type: ignore CustomInt = strawberry.scalar(NewType("CustomInt", int)) @strawberry.type class TypeA: name: str @strawberry.type class TypeB: age: int @pytest.mark.parametrize( "types,expected_name", [
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import json from typing import NewType import strawberry JSONScalar = strawberry.scalar( NewType("JSONScalar", object), serialize=lambda v: v, parse_value=lambda v: json.loads(v), description= "The GenericScalar scalar type represents a generic GraphQL scalar value.", )