Skip to content

feat: add metadata form fixture and enhance field serialization for A… - #27

Closed
metaforx wants to merge 2 commits into
mainfrom
fix/metadata-serialization
Closed

feat: add metadata form fixture and enhance field serialization for A…#27
metaforx wants to merge 2 commits into
mainfrom
fix/metadata-serialization

Conversation

@metaforx

@metaforx metaforx commented May 5, 2026

Copy link
Copy Markdown
Owner

…PI responses

Summary by Sourcery

Expose additional field metadata in form fields API responses and add coverage for placeholder and initial values.

New Features:

  • Include placeholder and initial values in serialized form field metadata returned by the API.

Enhancements:

  • Normalize initial values for API responses via a helper that handles callables, None, and date-like objects.

Tests:

  • Add a metadata form fixture and tests asserting placeholder and initial values are present in the form fields API response.

@sourcery-ai

sourcery-ai Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adds a metadata form test fixture and extends the form-fields API to include placeholder and serialized initial values in responses, ensuring JSON-safe handling of initial values.

Sequence diagram for extended form-fields API response

sequenceDiagram
    actor Client
    participant APIView as FormFieldsAPIView
    participant ViewFn as get_form_fields
    participant Serializer as _serialize_initial
    participant DjangoField as DjangoFormField
    participant Response as DRFResponse

    Client->>APIView: GET /api/form-fields/{slug}
    APIView->>ViewFn: get_form_fields(request, slug)
    ViewFn->>DjangoField: iterate form.fields.items()
    DjangoField-->>ViewFn: field_name, field

    ViewFn->>DjangoField: read widget.attrs
    DjangoField-->>ViewFn: placeholder
    ViewFn->>DjangoField: read initial
    DjangoField-->>ViewFn: initial_value

    ViewFn->>Serializer: _serialize_initial(initial_value)
    Serializer-->>ViewFn: json_safe_initial

    ViewFn-->>APIView: list of field_info
    APIView->>Response: Response(field_info_list)
    Response-->>Client: 200 OK JSON (includes placeholder, initial)
Loading

File-Level Changes

Change Details Files
Add a form metadata fixture and tests to validate placeholder and initial values are exposed by the API.
  • Introduce a metadata_form pytest fixture that builds a form with text and date elements plus a db_store handler.
  • Configure the text element with a placeholder and the date element with an initial value to drive API behavior tests.
  • Add a test that calls the form-fields API and asserts the placeholder and initial values are present in the serialized field data.
tests/api/test_form_fields.py
Enhance form field serialization in the API to include placeholder and robustly serialized initial values.
  • Introduce a helper function to serialize initial values to JSON-friendly formats, handling callables, None, and isoformat-capable objects safely.
  • In get_form_fields, capture widget attrs and, when populated, include the placeholder attribute in the field metadata.
  • In get_form_fields, serialize field.initial via the helper and, when non-null, include it as an initial key in the API response.
src/unfold_fobi/api/views.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • In _serialize_initial, you currently return None for any callable initial; if some fields use callables to provide dynamic defaults, consider evaluating the callable or at least documenting why these are intentionally omitted from the API.
  • The _serialize_initial helper relies on hasattr(value, "isoformat"); you may want to narrow this to explicit datetime/date types (or similar) to avoid unexpected behavior for other objects that happen to expose an isoformat method.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `_serialize_initial`, you currently return `None` for any callable initial; if some fields use callables to provide dynamic defaults, consider evaluating the callable or at least documenting why these are intentionally omitted from the API.
- The `_serialize_initial` helper relies on `hasattr(value, "isoformat")`; you may want to narrow this to explicit `datetime`/`date` types (or similar) to avoid unexpected behavior for other objects that happen to expose an `isoformat` method.

## Individual Comments

### Comment 1
<location path="src/unfold_fobi/api/views.py" line_range="22-26" />
<code_context>
 from rest_framework.response import Response


+def _serialize_initial(value):
+    """Return a JSON-friendly initial value for API responses."""
+    if callable(value):
+        return None
+    if value is None:
+        return None
+    if hasattr(value, "isoformat"):
+        try:
+            return value.isoformat()
+        except Exception:
+            return value
+    return value
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Fallback branch may return non-JSON-serializable values despite the function's contract.

Because `isoformat()` failures fall through to returning the original `value`, this can still yield non-JSON-serializable objects. To preserve the contract and avoid runtime serialization errors, the `except` branch should convert to a safe type (e.g. `str(value)`) or return `None`/omit the field on failure.

```suggestion
    if hasattr(value, "isoformat"):
        try:
            return value.isoformat()
        except Exception:
            # Fall back to a string representation to keep the return JSON-serializable.
            return str(value)
```
</issue_to_address>

### Comment 2
<location path="src/unfold_fobi/api/views.py" line_range="176" />
<code_context>
     }

     for field_name, field in fields.items():
+        widget_attrs = getattr(getattr(field, "widget", None), "attrs", {})
         field_info = {
             "name": field_name,
</code_context>
<issue_to_address>
**issue:** Potential `AttributeError` if `widget.attrs` exists but is `None` rather than a dict.

If a custom widget sets `attrs = None`, this expression will return `None` and `widget_attrs.get("placeholder")` will raise `AttributeError`. Consider normalizing to a dict, e.g.:

```python
widget = getattr(field, "widget", None)
widget_attrs = getattr(widget, "attrs", {}) or {}
```

or use a type check after `getattr` to ensure `widget_attrs` is a dict before use.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/unfold_fobi/api/views.py Outdated
}

for field_name, field in fields.items():
widget_attrs = getattr(getattr(field, "widget", None), "attrs", {})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Potential AttributeError if widget.attrs exists but is None rather than a dict.

If a custom widget sets attrs = None, this expression will return None and widget_attrs.get("placeholder") will raise AttributeError. Consider normalizing to a dict, e.g.:

widget = getattr(field, "widget", None)
widget_attrs = getattr(widget, "attrs", {}) or {}

or use a type check after getattr to ensure widget_attrs is a dict before use.

@metaforx metaforx closed this May 5, 2026
@metaforx
metaforx deleted the fix/metadata-serialization branch May 5, 2026 15:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant