-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
test_python.py
614 lines (474 loc) · 22.1 KB
/
test_python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
import decimal
import sys
import unittest
import warnings
from typing import Iterable, Optional, Union
from unittest.mock import patch
import pytest
from faker import Faker
@pytest.mark.parametrize("object_type", (None, bool, str, float, int, tuple, set, list, Iterable, dict))
def test_pyobject(
object_type: Optional[Union[bool, str, float, int, tuple, set, list, Iterable, dict]],
):
random_object = Faker().pyobject(object_type=object_type)
if object_type is None:
assert random_object is None
else:
assert isinstance(random_object, object_type)
@pytest.mark.parametrize("object_type", (object, type, callable))
def test_pyobject_with_unknown_object_type(object_type):
with pytest.raises(ValueError, match=f"Object type `{object_type}` is not supported by `pyobject` function"):
assert Faker().pyobject(object_type=object_type)
@pytest.mark.parametrize(
"mock_random_number_source, right_digits, expected_decimal_part",
(
("1234567", 5, "12345"),
("1234567", 0, "1"), # This is kinda interesting - same as 1 digit
("1234567", 1, "1"),
("1234567", 2, "12"),
("0123", 1, "1"),
),
)
def test_pyfloat_right_and_left_digits_positive(mock_random_number_source, right_digits, expected_decimal_part):
# Remove the randomness from the test by mocking the `BaseProvider.random_number` value
def mock_random_number(self, digits=None, fix_len=False):
return int(mock_random_number_source[: digits or 1])
with patch("faker.providers.BaseProvider.random_number", mock_random_number):
result = Faker().pyfloat(left_digits=1, right_digits=right_digits, positive=True)
decimal_part = str(result).split(".")[1]
assert decimal_part == expected_decimal_part
def test_pyfloat_right_or_left_digit_overflow():
max_float_digits = sys.float_info.dig
faker = Faker()
# Make random_int always return the maximum value input - makes it easy to reason about the code below
def mock_random_int(self, min=0, max=9999, step=1):
return max
# Remove the randomness from the test by mocking the `BaseProvider.random_number` value
def mock_random_number(self, digits=None, fix_len=False):
return int("12345678901234567890"[: digits or 1])
with patch("faker.providers.BaseProvider.random_int", mock_random_int):
with patch("faker.providers.BaseProvider.random_number", mock_random_number):
# A bit too much, but ~half on either side
with pytest.raises(ValueError, match="Asking for too many digits"):
faker.pyfloat(
left_digits=max_float_digits // 2 + 1,
right_digits=max_float_digits // 2 + 1,
)
# Asking for max digits on either side also fails, because we need one digit on the other side, i.e.
# 0.123123123, or 123123123.0 (at least needs to lead with `0.` or trail with `.0`).
with pytest.raises(ValueError, match="Asking for too many digits"):
faker.pyfloat(left_digits=max_float_digits)
with pytest.raises(ValueError, match="Asking for too many digits"):
faker.pyfloat(right_digits=max_float_digits)
# Just the right amount of max digits on either side
result = faker.pyfloat(left_digits=max_float_digits - 1)
assert str(abs(result)) == "12345678901234.1"
result = faker.pyfloat(right_digits=max_float_digits - 1)
assert str(abs(result)) == "1.12345678901234"
class TestPyint(unittest.TestCase):
def setUp(self):
self.fake = Faker()
Faker.seed(0)
def test_pyint(self):
self.assertIsInstance(self.fake.pyint(), int)
def test_pyint_bounds(self):
self.assertTrue(0 <= self.fake.pyint() <= 9999)
def test_pyint_step(self):
random_int = self.fake.pyint(step=2)
self.assertEqual(0, random_int % 2)
def test_pyint_bound_0(self):
self.assertEqual(0, self.fake.pyint(min_value=0, max_value=0))
def test_pyint_bound_positive(self):
self.assertEqual(5, self.fake.pyint(min_value=5, max_value=5))
def test_pyint_bound_negative(self):
self.assertEqual(-5, self.fake.pyint(min_value=-5, max_value=-5))
def test_pyint_range(self):
self.assertTrue(0 <= self.fake.pyint(min_value=0, max_value=2) <= 2)
class TestPyfloat(unittest.TestCase):
def setUp(self):
self.fake = Faker()
Faker.seed(0)
def test_pyfloat(self):
result = self.fake.pyfloat()
self.assertIsInstance(result, float)
def test_left_digits(self):
expected_left_digits = 10
result = self.fake.pyfloat(left_digits=expected_left_digits)
left_digits = len(str(abs(int(result))))
self.assertGreaterEqual(expected_left_digits, left_digits)
def test_right_digits(self):
expected_right_digits = 10
result = self.fake.pyfloat(right_digits=expected_right_digits)
right_digits = len(("%r" % result).split(".")[1])
self.assertGreaterEqual(expected_right_digits, right_digits)
def test_positive(self):
result = self.fake.pyfloat(positive=True)
self.assertGreater(result, 0)
self.assertEqual(result, abs(result))
def test_min_value(self):
min_values = (0, 10, -1000, 1000, 999999)
for min_value in min_values:
result = self.fake.pyfloat(min_value=min_value)
self.assertGreaterEqual(result, min_value)
def test_min_value_and_left_digits(self):
"""
Combining the min_value and left_digits keyword arguments produces
numbers that obey both of those constraints.
"""
result = self.fake.pyfloat(left_digits=1, min_value=0)
self.assertLess(result, 10)
self.assertGreaterEqual(result, 0)
def test_max_value(self):
max_values = (0, 10, -1000, 1000, 999999)
for max_value in max_values:
result = self.fake.pyfloat(max_value=max_value)
self.assertLessEqual(result, max_value)
def test_max_value_zero_and_left_digits(self):
"""
Combining the max_value and left_digits keyword arguments produces
numbers that obey both of those constraints.
"""
result = self.fake.pyfloat(left_digits=2, max_value=0)
self.assertLessEqual(result, 0)
self.assertGreater(result, -100)
def test_max_value_should_be_greater_than_min_value(self):
"""
An exception should be raised if min_value is greater than max_value
"""
expected_message = "Min value cannot be greater than max value"
with self.assertRaises(ValueError) as raises:
self.fake.pyfloat(min_value=100, max_value=0)
message = str(raises.exception)
self.assertEqual(message, expected_message)
def test_max_value_and_positive(self):
"""
Combining the max_value and positive keyword arguments produces
numbers that obey both of those constraints.
"""
result = self.fake.pyfloat(positive=True, max_value=100)
self.assertLessEqual(result, 100)
self.assertGreater(result, 0)
def test_max_and_min_value_positive_with_decimals(self):
"""
Combining the max_value and min_value keyword arguments with
positive values for each produces numbers that obey both of
those constraints.
"""
for _ in range(1000):
result = self.fake.pyfloat(min_value=100.123, max_value=200.321)
self.assertLessEqual(result, 200.321)
self.assertGreaterEqual(result, 100.123)
def test_max_and_min_value_negative(self):
"""
Combining the max_value and min_value keyword arguments with
negative values for each produces numbers that obey both of
those constraints.
"""
result = self.fake.pyfloat(max_value=-100, min_value=-200)
self.assertLessEqual(result, -100)
self.assertGreaterEqual(result, -200)
def test_max_and_min_value_negative_with_decimals(self):
"""
Combining the max_value and min_value keyword arguments with
negative values for each produces numbers that obey both of
those constraints.
"""
for _ in range(1000):
result = self.fake.pyfloat(max_value=-100.123, min_value=-200.321)
self.assertLessEqual(result, -100.123)
self.assertGreaterEqual(result, -200.321)
def test_positive_and_min_value_incompatible(self):
"""
An exception should be raised if positive=True is set, but
a negative min_value is provided.
"""
expected_message = "Cannot combine positive=True with negative or zero min_value"
with self.assertRaises(ValueError) as raises:
self.fake.pyfloat(min_value=-100, positive=True)
message = str(raises.exception)
self.assertEqual(message, expected_message)
def test_positive_doesnt_return_zero(self):
"""
Choose the right_digits and max_value so it's guaranteed to return zero,
then watch as it doesn't because positive=True
"""
result = self.fake.pyfloat(positive=True, right_digits=0, max_value=1)
self.assertGreater(result, 0)
@pytest.mark.skipif(sys.version_info < (3, 10), reason="Only relevant for Python 3.10 and later.")
@pytest.mark.filterwarnings(
# Convert the warning to an error for this test
r"error:non-integer arguments to randrange\(\):DeprecationWarning"
)
def test_float_min_and_max_value_does_not_warn(self):
"""
Float arguments to randrange are deprecated from Python 3.10. This is a regression
test to check that `pyfloat` does not cause a deprecation warning.
"""
self.fake.pyfloat(min_value=-1.0, max_value=1.0)
def test_float_min_and_max_value_with_same_whole(self):
self.fake.pyfloat(min_value=2.3, max_value=2.5)
class TestPydecimal(unittest.TestCase):
def setUp(self):
self.fake = Faker()
Faker.seed(0)
def test_pydecimal(self):
result = self.fake.pydecimal()
self.assertIsInstance(result, decimal.Decimal)
def test_left_digits(self):
expected_left_digits = 10
result = self.fake.pydecimal(left_digits=expected_left_digits)
left_digits = len(str(abs(int(result))))
self.assertGreaterEqual(expected_left_digits, left_digits)
def test_left_digits_can_be_zero(self):
expected_left_digits = 0
result = self.fake.pydecimal(left_digits=expected_left_digits)
left_digits = int(result)
self.assertEqual(expected_left_digits, left_digits)
def test_right_digits(self):
expected_right_digits = 10
result = self.fake.pydecimal(right_digits=expected_right_digits)
right_digits = len(str(result).split(".")[1])
self.assertGreaterEqual(expected_right_digits, right_digits)
def test_positive(self):
result = self.fake.pydecimal(positive=True)
self.assertGreater(result, 0)
abs_result = -result if result < 0 else result # abs() result returns scientific notation
self.assertEqual(result, abs_result)
def test_min_value(self):
min_values = (0, 10, -1000, 1000, 999999)
for min_value in min_values:
result = self.fake.pydecimal(min_value=min_value)
self.assertGreaterEqual(result, min_value)
def test_min_value_always_returns_a_decimal(self):
min_values = (0, 10, -1000, 1000, 999999)
for min_value in min_values:
result = self.fake.pydecimal(min_value=min_value)
self.assertIsInstance(result, decimal.Decimal)
def test_min_value_and_left_digits(self):
"""
Combining the min_value and left_digits keyword arguments produces
numbers that obey both of those constraints.
"""
result = self.fake.pydecimal(left_digits=1, min_value=0)
self.assertLess(result, 10)
self.assertGreaterEqual(result, 0)
def test_max_value(self):
max_values = (0, 10, -1000, 1000, 999999)
for max_value in max_values:
result = self.fake.pydecimal(max_value=max_value)
self.assertLessEqual(result, max_value)
def test_max_value_always_returns_a_decimal(self):
max_values = (0, 10, -1000, 1000, 999999)
for max_value in max_values:
result = self.fake.pydecimal(max_value=max_value)
self.assertIsInstance(result, decimal.Decimal)
def test_max_value_zero_and_left_digits(self):
"""
Combining the max_value and left_digits keyword arguments produces
numbers that obey both of those constraints.
"""
result = self.fake.pydecimal(left_digits=2, max_value=0)
self.assertLessEqual(result, 0)
self.assertGreater(result, -100)
def test_max_value_should_be_greater_than_min_value(self):
"""
An exception should be raised if min_value is greater than max_value
"""
expected_message = "Min value cannot be greater than max value"
with self.assertRaises(ValueError) as raises:
self.fake.pydecimal(min_value=100, max_value=0)
message = str(raises.exception)
self.assertEqual(message, expected_message)
def test_max_value_and_positive(self):
"""
Combining the max_value and positive keyword arguments produces
numbers that obey both of those constraints.
"""
result = self.fake.pydecimal(positive=True, max_value=100)
self.assertLessEqual(result, 100)
self.assertGreater(result, 0)
def test_max_and_min_value_negative(self):
"""
Combining the max_value and min_value keyword arguments with
negative values for each produces numbers that obey both of
those constraints.
"""
result = self.fake.pydecimal(max_value=-100, min_value=-200)
self.assertLessEqual(result, -100)
self.assertGreaterEqual(result, -200)
def test_positive_and_min_value_incompatible(self):
"""
An exception should be raised if positive=True is set, but
a negative min_value is provided.
"""
expected_message = "Cannot combine positive=True with negative or zero min_value"
with self.assertRaises(ValueError) as raises:
self.fake.pydecimal(min_value=-100, positive=True)
message = str(raises.exception)
self.assertEqual(message, expected_message)
def test_positive_doesnt_return_zero(self):
"""
Choose the right_digits and max_value so it's guaranteed to return zero,
then watch as it doesn't because positive=True
"""
result = self.fake.pydecimal(positive=True, right_digits=0, max_value=1)
self.assertGreater(result, 0)
def test_min_value_zero_doesnt_return_negative(self):
Faker.seed("1")
result = self.fake.pydecimal(left_digits=3, right_digits=2, min_value=0, max_value=999)
self.assertGreater(result, 0)
def test_min_value_one_hundred_doesnt_return_negative(self):
Faker.seed("1")
result = self.fake.pydecimal(left_digits=3, right_digits=2, min_value=100, max_value=999)
self.assertGreater(result, 100)
def test_min_value_minus_one_doesnt_return_positive(self):
Faker.seed("5")
result = self.fake.pydecimal(left_digits=3, right_digits=2, min_value=-999, max_value=0)
self.assertLess(result, 0)
def test_min_value_minus_one_hundred_doesnt_return_positive(self):
Faker.seed("5")
result = self.fake.pydecimal(left_digits=3, right_digits=2, min_value=-999, max_value=-100)
self.assertLess(result, -100)
def test_min_value_10_pow_1000_return_greater_number(self):
Faker.seed("2")
result = self.fake.pydecimal(min_value=10**1000)
self.assertGreater(result, 10**1000)
class TestPystr(unittest.TestCase):
def setUp(self):
self.fake = Faker(includes=["tests.mymodule.en_US"])
Faker.seed(0)
def test_no_parameters(self):
some_string = self.fake.pystr()
assert isinstance(some_string, str)
assert len(some_string) <= 20
def test_lower_length_limit(self):
some_string = self.fake.pystr(min_chars=3)
assert isinstance(some_string, str)
assert len(some_string) >= 3
assert len(some_string) <= 20
def test_upper_length_limit(self):
some_string = self.fake.pystr(max_chars=5)
assert isinstance(some_string, str)
assert len(some_string) <= 5
def test_invalid_length_limits(self):
with self.assertRaises(AssertionError):
self.fake.pystr(min_chars=6, max_chars=5)
def test_exact_length(self):
some_string = self.fake.pystr(min_chars=5, max_chars=5)
assert isinstance(some_string, str)
assert len(some_string) == 5
def test_prefix(self):
some_string = self.fake.pystr(prefix="START_")
assert isinstance(some_string, str)
assert some_string.startswith("START_")
assert len(some_string) == 26
def test_suffix(self):
some_string = self.fake.pystr(suffix="_END")
assert isinstance(some_string, str)
assert some_string.endswith("_END")
assert len(some_string) == 24
def test_prefix_and_suffix(self):
some_string = self.fake.pystr(min_chars=9, max_chars=20, prefix="START_", suffix="_END")
assert isinstance(some_string, str)
assert some_string.startswith("START_")
assert some_string.endswith("_END")
assert len(some_string) >= 19
class TestPystrFormat(unittest.TestCase):
def setUp(self):
self.fake = Faker(includes=["tests.mymodule.en_US"])
Faker.seed(0)
def test_formatter_invocation(self):
with patch.object(self.fake["en_US"], "foo") as mock_foo:
with patch("faker.providers.BaseProvider.bothify", wraps=self.fake.bothify) as mock_bothify:
mock_foo.return_value = "barbar"
value = self.fake.pystr_format("{{foo}}?#?{{foo}}?#?{{foo}}", letters="abcde")
assert value.count("barbar") == 3
assert mock_foo.call_count == 3
mock_bothify.assert_called_once_with("barbar?#?barbar?#?barbar", letters="abcde")
class TestPython(unittest.TestCase):
"""Tests python generators"""
def setUp(self):
self.factory = Faker()
def test_pybool_return_type(self):
some_bool = self.factory.pybool()
assert isinstance(some_bool, bool)
def __test_pybool_truth_probability(
self,
truth_probability: int,
deviation_threshold: int = 5,
iterations: int = 999,
):
truth_count_expected = iterations * truth_probability / 100
truth_count_actual = 0
for iteration in range(iterations):
boolean = self.factory.pybool(truth_probability=truth_probability)
assert isinstance(boolean, bool)
if boolean is True:
truth_count_actual += 1
deviation_absolute = abs(truth_count_expected - truth_count_actual)
deviation_percentage = deviation_absolute / iterations * 100
# Increase `deviation_threshold` value in case this assertion becomes flaky.
assert deviation_percentage <= deviation_threshold
def test_pybool_truth_probability_zero(self):
self.__test_pybool_truth_probability(0, deviation_threshold=0)
def test_pybool_truth_probability_twenty_five(self):
self.__test_pybool_truth_probability(25)
def test_pybool_truth_probability_fifty(self):
self.__test_pybool_truth_probability(50)
def test_pybool_truth_probability_seventy_five(self):
self.__test_pybool_truth_probability(75)
def test_pybool_truth_probability_hundred(self):
self.__test_pybool_truth_probability(100, deviation_threshold=0)
def __test_pybool_invalid_truth_probability(self, truth_probability: int):
with pytest.raises(ValueError) as exception:
self.factory.pybool(truth_probability=truth_probability)
message_expected = "Invalid `truth_probability` value: must be between `0` and `100` inclusive"
message_actual = str(exception.value)
assert message_expected == message_actual
def test_pybool_truth_probability_less_than_zero(self):
self.__test_pybool_invalid_truth_probability(-1)
def test_pybool_truth_probability_more_than_hundred(self):
self.__test_pybool_invalid_truth_probability(101)
def test_pytuple(self):
with warnings.catch_warnings(record=True) as w:
some_tuple = Faker().pytuple()
assert len(w) == 0
assert some_tuple
assert isinstance(some_tuple, tuple)
def test_pytuple_size(self):
def mock_pyint(self, *args, **kwargs):
return 1
with patch("faker.providers.python.Provider.pyint", mock_pyint):
some_tuple = Faker().pytuple(nb_elements=3, variable_nb_elements=False, value_types=[int])
assert some_tuple == (1, 1, 1)
def test_pylist(self):
with warnings.catch_warnings(record=True) as w:
some_list = self.factory.pylist()
assert len(w) == 0
assert some_list
assert isinstance(some_list, list)
def test_pylist_types(self):
with warnings.catch_warnings(record=True) as w:
some_list = self.factory.pylist(10, True, [int])
assert len(w) == 0
assert some_list
for item in some_list:
assert isinstance(item, int)
with warnings.catch_warnings(record=True) as w:
some_list = self.factory.pylist(10, True, value_types=[int])
assert len(w) == 0
assert some_list
for item in some_list:
assert isinstance(item, int)
with warnings.catch_warnings(record=True) as w:
some_list = self.factory.pylist(10, True, int)
assert len(w) == 1
assert some_list
for item in some_list:
assert isinstance(item, int)
with warnings.catch_warnings(record=True) as w:
some_list = self.factory.pylist(10, True, int, float)
assert len(w) == 2
assert some_list
for item in some_list:
assert isinstance(item, (int, float))