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

Do not duplicate classmethod when replacing validators #160

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
6 changes: 4 additions & 2 deletions bump_pydantic/codemods/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,10 @@ def leave_validator_func(self, original_node: cst.FunctionDef, updated_node: cst
self._should_add_comment = False
return updated_node

classmethod_decorator = cst.Decorator(decorator=cst.Name("classmethod"))
return updated_node.with_changes(decorators=[*updated_node.decorators, classmethod_decorator])
if not any(m.matches(d, m.Decorator(decorator=m.Name("classmethod"))) for d in updated_node.decorators):
classmethod_decorator = cst.Decorator(decorator=cst.Name("classmethod"))
updated_node = updated_node.with_changes(decorators=[*updated_node.decorators, classmethod_decorator])
return updated_node

def _decorator_with_leading_comment(self, node: cst.Decorator, comment: str) -> cst.Decorator:
return node.with_changes(
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,39 @@ def _string_validator(cls, v: t.Any) -> t.Optional[str]:
from pydantic import field_validator


class Potato(BaseModel):
name: str
dialect: str

@field_validator("name", "dialect")
@classmethod
def _string_validator(cls, v: t.Any) -> t.Optional[str]:
if isinstance(v, exp.Expression):
return v.name.lower()
return str(v).lower() if v is not None else None
"""
self.assertCodemod(before, after)

def test_replace_validator_with_existing_classmethod(self) -> None:
before = """
from pydantic import validator


class Potato(BaseModel):
name: str
dialect: str

@validator("name", "dialect")
@classmethod
def _string_validator(cls, v: t.Any) -> t.Optional[str]:
if isinstance(v, exp.Expression):
return v.name.lower()
return str(v).lower() if v is not None else None
"""
after = """
from pydantic import field_validator


class Potato(BaseModel):
name: str
dialect: str
Expand Down