Skip to content

Commit

Permalink
(PC-29597)[API] fix: use column name for error key
Browse files Browse the repository at this point in the history
  • Loading branch information
R0ntheo committed Oct 21, 2024
1 parent 4cc5344 commit 0486699
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
14 changes: 8 additions & 6 deletions api/src/pcapi/validation/models/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def validate_generic(model: Model) -> ApiErrors:

column = columns[key]
value = getattr(model, key)

column_name = column.expression.name
if ( # pylint: disable=too-many-boolean-expressions
not getattr(column.expression, "nullable", False)
and not column.expression.foreign_keys
Expand All @@ -37,7 +37,7 @@ def validate_generic(model: Model) -> ApiErrors:
and getattr(column.expression, "server_default", ...) is None
and value is None
):
api_errors.add_error(key, "Cette information est obligatoire")
api_errors.add_error(column_name, "Cette information est obligatoire")

if value is None:
continue
Expand All @@ -47,20 +47,22 @@ def validate_generic(model: Model) -> ApiErrors:
and not isinstance(column.expression.type, sqlalchemy.Enum)
and not isinstance(value, str)
):
api_errors.add_error(key, "doit être une chaîne de caractères")
api_errors.add_error(column_name, "doit être une chaîne de caractères")

if (
isinstance(column.expression.type, (String, CHAR))
and isinstance(value, str)
and column.expression.type.length
and len(value) > column.expression.type.length
):
api_errors.add_error(key, f"Vous devez saisir moins de {str(column.expression.type.length)} caractères")
api_errors.add_error(
column_name, f"Vous devez saisir moins de {str(column.expression.type.length)} caractères"
)

if isinstance(column.expression.type, Integer) and not isinstance(value, int):
api_errors.add_error(key, "doit être un entier")
api_errors.add_error(column_name, "doit être un entier")

if isinstance(column.expression.type, Float) and not isinstance(value, float):
api_errors.add_error(key, "doit être un nombre")
api_errors.add_error(column_name, "doit être un nombre")

return api_errors
2 changes: 1 addition & 1 deletion api/tests/validation/models/generic_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def test_should_return_error_when_information_requires_a_string_type():
def test_should_return_error_when_information_requires_an_integer_type():
offer = offers_factories.OfferFactory.build(durationMinutes="not a number")
api_error = validate_generic(offer)
assert api_error.errors == {"_durationMinutes": ["doit être un entier"]}
assert api_error.errors == {"durationMinutes": ["doit être un entier"]}


def test_should_return_error_when_information_exceeds_column_size():
Expand Down

0 comments on commit 0486699

Please sign in to comment.