Skip to content

Commit

Permalink
[Backport] Fix Decimal trailing zero handling (#5968)
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Jun 2, 2023
1 parent 0813a03 commit a350460
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
1 change: 1 addition & 0 deletions changes/5968-hramezani.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix trailing zeros not ignored in Decimal validation.
8 changes: 6 additions & 2 deletions pydantic/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import re
import warnings
from datetime import date
from decimal import Decimal
from decimal import Decimal, InvalidOperation
from enum import Enum
from pathlib import Path
from types import new_class
Expand Down Expand Up @@ -691,7 +691,11 @@ def __get_validators__(cls) -> 'CallableGenerator':

@classmethod
def validate(cls, value: Decimal) -> Decimal:
digit_tuple, exponent = value.as_tuple()[1:]
try:
normalized_value = value.normalize()
except InvalidOperation:
normalized_value = value
digit_tuple, exponent = normalized_value.as_tuple()[1:]
if exponent in {'F', 'n', 'N'}:
raise errors.DecimalIsNotFiniteError()

Expand Down
19 changes: 16 additions & 3 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2075,6 +2075,19 @@ class Config:
(dict(max_digits=4, decimal_places=1), Decimal('999'), Decimal('999')),
(dict(max_digits=20, decimal_places=2), Decimal('742403889818000000'), Decimal('742403889818000000')),
(dict(max_digits=20, decimal_places=2), Decimal('7.42403889818E+17'), Decimal('7.42403889818E+17')),
(dict(max_digits=6, decimal_places=2), Decimal('000000000001111.700000'), Decimal('000000000001111.700000')),
(
dict(max_digits=6, decimal_places=2),
Decimal('0000000000011111.700000'),
[
{
'loc': ('foo',),
'type': 'value_error.decimal.whole_digits',
'msg': 'ensure that there are no more than 4 digits before the decimal point',
'ctx': {'whole_digits': 4},
}
],
),
(
dict(max_digits=20, decimal_places=2),
Decimal('7424742403889818000000'),
Expand Down Expand Up @@ -2102,14 +2115,14 @@ class Config:
),
(dict(max_digits=5, decimal_places=5), Decimal('70E-5'), Decimal('70E-5')),
(
dict(max_digits=5, decimal_places=5),
dict(max_digits=4, decimal_places=4),
Decimal('70E-6'),
[
{
'loc': ('foo',),
'msg': 'ensure that there are no more than 5 digits in total',
'msg': 'ensure that there are no more than 4 digits in total',
'type': 'value_error.decimal.max_digits',
'ctx': {'max_digits': 5},
'ctx': {'max_digits': 4},
}
],
),
Expand Down

0 comments on commit a350460

Please sign in to comment.