Skip to content

Commit

Permalink
fix: Don't crash when trying to evaluate AST literals (field descript…
Browse files Browse the repository at this point in the history
…ions)

Issue-16: #16
  • Loading branch information
pawamoy committed Dec 3, 2024
1 parent 6084186 commit b41bf46
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/griffe_pydantic/static.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,10 @@ def process_attribute(attr: Attribute, cls: Class, *, processed: set[str]) -> No

# Populate docstring from the field's `description` argument.
if not attr.docstring and (docstring := kwargs.get("description", None)):
attr.docstring = Docstring(ast.literal_eval(docstring), parent=attr) # type: ignore[arg-type]
try:
attr.docstring = Docstring(ast.literal_eval(docstring), parent=attr) # type: ignore[arg-type]
except ValueError:
logger.debug(f"Could not parse description of field '{attr.path}' as literal, skipping")


def process_function(func: Function, cls: Class, *, processed: set[str]) -> None:
Expand Down
26 changes: 26 additions & 0 deletions tests/test_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

import pytest
from griffe import Extensions, temporary_visited_package

from griffe_pydantic.extension import PydanticExtension
Expand Down Expand Up @@ -120,3 +122,27 @@ class Model(BaseModel):
extensions=Extensions(PydanticExtension(schema=False)),
) as package:
python_handler.render(package["Model"], {}) # Assert no errors.


def test_not_crashing_on_dynamic_field_description(caplog: pytest.LogCaptureFixture) -> None:
"""Test the extension with dynamic field description."""
code = """
import pydantic
desc = "xyz"
class TestModel(pydantic.BaseModel):
abc: str = pydantic.Field(description=desc)
"""
with (
caplog.at_level(logging.DEBUG),
temporary_visited_package(
"package",
modules={"__init__.py": code},
extensions=Extensions(PydanticExtension(schema=False)),
),
):
assert any(
record.levelname == "DEBUG" and "field 'package.TestModel.abc' as literal" in record.message
for record in caplog.records
)

0 comments on commit b41bf46

Please sign in to comment.