Skip to content

Commit e596f43

Browse files
use warnings rather than logging a warning for DecimalField warnings (#9367)
1 parent 7f18ec1 commit e596f43

File tree

2 files changed

+17
-14
lines changed

2 files changed

+17
-14
lines changed

rest_framework/fields.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
import decimal
55
import functools
66
import inspect
7-
import logging
87
import re
98
import uuid
9+
import warnings
1010
from collections.abc import Mapping
1111
from enum import Enum
1212

@@ -44,8 +44,6 @@
4444
from rest_framework.utils.timezone import valid_datetime
4545
from rest_framework.validators import ProhibitSurrogateCharactersValidator
4646

47-
logger = logging.getLogger("rest_framework.fields")
48-
4947

5048
class empty:
5149
"""
@@ -989,9 +987,9 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
989987
self.min_value = min_value
990988

991989
if self.max_value is not None and not isinstance(self.max_value, decimal.Decimal):
992-
logger.warning("max_value in DecimalField should be Decimal type.")
990+
warnings.warn("max_value should be a Decimal instance.")
993991
if self.min_value is not None and not isinstance(self.min_value, decimal.Decimal):
994-
logger.warning("min_value in DecimalField should be Decimal type.")
992+
warnings.warn("min_value should be a Decimal instance.")
995993

996994
if self.max_digits is not None and self.decimal_places is not None:
997995
self.max_whole_digits = self.max_digits - self.decimal_places

tests/test_fields.py

+14-9
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import re
55
import sys
66
import uuid
7+
import warnings
78
from decimal import ROUND_DOWN, ROUND_UP, Decimal
89
from enum import auto
910
from unittest.mock import patch
@@ -1254,15 +1255,19 @@ class TestMinMaxDecimalField(FieldValues):
12541255
)
12551256

12561257
def test_warning_when_not_decimal_types(self, caplog):
1257-
import logging
1258-
serializers.DecimalField(
1259-
max_digits=3, decimal_places=1,
1260-
min_value=10, max_value=20
1261-
)
1262-
assert caplog.record_tuples == [
1263-
("rest_framework.fields", logging.WARNING, "max_value in DecimalField should be Decimal type."),
1264-
("rest_framework.fields", logging.WARNING, "min_value in DecimalField should be Decimal type.")
1265-
]
1258+
with warnings.catch_warnings(record=True) as w:
1259+
warnings.simplefilter('always')
1260+
1261+
serializers.DecimalField(
1262+
max_digits=3, decimal_places=1,
1263+
min_value=10, max_value=20
1264+
)
1265+
1266+
assert len(w) == 2
1267+
assert all(issubclass(i.category, UserWarning) for i in w)
1268+
1269+
assert 'max_value should be a Decimal instance' in str(w[0].message)
1270+
assert 'min_value should be a Decimal instance' in str(w[1].message)
12661271

12671272

12681273
class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues):

0 commit comments

Comments
 (0)