def test_uses_default_for_optional_types_when_nothing_is_passed(): @strawberry.input class Number: value: int @strawberry.input class Input: numbers: Optional[Number] = UNSET numbers_second: Optional[Number] = UNSET # case 1 args = {"input": {}} arguments = [ StrawberryArgument( graphql_name=None, python_name="input", type_annotation=StrawberryAnnotation(Input), ), ] assert (convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "input": Input(UNSET, UNSET) }) # case 2 args = {"input": {"numbersSecond": None}} arguments = [ StrawberryArgument( graphql_name=None, python_name="input", type_annotation=StrawberryAnnotation(Input), ), ] assert (convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "input": Input(UNSET, None) })
def test_when_optional(): @strawberry.input class Number: value: int @strawberry.input class Input: numbers: Optional[Number] = UNSET numbers_second: Optional[Number] = UNSET args = {} arguments = [ StrawberryArgument( graphql_name=None, python_name="input", type_annotation=StrawberryAnnotation(Optional[Input]), ) ] assert (convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == {})
def test_list(): args = { "integerList": [1, 2], "stringList": ["abc", "cde"], } arguments = [ StrawberryArgument( graphql_name="integerList", python_name="integer_list", type_annotation=StrawberryAnnotation(List[int]), ), StrawberryArgument( graphql_name="stringList", python_name="string_list", type_annotation=StrawberryAnnotation(List[str]), ), ] assert convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "integer_list": [1, 2], "string_list": ["abc", "cde"], }
def test_input_types(): @strawberry.input class MyInput: abc: str say_hello_to: str fun: str was: int = strawberry.field(name="having") args = { "input": { "abc": "example", "sayHelloTo": "Patrick", "having": 10, "fun": "yes" } } arguments = [ StrawberryArgument( graphql_name=None, python_name="input", type_annotation=StrawberryAnnotation(MyInput), ), ] assert (convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "input": MyInput(abc="example", say_hello_to="Patrick", was=10, fun="yes") })
def test_lazy(): LazierType = LazyType["LaziestType", __name__] args = { "lazyArg": { "something": True }, } arguments = [ StrawberryArgument( graphql_name="lazyArg", python_name="lazy_arg", type_annotation=StrawberryAnnotation(LazierType), ), ] assert (convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "lazy_arg": LaziestType(something=True) })
def test_can_set_camel_casing_to_false_uses_name_field_decorator(): @strawberry.type class Query: @strawberry.field(name="exampleField") def example_field(self) -> str: return "ABC" schema = strawberry.Schema( query=Query, config=StrawberryConfig(auto_camel_case=False) ) query = """ { __type(name: "Query") { fields { name } } } """ result = schema.execute_sync(query) assert not result.errors assert result.data["__type"]["fields"] == [{"name": "exampleField"}]
def test_can_turn_camel_case_off_arguments(): @strawberry.type class Query: @strawberry.field def example_field(self, example_input: str) -> str: return example_input schema = strawberry.Schema( query=Query, config=StrawberryConfig(auto_camel_case=False) ) query = """ { __type(name: "Query") { fields { name args { name } } } } """ result = schema.execute_sync(query, root_value=Query()) assert not result.errors assert result.data["__type"]["fields"] == [ {"args": [{"name": "example_input"}], "name": "example_field"} ]
def test_nested_list_of_complex_types(): @strawberry.input class Number: value: int @strawberry.input class Input: numbers: List[Number] args = {"input": {"numbers": [{"value": 1}, {"value": 2}]}} arguments = [ StrawberryArgument( graphql_name=None, python_name="input", type_annotation=StrawberryAnnotation(Input), ), ] assert (convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "input": Input(numbers=[Number(1), Number(2)]) })
def test_name_generation(types, expected_name): config = StrawberryConfig() @strawberry.type class Example(Generic[T]): a: T type_definition = Example._type_definition # type: ignore assert config.name_converter.from_generic(type_definition, types) == expected_name
def test_printer_with_camel_case_off(): @strawberry.type class Query: hello_world: str expected_type = """ type Query { hello_world: String! } """ schema = strawberry.Schema( query=Query, config=StrawberryConfig(auto_camel_case=False) ) assert print_schema(schema) == textwrap.dedent(expected_type).strip()
def test_runs_directives_camel_case_off(): @strawberry.type class Person: name: str = "Jess" @strawberry.type class Query: @strawberry.field def person(self) -> Person: return Person() @strawberry.directive(locations=[DirectiveLocation.FIELD], description="Make string uppercase") def turn_uppercase(value: str): return value.upper() @strawberry.directive(locations=[DirectiveLocation.FIELD]) def replace(value: str, old: str, new: str): return value.replace(old, new) schema = strawberry.Schema( query=Query, directives=[turn_uppercase, replace], config=StrawberryConfig(auto_camel_case=False), ) query = """query People($identified: Boolean!){ person { name @turn_uppercase } jess: person { name @replace(old: "Jess", new: "Jessica") } johnDoe: person { name @replace(old: "Jess", new: "John") @include(if: $identified) } }""" result = schema.execute_sync(query, variable_values={"identified": False}) assert not result.errors assert result.data["person"]["name"] == "JESS" assert result.data["jess"]["name"] == "Jessica" assert result.data["johnDoe"].get("name") is None
def test_nested_generics(): config = StrawberryConfig() @strawberry.type class Edge(Generic[T]): node: T @strawberry.type class Connection(Generic[T]): edges: List[T] type_definition = Connection._type_definition # type: ignore assert (config.name_converter.from_generic( type_definition, [ Edge[int], ], ) == "IntEdgeConnection")
def test_can_turn_camel_case_off_arguments_conversion_works(): @strawberry.type class Query: @strawberry.field def example_field(self, example_input: str) -> str: return example_input schema = strawberry.Schema( query=Query, config=StrawberryConfig(auto_camel_case=False) ) query = """ { example_field(example_input: "Hello world") } """ result = schema.execute_sync(query, root_value=Query()) assert not result.errors assert result.data["example_field"] == "Hello world"
def test_optional_list_of_input_types(): @strawberry.input class MyInput: abc: str args = {"inputList": [{"abc": "example"}]} arguments = [ StrawberryArgument( graphql_name="inputList", python_name="input_list", type_annotation=StrawberryAnnotation(Optional[List[MyInput]]), ), ] assert (convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "input_list": [MyInput(abc="example")] })
def test_can_set_camel_casing_to_false(): @strawberry.type class Query: example_field: str = "Example" schema = strawberry.Schema( query=Query, config=StrawberryConfig(auto_camel_case=False) ) query = """ { __type(name: "Query") { fields { name } } } """ result = schema.execute_sync(query, root_value=Query()) assert not result.errors assert result.data["__type"]["fields"] == [{"name": "example_field"}]
def test_simple_types(): args = {"integer": 1, "string": "abc", "float": 1.2, "bool": True} arguments = [ StrawberryArgument( graphql_name="integer", type_annotation=StrawberryAnnotation(int), python_name="integer", ), StrawberryArgument( graphql_name="string", type_annotation=StrawberryAnnotation(str), python_name="string", ), StrawberryArgument( graphql_name="float", type_annotation=StrawberryAnnotation(float), python_name="float", ), StrawberryArgument( graphql_name="bool", type_annotation=StrawberryAnnotation(bool), python_name="bool", ), ] assert convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "integer": 1, "string": "abc", "float": 1.2, "bool": True, }
ret_data = [] for obj in links_dict: info.context['data'] = obj network_link_data = network_link() ret_data.append(network_link_data) return ret_data class uuid_query_operator_input: value_eq: typing.Optional[str] value_ne: typing.OPtional[str] @strawberry.type class Query: network_links: typing.List[network_link] = strawberry.field( resolver=network_links) schema = strawberry.Schema(query=Query, config=StrawberryConfig(auto_camel_case=False)) graphql_app = GraphQL(schema) app = FastAPI() app.add_route("/graphql", graphql_app) app.add_websocket_route("/graphql", graphql_app) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)
return libraries[index] def resolve_storage(self, info): return storage def resolve_search(self, info, contains): search_books = [b for b in books if contains in b.name] search_magazines = [m for m in magazines if contains in m.name] return search_books + search_magazines def resolve_hello(self, info): return "Hello!" def resolve_echo(self, info, echo): return echo def resolve_error(self, info) -> str: raise RuntimeError("Runtime Error!") @strawberry.type class Mutation: @strawberry.mutation def storage_add(self, string: str) -> str: storage.append(string) return str(string) _target_application = Schema(query=Query, mutation=Mutation, config=StrawberryConfig(auto_camel_case=False)) _target_asgi_application = GraphQL(_target_application)
import strawberry from strawberry.schema.config import StrawberryConfig from strawberry.types import Info def first_name_func(root: User, info: Info) -> str: return f"Some {info.field_name}" def last_name_func(root: User, info: Info) -> str: return f"Test {info.field_name}" @strawberry.type class User: first_name: str = strawberry.field(resolver=first_name_func) last_name: str = strawberry.field(resolver=last_name_func) @strawberry.type class Query: @strawberry.field def last_user(self) -> User: return User() schema = strawberry.Schema( query=Query, config=StrawberryConfig() )
def test_nested_input_types(): @strawberry.enum class ChangeType(Enum): MAJOR = "major" MINOR = "minor" PATCH = "patch" @strawberry.input class ReleaseInfo: change_type: ChangeType changelog: str @strawberry.enum class ReleaseFileStatus(Enum): MISSING = "missing" INVALID = "invalid" OK = "ok" @strawberry.input class AddReleaseFileCommentInput: pr_number: int status: ReleaseFileStatus release_info: Optional[ReleaseInfo] args = { "input": { "prNumber": 12, "status": ReleaseFileStatus.OK.value, "releaseInfo": { "changeType": ChangeType.MAJOR.value, "changelog": "example", }, } } arguments = [ StrawberryArgument( graphql_name=None, python_name="input", type_annotation=StrawberryAnnotation(AddReleaseFileCommentInput), ), ] assert convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "input": AddReleaseFileCommentInput( pr_number=12, status=ReleaseFileStatus.OK, release_info=ReleaseInfo(change_type=ChangeType.MAJOR, changelog="example"), ) } args = { "input": { "prNumber": 12, "status": ReleaseFileStatus.OK.value, "releaseInfo": None, } } arguments = [ StrawberryArgument( graphql_name=None, python_name="input", type_annotation=StrawberryAnnotation(AddReleaseFileCommentInput), ), ] assert convert_arguments( args, arguments, scalar_registry=DEFAULT_SCALAR_REGISTRY, config=StrawberryConfig(), ) == { "input": AddReleaseFileCommentInput(pr_number=12, status=ReleaseFileStatus.OK, release_info=None) }
def test_field_provides_are_printed_correctly_camel_case_off(): global Review @strawberry.federation.type class User: username: str @strawberry.federation.type(keys=["upc"], extend=True) class Product: upc: str = strawberry.federation.field(external=True) the_name: str = strawberry.federation.field(external=True) reviews: List["Review"] @strawberry.federation.type class Review: body: str author: User product: Product = strawberry.federation.field(provides=["name"]) @strawberry.federation.type class Query: @strawberry.field def top_products(self, first: int) -> List[Product]: return [] schema = strawberry.federation.Schema( query=Query, config=StrawberryConfig(auto_camel_case=False)) expected = """ extend type Product @key(fields: "upc") { upc: String! @external the_name: String! @external reviews: [Review!]! } type Query { _service: _Service! _entities(representations: [_Any!]!): [_Entity]! top_products(first: Int!): [Product!]! } type Review { body: String! author: User! product: Product! @provides(fields: "name") } type User { username: String! } scalar _Any union _Entity = Product type _Service { sdl: String! } """ assert schema.as_str() == textwrap.dedent(expected).strip() del Review