File: test_field_exceptions.py

package info (click to toggle)
strawberry-graphql 0.306.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 18,176 kB
  • sloc: javascript: 178,052; python: 65,643; sh: 33; makefile: 25
file content (68 lines) | stat: -rw-r--r-- 2,048 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import textwrap
from typing import Any

import pytest

import strawberry
from strawberry.annotation import StrawberryAnnotation
from strawberry.exceptions import (
    FieldWithResolverAndDefaultFactoryError,
    FieldWithResolverAndDefaultValueError,
)
from strawberry.extensions.field_extension import FieldExtension
from strawberry.types.field import StrawberryField


def test_field_with_resolver_default():
    with pytest.raises(FieldWithResolverAndDefaultValueError):

        @strawberry.type
        class Query:
            @strawberry.field(default="potato")
            def fruit(self) -> str:
                return "tomato"


def test_field_with_separate_resolver_default():
    def fruit_resolver() -> str:  # pragma: no cover
        return "strawberry"

    with pytest.raises(FieldWithResolverAndDefaultValueError):

        @strawberry.type
        class Query:
            weapon: str = strawberry.field(default="banana", resolver=fruit_resolver)


def test_field_with_resolver_default_factory():
    with pytest.raises(FieldWithResolverAndDefaultFactoryError):

        @strawberry.type
        class Query:
            @strawberry.field(default_factory=lambda: "steel")
            def metal(self) -> str:
                return "iron"


def test_extension_changing_field_return_value():
    """Ensure that field extensions can change the field's return type."""

    class ChangeReturnTypeExtension(FieldExtension):
        def apply(self, field: StrawberryField) -> None:
            field.type_annotation = StrawberryAnnotation.from_annotation(int)

        def resolve(self, next_, source, info, **kwargs: Any):
            return next_(source, info, **kwargs)

    @strawberry.type
    class Query:
        @strawberry.field(extensions=[ChangeReturnTypeExtension()])
        def test_changing_return_type(self) -> bool: ...

    schema = strawberry.Schema(query=Query)
    expected = """\
      type Query {
        testChangingReturnType: Int!
      }
    """
    assert str(schema) == textwrap.dedent(expected).strip()