Skip to content

Conversation

@FanGoH
Copy link

@FanGoH FanGoH commented Nov 10, 2025

Ajustar la libreria para seguir las indicaciones en la guia de migracion de pydantic, esto permite suprimir un warning y preparar la compatibilidad para cuando se quiera utilizar pydantic v3

Se incluyen pruebas adicionales para verificar que los warnings ya no son emitidos

Summary by CodeRabbit

  • Tests
    • Added test coverage verifying no warnings are emitted when performing standard operations with valid data (bank configuration and CLABE validation).

@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

Walkthrough

This pull request addresses a Pydantic deprecation by relocating the strip_whitespace configuration from a Field parameter to json_schema_extra dict for the bank_name field in the BankConfigRequest class within clabe/validations.py. Two new test cases are added to tests/test_clabe.py and tests/test_types.py to verify that the changes do not emit warnings during validation. The functional behavior of whitespace stripping remains unchanged; only the metadata structure is reorganized.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • The primary change is a straightforward configuration relocation with no logic modifications
  • Two new tests follow identical patterns with minimal complexity
  • Limited file scope with consistent, repetitive changes across test files
  • No complex structural edits or multi-pattern logic changes

Areas requiring attention:

  • Verify that moving strip_whitespace to json_schema_extra maintains equivalent behavior in Pydantic validation
  • Confirm the warning capture tests use appropriate filter settings to catch Pydantic-related warnings

Possibly related issues

  • Issue #180: Directly addresses the reported Pydantic deprecation warning for the strip_whitespace parameter by moving it from Field argument to json_schema_extra for the same field in the same file.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Seguir la guia de Pydantic para suprimir una advertencia' accurately describes the main change: following Pydantic guidelines to suppress a warning by moving strip_whitespace configuration from Field parameter to json_schema_extra.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ccf338 and 6e361ae.

📒 Files selected for processing (3)
  • clabe/validations.py (1 hunks)
  • tests/test_clabe.py (2 hunks)
  • tests/test_types.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit configuration file

**/*.py: Enforce Relative Imports for Internal Modules

Ensure that any imports referencing internal modules use relative paths. However, if modules reside in the main module directories (for example /src or /library_or_app_name) —and relative imports are not feasible—absolute imports are acceptable. Additionally, if a module is located outside the main module structure (for example, in /tests or /scripts at a similar level), absolute imports are also valid.

Examples and Guidelines:

  1. If a module is in the same folder or a subfolder of the current file, use relative imports. For instance: from .some_module import SomeClass
  2. If the module is located under /src or /library_or_app_name and cannot be imported relatively, absolute imports are allowed (e.g., from library_or_app_name.utilities import helper_method).
  3. If a module is outside the main module directories (for example, in /tests, /scripts, or any similarly placed directory), absolute imports are valid.
  4. External (third-party) libraries should be imported absolutely (e.g., import requests).

**/*.py:
Rule: Enforce Snake Case in Python Backend

  1. New or Modified Code: Use snake_case for all variables, functions, methods, and class attributes.
  2. Exceptions (Pydantic models for API responses):
    • Primary fields must be snake_case.
    • If older clients expect camelCase, create a computed or alias field that references the snake_case field.
    • Mark any camelCase fields as deprecated or transitional.

Examples

Invalid:

class CardConfiguration(BaseModel):
    title: str
    subTitle: str  # ❌ Modified or new field in camelCase

Valid:

class CardConfiguration(BaseModel):
    title: str
    subtitle: str  # ✅ snake_case for new/modified field

    @computed_field
    def subTitle(self) -> str:  # camelCase allowed only for compatibility
        return self.subtitle

Any direct use of camelCase in new or updated code outside of these exceptions should be flagged.

`*...

Files:

  • tests/test_clabe.py
  • tests/test_types.py
  • clabe/validations.py
🧬 Code graph analysis (1)
tests/test_clabe.py (1)
clabe/validations.py (1)
  • add_bank (95-108)
🔇 Additional comments (1)
tests/test_types.py (1)

23-27: Review comment is based on incorrect assumptions about Pydantic behavior.

The json_schema_extra in the BankConfigRequest model is used only when generating JSON Schema and does not perform runtime validation. Runtime whitespace stripping in Pydantic requires the ConfigDict(str_strip_whitespace=True) model configuration option, which is not present in this codebase.

The test test_valid_clabe_shows_no_warnings correctly verifies that no warnings are emitted during CLABE validation and is unrelated to whitespace stripping. There is no actual whitespace stripping behavior being changed or tested here—the suggestion to add whitespace stripping tests is based on a misreading of the Pydantic Field configuration.

Likely an incorrect or invalid review comment.

Comment on lines 77 to 83
bank_name: str = Field(
min_length=1,
strip_whitespace=True,
description="Bank name must have at least 1 character.",
json_schema_extra={
"strip_whitespace": True,
}
)
Copy link

@coderabbitai coderabbitai bot Nov 10, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

CRITICAL: Whitespace stripping behavior is broken.

Moving strip_whitespace to json_schema_extra only adds metadata to the JSON schema—it does not preserve the runtime whitespace stripping behavior that existed in Pydantic v1. The field will no longer strip whitespace from bank names during validation.

For Pydantic v2, use StringConstraints to preserve the behavior:

-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, StringConstraints
+from typing import Annotated

 class BankConfigRequest(BaseModel):
     """
     Validates and processes bank configuration requests.

     The class handles validation of bank names and codes, ensuring:
     - Bank names are non-empty strings
     - Banxico codes are exactly 5 digits
     """

-    bank_name: str = Field(
+    bank_name: Annotated[str, StringConstraints(strip_whitespace=True)] = Field(
         min_length=1,
         description="Bank name must have at least 1 character.",
-        json_schema_extra={
-            "strip_whitespace": True,
-        }
     )

This follows the Pydantic v2 migration guide and maintains the actual whitespace stripping functionality. As per coding guidelines.

Verify the current behavior with whitespace:


🏁 Script executed:

#!/bin/bash
# Description: Test if whitespace stripping still works

python3 << 'EOF'
from clabe.validations import BankConfigRequest

# Test with leading/trailing whitespace
try:
    request = BankConfigRequest(
        bank_code_banxico="90716",
        bank_name="  Test Bank  "
    )
    print(f"bank_name value: '{request.bank_name}'")
    print(f"Whitespace stripped: {request.bank_name == 'Test Bank'}")
except Exception as e:
    print(f"Error: {e}")
EOF

Length of output: 59



CRITICAL: Whitespace stripping behavior is broken—verification confirms field retains spaces.

The test confirms that moving strip_whitespace to json_schema_extra does not preserve whitespace stripping. Input " Test Bank " remains unchanged instead of being stripped to "Test Bank". This violates the coding guideline requiring built-in Pydantic validators.

Fix at lines 77–83 using StringConstraints and Annotated:

from typing import Annotated
from pydantic import StringConstraints

bank_name: Annotated[str, StringConstraints(strip_whitespace=True)] = Field(
    min_length=1,
    description="Bank name must have at least 1 character.",
)

This is the correct Pydantic v2 approach and will restore runtime whitespace stripping.

🤖 Prompt for AI Agents
In clabe/validations.py around lines 77–83, the Field currently uses
json_schema_extra to set strip_whitespace which does not perform runtime
stripping; replace that with Pydantic v2 string constraints by switching the
annotation to use typing.Annotated with
pydantic.StringConstraints(strip_whitespace=True) and remove strip_whitespace
from json_schema_extra so the bank_name field becomes an Annotated[str,
StringConstraints(strip_whitespace=True)] with the existing Field(min_length=1,
description=...) to restore runtime whitespace stripping.

Copy link
Member

Choose a reason for hiding this comment

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

hola @FanGoH gracias por tu aporte! Observo algunos detalles, revisé la doc y en efecto esto suprime los warnings pero no corrige el issue principal que es hacer que el validator suprima espacios en blanco. Puedes revisar la sugerencia de @coderabbitai por favor?

Copy link

Choose a reason for hiding this comment

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

@felipao-mx Thank you for confirming! You're absolutely right - the current approach only suppresses the warning but loses the actual whitespace stripping behavior at runtime.

To summarize for @FanGoH:

  • Current PR: Moves strip_whitespace=True to json_schema_extra → ❌ Breaks functionality (only adds schema metadata)
  • Correct fix: Use Annotated[str, StringConstraints(strip_whitespace=True)] → ✅ Preserves both functionality and Pydantic v2 compatibility

The suggested approach follows the official Pydantic v2 migration guide and will:

  1. ✅ Suppress the deprecation warning
  2. ✅ Maintain the whitespace stripping behavior
  3. ✅ Prepare for Pydantic v3 compatibility

Happy to help verify the fix once implemented! 🚀

Comment on lines +59 to +63
def test_add_bank_no_show_warnings():
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter("always")
add_bank("90716", "Test bank")
assert len(caught_warnings) == 0, "Warnings were emitted during add_bank"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Add test coverage for whitespace stripping behavior.

While this test correctly verifies that no warnings are emitted, it doesn't validate the actual whitespace stripping behavior that was supposedly preserved from the Pydantic migration. Consider testing with whitespace in the bank name (e.g., add_bank("90716", " Test Bank ")) to ensure the behavior is maintained.

🤖 Prompt for AI Agents
In tests/test_clabe.py around lines 59 to 63, the test only asserts no warnings
but doesn't verify that add_bank strips surrounding whitespace from the bank
name; update the test to call add_bank("90716", "  Test Bank  ") (while still
using warnings.catch_warnings) and assert that the returned/recorded bank name
equals "Test Bank" (or lookup the stored bank entry and assert its name is
stripped), in addition to preserving the existing assertion that no warnings
were emitted.

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