Skip to content

Commit

Permalink
Merge branch 'main' into stillmatic/main
Browse files Browse the repository at this point in the history
  • Loading branch information
patrick91 committed Aug 15, 2023
2 parents 74a74ec + 4fe8537 commit f3ec9cd
Show file tree
Hide file tree
Showing 6 changed files with 188 additions and 31 deletions.
49 changes: 49 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,55 @@
CHANGELOG
=========

0.203.3 - 2023-08-14
--------------------

Mark pydantic constrained list test with need_pydantic_v1 since it is removed in pydantic V2

Contributed by [tjeerddie](https://github.com/tjeerddie) via [PR #3034](https://github.com/strawberry-graphql/strawberry/pull/3034/)


0.203.2 - 2023-08-14
--------------------

Enhancements:
- Improved pydantic conversion compatibility with specialized list classes.
- Modified `StrawberryAnnotation._is_list` to check if the `annotation` extends from the `list` type, enabling it to be considered a list.
- in `StrawberryAnnotation` Moved the `_is_list` check before the `_is_generic` check in `resolve` to avoid `unsupported` error in `_is_generic` before it checked `_is_list`.

This enhancement enables the usage of constrained lists as class types and allows the creation of specialized lists. The following example demonstrates this feature:

```python
import strawberry
from pydantic import BaseModel, ConstrainedList


class FriendList(ConstrainedList):
min_items = 1


class UserModel(BaseModel):
age: int
friend_names: FriendList[str]


@strawberry.experimental.pydantic.type(UserModel)
class User:
age: strawberry.auto
friend_names: strawberry.auto
```

Contributed by [tjeerddie](https://github.com/tjeerddie) via [PR #2909](https://github.com/strawberry-graphql/strawberry/pull/2909/)


0.203.1 - 2023-08-12
--------------------

This release updates the built-in GraphiQL to the current latest version (3.0.5), it also updates React to the current latest version (18.2.0) and uses the production distribution instead of development to reduce bundle size.

Contributed by [Kien Dang](https://github.com/kiendang) via [PR #3031](https://github.com/strawberry-graphql/strawberry/pull/3031/)


0.203.0 - 2023-08-10
--------------------

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[tool.poetry]
name = "strawberry-graphql"
packages = [ { include = "strawberry" } ]
version = "0.203.0"
version = "0.203.3"
description = "A library for creating GraphQL APIs"
authors = ["Patrick Arminio <patrick.arminio@gmail.com>"]
license = "MIT"
Expand Down
12 changes: 9 additions & 3 deletions strawberry/annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ def resolve(self) -> Union[StrawberryType, type]:

if self._is_lazy_type(evaled_type):
return evaled_type
if self._is_list(evaled_type):
return self.create_list(evaled_type)

if self._is_generic(evaled_type):
if any(is_type_var(type_) for type_ in get_args(evaled_type)):
Expand All @@ -151,8 +153,6 @@ def resolve(self) -> Union[StrawberryType, type]:
# a StrawberryType
if self._is_enum(evaled_type):
return self.create_enum(evaled_type)
if self._is_list(evaled_type):
return self.create_list(evaled_type)
elif self._is_optional(evaled_type, args):
return self.create_optional(evaled_type)
elif self._is_union(evaled_type, args):
Expand Down Expand Up @@ -298,8 +298,14 @@ def _is_list(cls, annotation: Any) -> bool:
"""Returns True if annotation is a List"""

annotation_origin = get_origin(annotation)
annotation_mro = getattr(annotation, "__mro__", [])
is_list = any(x is list for x in annotation_mro)

return (annotation_origin in (list, tuple)) or annotation_origin is abc.Sequence
return (
(annotation_origin in (list, tuple))
or annotation_origin is abc.Sequence
or is_list
)

@classmethod
def _is_strawberry_type(cls, evaled_type: Any) -> bool:
Expand Down
44 changes: 18 additions & 26 deletions strawberry/static/graphiql.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@

<script
crossorigin
src="https://unpkg.com/react@17.0.2/umd/react.development.js"
integrity="sha384-xQwCoNcK/7P3Lpv50IZSEbJdpqbToWEODAUyI/RECaRXmOE2apWt7htari8kvKa/"
src="https://unpkg.com/react@18.2.0/umd/react.production.min.js"
integrity="sha384-tMH8h3BGESGckSAVGZ82T9n90ztNXxvdwvdM6UoR56cYcf+0iGXBliJ29D+wZ/x8"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"
integrity="sha384-E9IgxDsnjKgh0777N3lXen7NwXeTsOpLLJhI01SW7idG046SRqJpsW2rJwsOYk0L"
src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js"
integrity="sha384-bm7MnzvK++ykSwVJ2tynSE5TRdN+xL418osEVF2DE/L/gfWHj91J2Sphe582B1Bh"
></script>

<script
Expand All @@ -61,14 +61,14 @@
<link
crossorigin
rel="stylesheet"
href="https://unpkg.com/graphiql@2.4.7/graphiql.min.css"
integrity="sha384-486GcFFVcFN0yj7LIp/vn7DVsuf2CTytJlNuqjHg0zF2g72zra2gWCNV2HBxJgC6"
href="https://unpkg.com/graphiql@3.0.5/graphiql.min.css"
integrity="sha384-yz3/sqpuplkA7msMo0FE4ekg0xdwdvZ8JX9MVZREsxipqjU4h8IRfmAMRcb1QpUy"
/>

<link
crossorigin
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@graphiql/plugin-explorer@0.1.15/dist/style.css"
href="https://unpkg.com/@graphiql/plugin-explorer@0.3.4/dist/style.css"
integrity="sha384-kOrlMT58B3t0hTVIPFqWyg1oL4DKvxHNcC1X2qugv4fXd9ehKULhhjDLvBi3HoEK"
/>
</head>
Expand All @@ -77,13 +77,13 @@
<div id="graphiql" class="graphiql-container">Loading...</div>
<script
crossorigin
src="https://unpkg.com/graphiql@2.4.7/graphiql.min.js"
integrity="sha384-8da92RVD56z/pbOOnJ4Ud5qlhqEzDtJI6qVZjN88SCbOatpo4xVDeP3T0nmfTf+9"
src="https://unpkg.com/graphiql@3.0.5/graphiql.min.js"
integrity="sha384-M+Ed4RZlnWvJ8keiTju1xlV6xM5tB9tLTfoSdWPDVrK4aOOpavtruK9pz/dfuCZ/"
></script>
<script
crossorigin
src="https://unpkg.com/@graphiql/plugin-explorer@0.1.15/dist/graphiql-plugin-explorer.umd.js"
integrity="sha384-730PslzMVMN3EMJOKuh/WVRaRwhaBbWE43IOXyR+DMDlQiYx0BjiPmoPZ+6qEa0C"
src="https://unpkg.com/@graphiql/plugin-explorer@0.3.4/dist/index.umd.js"
integrity="sha384-2oonKe47vfHIZnmB6ZZ10vl7T0Y+qrHQF2cmNTaFDuPshpKqpUMGMc9jgj9MLDZ9"
></script>
<script>
const EXAMPLE_QUERY = `# Welcome to GraphiQL 🍓
Expand Down Expand Up @@ -142,25 +142,17 @@
subscriptionUrl,
});

function GraphiQLWithExplorer() {
const [query, setQuery] = React.useState(EXAMPLE_QUERY);
const explorerPlugin = GraphiQLPluginExplorer.useExplorerPlugin({
query: query,
onEdit: setQuery,
});
return React.createElement(GraphiQL, {
const explorerPlugin = GraphiQLPluginExplorer.explorerPlugin();

const root = ReactDOM.createRoot(document.getElementById("graphiql"));

root.render(
React.createElement(GraphiQL, {
fetcher: fetcher,
defaultEditorToolsVisibility: true,
plugins: [explorerPlugin],
query: query,
onEditQuery: setQuery,
inputValueDeprecation: true,
});
}

ReactDOM.render(
React.createElement(GraphiQLWithExplorer),
document.getElementById("graphiql")
}),
);
</script>
</body>
Expand Down
37 changes: 37 additions & 0 deletions tests/experimental/pydantic/schema/test_basic.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import sys
import textwrap
from enum import Enum
from typing import List, Optional, Union

import pydantic
import pytest

import strawberry
from tests.experimental.pydantic.utils import needs_pydantic_v1


def test_basic_type_field_list():
Expand Down Expand Up @@ -526,3 +529,37 @@ def user(self) -> User:
assert not result.errors
assert result.data["user"]["age"] == 1
assert result.data["user"]["password"] is None


@needs_pydantic_v1
@pytest.mark.skipif(
sys.version_info < (3, 9),
reason="ConstrainedList with another model does not work with 3.8",
)
def test_basic_type_with_constrained_list():
class FriendList(pydantic.ConstrainedList):
min_items = 1

class UserModel(pydantic.BaseModel):
age: int
friend_names: FriendList[str]

@strawberry.experimental.pydantic.type(UserModel)
class User:
age: strawberry.auto
friend_names: strawberry.auto

@strawberry.type
class Query:
@strawberry.field
def user(self) -> User:
return User(age=1, friend_names=["A", "B"])

schema = strawberry.Schema(query=Query)

query = "{ user { friendNames } }"

result = schema.execute_sync(query)

assert not result.errors
assert result.data["user"]["friendNames"] == ["A", "B"]
75 changes: 74 additions & 1 deletion tests/experimental/pydantic/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import re
import sys
from enum import Enum
from typing import Any, Dict, List, NewType, Optional, Union
from typing import Any, Dict, List, NewType, Optional, TypeVar, Union

import pytest
from pydantic import BaseModel, Field, ValidationError
Expand All @@ -21,6 +21,7 @@
from strawberry.experimental.pydantic.utils import get_default_factory_for_field
from strawberry.type import StrawberryList, StrawberryOptional
from strawberry.types.types import StrawberryObjectDefinition
from tests.experimental.pydantic.utils import needs_pydantic_v1

if IS_PYDANTIC_V2:
pass
Expand Down Expand Up @@ -1225,3 +1226,75 @@ class Test:

assert test.optional_list == [1, 2, 3]
assert test.optional_str is None


@needs_pydantic_v1
@pytest.mark.skipif(
sys.version_info < (3, 9),
reason="ConstrainedList with another model does not work with 3.8",
)
def test_can_convert_pydantic_type_to_strawberry_with_constrained_list():
from pydantic import ConstrainedList

class WorkModel(BaseModel):
name: str

class workList(ConstrainedList):
min_items = 1

class UserModel(BaseModel):
work: workList[WorkModel]

@strawberry.experimental.pydantic.type(WorkModel)
class Work:
name: strawberry.auto

@strawberry.experimental.pydantic.type(UserModel)
class User:
work: strawberry.auto

origin_user = UserModel(
work=[WorkModel(name="developer"), WorkModel(name="tester")]
)

user = User.from_pydantic(origin_user)

assert user == User(work=[Work(name="developer"), Work(name="tester")])


SI = TypeVar("SI", covariant=True) # pragma: no mutate


class SpecialList(List[SI]):
pass


@needs_pydantic_v1
@pytest.mark.skipif(
sys.version_info < (3, 9), reason="SpecialList does not work with 3.8"
)
def test_can_convert_pydantic_type_to_strawberry_with_specialized_list():
class WorkModel(BaseModel):
name: str

class workList(SpecialList[SI]):
min_items = 1

class UserModel(BaseModel):
work: workList[WorkModel]

@strawberry.experimental.pydantic.type(WorkModel)
class Work:
name: strawberry.auto

@strawberry.experimental.pydantic.type(UserModel)
class User:
work: strawberry.auto

origin_user = UserModel(
work=[WorkModel(name="developer"), WorkModel(name="tester")]
)

user = User.from_pydantic(origin_user)

assert user == User(work=[Work(name="developer"), Work(name="tester")])

0 comments on commit f3ec9cd

Please sign in to comment.