Debian Codegraph @

tests/test_settings.py

raw
1 from datetime import datetime, tzinfo
2
3 import pytest
4 from parameterized import param, parameterized
5
6 from dateparser import DateDataParser, parse
7 from dateparser.conf import SettingValidationError, apply_settings, settings
8 from tests import BaseTestCase
9
10
11 def test_function(settings=None):
12 return settings
13
14
15 class TimeZoneSettingsTest(BaseTestCase):
16 def setUp(self):
17 super().setUp()
18 self.given_ds = NotImplemented
19 self.result = NotImplemented
20 self.timezone = NotImplemented
21 self.confs = NotImplemented
22
23 @parameterized.expand(
24 [
25 param(
26 "12 Feb 2015 10:30 PM +0100",
27 datetime(2015, 2, 12, 22, 30),
28 r"UTC\+01:00",
29 ),
30 param("12 Feb 2015 4:30 PM EST", datetime(2015, 2, 12, 16, 30), "EST"),
31 param("12 Feb 2015 8:30 PM PKT", datetime(2015, 2, 12, 20, 30), "PKT"),
32 param("12 Feb 2015 8:30 PM ACT", datetime(2015, 2, 12, 20, 30), "ACT"),
33 ]
34 )
35 def test_should_return_and_assert_tz(self, ds, dt, tz):
36 self.given(ds)
37 self.given_configurations({})
38 self.when_date_is_parsed()
39 self.then_date_is_tz_aware()
40 self.then_date_is(dt)
41 self.then_timezone_is(tz)
42
43 @parameterized.expand(
44 [
45 param("12 Feb 2015 4:30 PM EST", datetime(2015, 2, 12, 16, 30), "EST"),
46 param("12 Feb 2015 8:30 PM PKT", datetime(2015, 2, 12, 20, 30), "PKT"),
47 param("12 Feb 2015 8:30 PM ACT", datetime(2015, 2, 12, 20, 30), "ACT"),
48 param("12 Feb 2015 8:30 PM", datetime(2015, 2, 12, 20, 30), ""),
49 ]
50 )
51 def test_only_return_explicit_timezone(self, ds, dt, tz):
52 self.given(ds)
53 self.given_configurations({})
54 self.when_date_is_parsed()
55 self.then_date_is(dt)
56 if tz:
57 self.then_date_is_tz_aware()
58 self.then_timezone_is(tz)
59 else:
60 self.then_date_is_not_tz_aware()
61
62 @parameterized.expand(
63 [
64 param(
65 "12 Feb 2015 4:30 PM EST",
66 datetime(2015, 2, 12, 16, 30),
67 ),
68 param(
69 "12 Feb 2015 8:30 PM PKT",
70 datetime(2015, 2, 12, 20, 30),
71 ),
72 param(
73 "12 Feb 2015 8:30 PM ACT",
74 datetime(2015, 2, 12, 20, 30),
75 ),
76 param(
77 "12 Feb 2015 8:30 PM +0100",
78 datetime(2015, 2, 12, 20, 30),
79 ),
80 ]
81 )
82 def test_should_return_naive_if_RETURN_AS_TIMEZONE_AWARE_IS_FALSE(self, ds, dt):
83 self.given(ds)
84 self.given_configurations({"RETURN_AS_TIMEZONE_AWARE": False})
85 self.when_date_is_parsed()
86 self.then_date_is(dt)
87 self.then_date_is_not_tz_aware()
88
89 def then_timezone_is(self, tzname):
90 self.assertEqual(self.result.tzinfo.tzname(""), tzname)
91
92 def given(self, ds):
93 self.given_ds = ds
94
95 def given_configurations(self, confs):
96 if "TIMEZONE" not in confs:
97 confs.update({"TIMEZONE": "local"})
98
99 self.confs = settings.replace(**confs)
100
101 def when_date_is_parsed(self):
102 self.result = parse(self.given_ds, settings=(self.confs or {}))
103
104 def then_date_is_tz_aware(self):
105 self.assertIsInstance(self.result.tzinfo, tzinfo)
106
107 def then_date_is_not_tz_aware(self):
108 self.assertIsNone(self.result.tzinfo)
109
110 def then_date_is(self, date):
111 dtc = self.result.replace(tzinfo=None)
112 self.assertEqual(dtc, date)
113
114
115 class SettingsTest(BaseTestCase):
116 def setUp(self):
117 super().setUp()
118 self.default_settings = settings
119
120 def test_apply_settings_should_return_default_settings_when_no_settings_are_supplied_to_the_decorated_function(
121 self,
122 ):
123 test_func = apply_settings(test_function)
124 self.assertEqual(test_func(), self.default_settings)
125
126 def test_apply_settings_should_return_non_default_settings_when_settings_are_supplied_to_the_decorated_function(
127 self,
128 ):
129 test_func = apply_settings(test_function)
130 self.assertNotEqual(
131 test_func(settings={"PREFER_DATES_FROM": "past"}), self.default_settings
132 )
133
134 def test_apply_settings_shouldnt_create_new_settings_when_same_settings_are_supplied_to_the_decorated_function_more_than_once( # noqa E501
135 self,
136 ):
137 test_func = apply_settings(test_function)
138 settings_once = test_func(settings={"PREFER_DATES_FROM": "past"})
139 settings_twice = test_func(settings={"PREFER_DATES_FROM": "past"})
140 self.assertEqual(settings_once, settings_twice)
141
142 def test_apply_settings_should_return_default_settings_when_called_with_no_settings_after_once_called_with_settings_supplied_to_the_decorated_function( # noqa E501
143 self,
144 ):
145 test_func = apply_settings(test_function)
146 settings_once = test_func(settings={"PREFER_DATES_FROM": "past"})
147 settings_twice = test_func()
148 self.assertNotEqual(settings_once, self.default_settings)
149 self.assertEqual(settings_twice, self.default_settings)
150
151
152 class InvalidSettingsTest(BaseTestCase):
153 def setUp(self):
154 super().setUp()
155
156 def test_error_is_raised_when_none_is_passed_in_settings(self):
157 test_func = apply_settings(test_function)
158 with self.assertRaisesRegex(TypeError, r"Invalid.*None\}"):
159 test_func(settings={"PREFER_DATES_FROM": None})
160
161 with self.assertRaisesRegex(TypeError, r"Invalid.*None\}"):
162 test_func(settings={"TIMEZONE": None})
163
164 with self.assertRaisesRegex(TypeError, r"Invalid.*None\}"):
165 test_func(settings={"TO_TIMEZONE": None})
166
167 def test_error_is_raised_for_invalid_type_settings(self):
168 test_func = apply_settings(test_function)
169 try:
170 test_func(settings=["current_period", False, "current"])
171 except Exception as error:
172 self.error = error
173 self.then_error_was_raised(
174 TypeError,
175 ["settings can only be either dict or instance of Settings class"],
176 )
177
178 def test_check_settings_wrong_setting_name(self):
179 with self.assertRaisesRegex(
180 SettingValidationError, r".* is not a valid setting"
181 ):
182 DateDataParser(settings={"AAAAA": "foo"})
183
184 @parameterized.expand(
185 [
186 param("DATE_ORDER", 2, "YYY", "MDY"),
187 param(
188 "TIMEZONE", False, "", "Europe/Madrid"
189 ), # should we check valid timezones?
190 param(
191 "TO_TIMEZONE", True, "", "Europe/Madrid"
192 ), # should we check valid timezones?
193 param("RETURN_AS_TIMEZONE_AWARE", "false", "", True),
194 param("PREFER_DAY_OF_MONTH", False, "current_period", "current"),
195 param("PREFER_DATES_FROM", True, "current", "current_period"),
196 param("RELATIVE_BASE", "yesterday", "", datetime.now()),
197 param("SKIP_TOKENS", "foo", "", ["foo"]),
198 param("REQUIRE_PARTS", "day", "", ["month", "day"]),
199 param("PARSERS", "absolute-time", "", ["absolute-time", "no-spaces-time"]),
200 param("STRICT_PARSING", "true", "", True),
201 param("RETURN_TIME_AS_PERIOD", "false", "", True),
202 param("PREFER_LOCALE_DATE_ORDER", "true", "", False),
203 param("NORMALIZE", "true", "", True),
204 param("FUZZY", "true", "", False),
205 param("PREFER_LOCALE_DATE_ORDER", "false", "", True),
206 param("DEFAULT_LANGUAGES", "en", "", ["en"]),
207 param("LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD", "1", "", 0.5),
208 ]
209 )
210 def test_check_settings(self, setting, wrong_type, wrong_value, valid_value):
211 with self.assertRaisesRegex(
212 SettingValidationError,
213 r'"{}" must be .*, not "{}".'.format(setting, type(wrong_type).__name__),
214 ):
215 DateDataParser(settings={setting: wrong_type})
216
217 if wrong_value:
218 with self.assertRaisesRegex(
219 SettingValidationError,
220 r'"{}" is not a valid value for "{}", it should be: .*'.format(
221 str(wrong_value).replace("[", "\\[").replace("]", "\\]"), setting
222 ),
223 ):
224 DateDataParser(settings={setting: wrong_value})
225
226 # check that a valid value doesn't raise an error
227 assert DateDataParser(settings={setting: valid_value})
228
229 def test_check_settings_extra_check_require_parts(self):
230 with self.assertRaisesRegex(
231 SettingValidationError,
232 r'"REQUIRE_PARTS" setting contains invalid values: time',
233 ):
234 DateDataParser(settings={"REQUIRE_PARTS": ["time", "day"]})
235 with self.assertRaisesRegex(
236 SettingValidationError,
237 r'There are repeated values in the "REQUIRE_PARTS" setting',
238 ):
239 DateDataParser(settings={"REQUIRE_PARTS": ["month", "day", "month"]})
240
241 def test_check_settings_extra_check_parsers(self):
242 with self.assertRaisesRegex(
243 SettingValidationError,
244 r'Found unknown parsers in the "PARSERS" setting: no-spaces',
245 ):
246 DateDataParser(settings={"PARSERS": ["absolute-time", "no-spaces"]})
247
248 with self.assertRaisesRegex(
249 SettingValidationError,
250 r'There are repeated values in the "PARSERS" setting',
251 ):
252 DateDataParser(
253 settings={"PARSERS": ["absolute-time", "timestamp", "absolute-time"]}
254 )
255
256 def test_check_settings_extra_check_confidence_threshold(self):
257 with self.assertRaisesRegex(
258 SettingValidationError,
259 r"1.1 is not a valid value for "
260 r"LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD. It can take values "
261 r"between 0 and 1",
262 ):
263 DateDataParser(settings={"LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD": 1.1})
264
265 def test_check_settings_extra_check_default_languages(self):
266 with self.assertRaisesRegex(
267 SettingValidationError,
268 "Found invalid languages in the 'DEFAULT_LANGUAGES' setting: 'abcd'",
269 ):
270 DateDataParser(settings={"DEFAULT_LANGUAGES": ["abcd"]})
271
272
273 @pytest.mark.parametrize(
274 "date_string,expected_result",
275 [
276 # Note that these results are "valid" but probably they shouldn't be considered
277 ("2020", datetime(1900, 1, 1, 20, 2)),
278 ("333", datetime(1900, 1, 1, 3, 3, 3)),
279 ("1000", datetime(1900, 1, 1, 10, 0)),
280 ("100000", datetime(1900, 1, 1, 10, 0)),
281 ],
282 )
283 def test_no_spaces_strict_parsing(date_string, expected_result):
284 parser = DateDataParser(
285 settings={"PARSERS": ["no-spaces-time"], "STRICT_PARSING": False}
286 )
287 assert parser.get_date_data(date_string)["date_obj"] == expected_result
288
289 parser = DateDataParser(
290 settings={"PARSERS": ["no-spaces-time"], "STRICT_PARSING": True}
291 )
292 assert parser.get_date_data(date_string)["date_obj"] is None
293
294
295 def detect_languages(text, confidence_threshold):
296 if confidence_threshold > 0.5:
297 return ["en"]
298 else:
299 return ["fr"]
300
301
302 def test_confidence_threshold_setting_is_applied():
303 ddp = DateDataParser(
304 detect_languages_function=detect_languages,
305 settings={"LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD": 0.6},
306 )
307 assert ddp.get_date_data("21/06/2020").locale == "en"
308
309 ddp2 = DateDataParser(
310 detect_languages_function=detect_languages,
311 settings={"LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD": 0.4},
312 )
313 assert ddp2.get_date_data("21/06/2020").locale == "fr"