Skip to content

Conversation

@fsbraun
Copy link
Member

@fsbraun fsbraun commented Dec 15, 2025

Summary by Sourcery

Validate cms_component template names and document their constraints.

Bug Fixes:

  • Reject non-string or non-identifier component names in the cms_component template tag to prevent invalid registrations.

Documentation:

  • Document that cms_component names must be valid Python identifiers in the template components tutorial.

Tests:

  • Add tests verifying cms_component raises ValueError for invalid component identifiers and accepts valid ones.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 15, 2025

Reviewer's Guide

Adds validation for cms_component template tag names to ensure they are string Python identifiers and extends tests to cover valid and invalid component names, improving error clarity and robustness of template component usage.

Flow diagram for cms_component template tag validation

flowchart TD
    A[start cms_component_tag] --> B[check _cms_components in context]
    B -->|not present| C[return empty string]
    B -->|present| D[check len args == 1]
    D -->|no| E[raise ValueError: requires exactly one positional argument]
    D -->|yes| F[check isinstance args_0 str]
    F -->|no| G[raise ValueError: component name must be a string]
    F -->|yes| H[check args_0 isidentifier]
    H -->|no| I[raise ValueError: component name must be a valid Python identifier]
    H -->|yes| J["append (args, kwargs) to context _cms_components cms_component"]
    J --> K[return empty string]
Loading

File-Level Changes

Change Details Files
Validate cms_component template tag arguments and enforce Python identifier naming for component names.
  • Require exactly one positional argument to be a string before using it as a component name.
  • Add a type check that raises ValueError when the component name is not a string.
  • Add an identifier check using isidentifier() and raise ValueError when the component name is not a valid Python identifier.
  • Append validated component definitions to the _cms_components['cms_component'] list in the template context.
djangocms_frontend/templatetags/cms_component.py
Add tests ensuring cms_component accepts valid names and rejects invalid identifiers with clear ValueError messages.
  • Create a test that initializes a template Context containing the _cms_components registry.
  • Verify that calling cms_component with a valid identifier appends one entry to the cms_component list.
  • Assert that various invalid names (containing hyphens, starting with digits, containing spaces, or empty) each raise ValueError.
  • Check that raised ValueError messages mention the requirement for a valid Python identifier.
tests/test_autocomponent.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

@codecov
Copy link

codecov bot commented Dec 15, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.01%. Comparing base (ac8a4d5) to head (57ca56b).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #333      +/-   ##
==========================================
+ Coverage   89.00%   89.01%   +0.01%     
==========================================
  Files         124      124              
  Lines        3383     3387       +4     
  Branches      287      289       +2     
==========================================
+ Hits         3011     3015       +4     
  Misses        256      256              
  Partials      116      116              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • In cms_component, consider extracting the argument validation (arity check, type check, identifier check) into a small helper function so that the tag implementation remains focused on registering the component and the validation logic is easier to reuse or adjust.
  • In test_cms_component_invalid_identifier, using the same Context instance for both the successful and failing calls couples the invalid-name checks to the side effects of the first call; consider using a fresh Context for each assertion or resetting _cms_components between checks to keep each case independent.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `cms_component`, consider extracting the argument validation (arity check, type check, identifier check) into a small helper function so that the tag implementation remains focused on registering the component and the validation logic is easier to reuse or adjust.
- In `test_cms_component_invalid_identifier`, using the same `Context` instance for both the successful and failing calls couples the invalid-name checks to the side effects of the first call; consider using a fresh `Context` for each assertion or resetting `_cms_components` between checks to keep each case independent.

## Individual Comments

### Comment 1
<location> `djangocms_frontend/templatetags/cms_component.py:33-36` </location>
<code_context>
     if "_cms_components" in context:
         if len(args) != 1:  # pragma: no cover
             raise ValueError("The cms_component tag requires exactly one positional argument: the component name.")
+        if not isinstance(args[0], str):
+            raise ValueError("The component name must be a string.")
+        if not args[0].isidentifier():
+            raise ValueError("The component name must be a valid Python identifier.")
         context["_cms_components"]["cms_component"].append((args, kwargs))
     return ""
</code_context>

<issue_to_address>
**suggestion:** Reconsider coupling component-name validation to Python identifiers via `isidentifier()`.

`str.isidentifier()` applies Python identifier rules (no hyphens, dots, spaces, etc.), which may be stricter than intended for template component names. If you just need to reject clearly invalid values (empty/whitespace/unsafe characters), a dedicated check (e.g., regex or explicit allowed character set) would give more control and avoid rejecting names like `hero-banner` or `card.1`. It’d be good to confirm the expected naming convention and align validation with that instead of Python identifier semantics.

Suggested implementation:

```python
import re
from django import template

```

```python
register = template.Library()

# Allow simple, URL‑style component names like "hero-banner" or "card.1".
# Restrict to a safe, predictable character set: letters, digits, underscore, hyphen, and dot.
COMPONENT_NAME_RE = re.compile(r"[A-Za-z0-9_.-]+")

```

```python
        if not isinstance(args[0], str):
            raise ValueError("The component name must be a string.")
        if not COMPONENT_NAME_RE.fullmatch(args[0]):
            raise ValueError(
                "The component name may only contain letters, numbers, hyphens (-), underscores (_), and dots (.)."
            )

```
</issue_to_address>

### Comment 2
<location> `tests/test_autocomponent.py:110-115` </location>
<code_context>
         with self.assertRaises(TemplateSyntaxError):
             Template(invalid_template)

+    def test_cms_component_invalid_identifier(self):
+        # Test that cms_component tag raises ValueError for invalid identifiers
+        from django.template import Context
+        from djangocms_frontend.templatetags.cms_component import cms_component
+
+        context = Context({"_cms_components": {"cms_component": []}})
+
+        # Valid identifier should work
</code_context>

<issue_to_address>
**issue (testing):** Add explicit tests for non-string component names as mentioned in the PR description.

This test only exercises invalid string identifiers, but the fix also covers non-string component names. Please add cases like `cms_component(context, 123)`, `cms_component(context, None)`, and a custom object, each asserting that a `ValueError` is raised with the expected "component name must be a string" message.
</issue_to_address>

### Comment 3
<location> `docs/source/tutorial/template_components.rst:14-15` </location>
<code_context>

 .. versionadded:: 2.1

-**Template components** are the easiest approach to creating or porting your own custom 
+**Template components** are the easiest approach to creating or porting your own custom
 frontend components, allowing you to define custom components **using django templates,
-without needing to write any Python code**. 
+without needing to write any Python code**.
</code_context>

<issue_to_address>
**suggestion (typo):** Consider capitalizing "Django" when referring to the framework.

Here, please capitalize “Django” to match the framework’s proper name and align with standard documentation style.

```suggestion
frontend components, allowing you to define custom components **using Django templates,
without needing to write any Python code**.
```
</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.

@fsbraun fsbraun merged commit 107b7cc into main Dec 15, 2025
35 checks passed
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.

2 participants