Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix pydantic type decorator - add missing internal methods #3366

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Release type: patch

Fix pydantic type decorator - add internal methods not copied by `dataclasses.make_dataclass()`
9 changes: 8 additions & 1 deletion strawberry/experimental/pydantic/object_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,14 +237,21 @@ def is_type_of(cls: Type, obj: Any, _info: GraphQLResolveInfo) -> bool:
else:
kwargs["init"] = False

cls = dataclasses.make_dataclass(
new_cls = dataclasses.make_dataclass(
cls.__name__,
[field.to_tuple() for field in all_model_fields],
bases=cls.__bases__,
namespace=namespace,
**kwargs, # type: ignore
)

# Add back attributes that were not copied (like internal methods)
for key, value in vars(cls).items():
if not hasattr(new_cls, key):
setattr(new_cls, key, value)

cls = new_cls

if sys.version_info < (3, 10, 1):
add_custom_init_fn(cls)

Expand Down
24 changes: 24 additions & 0 deletions tests/experimental/pydantic/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,30 @@ class UserType:
assert field3.type is other_sentinel


def test_basic_type_with_internal_method():
class User(pydantic.BaseModel):
age: int
password: Optional[str]

@strawberry.experimental.pydantic.type(User)
class UserType:
age: strawberry.auto
password: strawberry.auto

@strawberry.field
def password_hash(self) -> int:
return self.perform_hash(self.password)

def perform_hash(self, data: str) -> int:
return hash(data)

definition: StrawberryObjectDefinition = UserType.__strawberry_definition__
assert definition.name == "UserType"

assert len(definition.fields) == 3
assert hasattr(UserType, "perform_hash")


def test_referencing_other_models_fails_when_not_registered():
class Group(pydantic.BaseModel):
name: str
Expand Down
Loading