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

Convert example parameter into examples on Field #122

Merged
merged 3 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Empty file added .vscode/launch.json
Empty file.
17 changes: 11 additions & 6 deletions bump_pydantic/codemods/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"min_items": "min_length",
"max_items": "max_length",
"allow_mutation": "frozen",
"example": "examples",
"regex": "pattern",
# NOTE: This is only for BaseSettings.
"env": "validation_alias",
Expand Down Expand Up @@ -115,12 +116,16 @@ def leave_field_call(self, original_node: cst.Call, updated_node: cst.Call) -> c
if m.matches(arg, m.Arg(keyword=m.Name())):
keyword = RENAMED_KEYWORDS.get(arg.keyword.value, arg.keyword.value) # type: ignore
value = arg.value
# The `allow_mutation` keyword argument is a special case. It's the negative of `frozen`.
if arg.keyword and arg.keyword.value == "allow_mutation":
if m.matches(arg.value, m.Name(value="False")):
value = cst.Name("True")
elif m.matches(arg.value, m.Name(value="True")):
value = cst.Name("False")
if arg.keyword:
if arg.keyword.value == "allow_mutation":
# The `allow_mutation` keyword is the negative of `frozen`.
if m.matches(arg.value, m.Name(value="False")):
value = cst.Name("True")
elif m.matches(arg.value, m.Name(value="True")):
value = cst.Name("False")
if arg.keyword.value == "example":
# The example keyword is now a list, `examples`.
value = cst.List([arg.value])
Kludex marked this conversation as resolved.
Show resolved Hide resolved
new_arg = arg.with_changes(keyword=arg.keyword.with_changes(value=keyword), value=value) # type: ignore
new_args.append(new_arg) # type: ignore
else:
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,18 @@ class Potato(BaseModel):
potato: Annotated[List[int], Field(..., min_length=1, max_length=10)]
"""
self.assertCodemod(before, after)

def test_example_list(self) -> None:
before = """
from pydantic import BaseSettings, Field

class Settings(BaseSettings):
potato: int = Field(..., example=1)
"""
after = """
from pydantic import BaseSettings, Field

class Settings(BaseSettings):
potato: int = Field(..., examples=[1,])
"""
self.assertCodemod(before, after)