summaryrefslogtreecommitdiff
path: root/tests/test_fuzzy.py
blob: 1caeb0a28b5aa70d2b4f85a0450b2d1556918768 (plain)
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
# -*- coding: utf-8 -*-
# Copyright (c) 2010 Mark Sandstrom
# Copyright (c) 2011-2013 Raphaël Barrois
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import datetime
import decimal

from factory import compat
from factory import fuzzy

from .compat import mock, unittest
from . import utils


class FuzzyAttributeTestCase(unittest.TestCase):
    def test_simple_call(self):
        d = fuzzy.FuzzyAttribute(lambda: 10)

        res = d.evaluate(2, None, False)
        self.assertEqual(10, res)

        res = d.evaluate(2, None, False)
        self.assertEqual(10, res)


class FuzzyChoiceTestCase(unittest.TestCase):
    def test_unbiased(self):
        options = [1, 2, 3]
        d = fuzzy.FuzzyChoice(options)
        res = d.evaluate(2, None, False)
        self.assertIn(res, options)

    def test_mock(self):
        options = [1, 2, 3]
        fake_choice = lambda d: sum(d)

        d = fuzzy.FuzzyChoice(options)

        with mock.patch('random.choice', fake_choice):
            res = d.evaluate(2, None, False)

        self.assertEqual(6, res)

    def test_generator(self):
        def options():
            for i in range(3):
                yield i

        d = fuzzy.FuzzyChoice(options())

        res = d.evaluate(2, None, False)
        self.assertIn(res, [0, 1, 2])

        # And repeat
        res = d.evaluate(2, None, False)
        self.assertIn(res, [0, 1, 2])


class FuzzyIntegerTestCase(unittest.TestCase):
    def test_definition(self):
        """Tests all ways of defining a FuzzyInteger."""
        fuzz = fuzzy.FuzzyInteger(2, 3)
        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertIn(res, [2, 3])

        fuzz = fuzzy.FuzzyInteger(4)
        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertIn(res, [0, 1, 2, 3, 4])

    def test_biased(self):
        fake_randrange = lambda low, high, step: (low + high) * step

        fuzz = fuzzy.FuzzyInteger(2, 8)

        with mock.patch('random.randrange', fake_randrange):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual((2 + 8 + 1) * 1, res)

    def test_biased_high_only(self):
        fake_randrange = lambda low, high, step: (low + high) * step

        fuzz = fuzzy.FuzzyInteger(8)

        with mock.patch('random.randrange', fake_randrange):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual((0 + 8 + 1) * 1, res)

    def test_biased_with_step(self):
        fake_randrange = lambda low, high, step: (low + high) * step

        fuzz = fuzzy.FuzzyInteger(5, 8, 3)

        with mock.patch('random.randrange', fake_randrange):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual((5 + 8 + 1) * 3, res)


class FuzzyDecimalTestCase(unittest.TestCase):
    def test_definition(self):
        """Tests all ways of defining a FuzzyDecimal."""
        fuzz = fuzzy.FuzzyDecimal(2.0, 3.0)
        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertTrue(decimal.Decimal('2.0') <= res <= decimal.Decimal('3.0'),
                    "value %d is not between 2.0 and 3.0" % res)

        fuzz = fuzzy.FuzzyDecimal(4.0)
        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertTrue(decimal.Decimal('0.0') <= res <= decimal.Decimal('4.0'),
                    "value %d is not between 0.0 and 4.0" % res)

        fuzz = fuzzy.FuzzyDecimal(1.0, 4.0, precision=5)
        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertTrue(decimal.Decimal('0.54') <= res <= decimal.Decimal('4.0'),
                    "value %d is not between 0.54 and 4.0" % res)
            self.assertTrue(res.as_tuple().exponent, -5)

    def test_biased(self):
        fake_uniform = lambda low, high: low + high

        fuzz = fuzzy.FuzzyDecimal(2.0, 8.0)

        with mock.patch('random.uniform', fake_uniform):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(decimal.Decimal('10.0'), res)

    def test_biased_high_only(self):
        fake_uniform = lambda low, high: low + high

        fuzz = fuzzy.FuzzyDecimal(8.0)

        with mock.patch('random.uniform', fake_uniform):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(decimal.Decimal('8.0'), res)

    def test_precision(self):
        fake_uniform = lambda low, high: low + high + 0.001

        fuzz = fuzzy.FuzzyDecimal(8.0, precision=3)

        with mock.patch('random.uniform', fake_uniform):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(decimal.Decimal('8.001').quantize(decimal.Decimal(10) ** -3), res)


class FuzzyDateTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Setup useful constants
        cls.jan1 = datetime.date(2013, 1, 1)
        cls.jan3 = datetime.date(2013, 1, 3)
        cls.jan31 = datetime.date(2013, 1, 31)

    def test_accurate_definition(self):
        """Tests all ways of defining a FuzzyDate."""
        fuzz = fuzzy.FuzzyDate(self.jan1, self.jan31)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertLessEqual(self.jan1, res)
            self.assertLessEqual(res, self.jan31)

    def test_partial_definition(self):
        """Test defining a FuzzyDate without passing an end date."""
        with utils.mocked_date_today(self.jan3, fuzzy):
            fuzz = fuzzy.FuzzyDate(self.jan1)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertLessEqual(self.jan1, res)
            self.assertLessEqual(res, self.jan3)

    def test_invalid_definition(self):
        self.assertRaises(ValueError, fuzzy.FuzzyDate,
            self.jan31, self.jan1)

    def test_invalid_partial_definition(self):
        with utils.mocked_date_today(self.jan1, fuzzy):
            self.assertRaises(ValueError, fuzzy.FuzzyDate,
                self.jan31)

    def test_biased(self):
        """Tests a FuzzyDate with a biased random.randint."""

        fake_randint = lambda low, high: (low + high) // 2
        fuzz = fuzzy.FuzzyDate(self.jan1, self.jan31)

        with mock.patch('random.randint', fake_randint):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(datetime.date(2013, 1, 16), res)

    def test_biased_partial(self):
        """Tests a FuzzyDate with a biased random and implicit upper bound."""
        with utils.mocked_date_today(self.jan3, fuzzy):
            fuzz = fuzzy.FuzzyDate(self.jan1)

        fake_randint = lambda low, high: (low + high) // 2
        with mock.patch('random.randint', fake_randint):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(datetime.date(2013, 1, 2), res)


class FuzzyNaiveDateTimeTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Setup useful constants
        cls.jan1 = datetime.datetime(2013, 1, 1)
        cls.jan3 = datetime.datetime(2013, 1, 3)
        cls.jan31 = datetime.datetime(2013, 1, 31)

    def test_accurate_definition(self):
        """Tests explicit definition of a FuzzyNaiveDateTime."""
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertLessEqual(self.jan1, res)
            self.assertLessEqual(res, self.jan31)

    def test_partial_definition(self):
        """Test defining a FuzzyNaiveDateTime without passing an end date."""
        with utils.mocked_datetime_now(self.jan3, fuzzy):
            fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertLessEqual(self.jan1, res)
            self.assertLessEqual(res, self.jan3)

    def test_aware_start(self):
        """Tests that a timezone-aware start datetime is rejected."""
        self.assertRaises(ValueError, fuzzy.FuzzyNaiveDateTime,
            self.jan1.replace(tzinfo=compat.UTC), self.jan31)

    def test_aware_end(self):
        """Tests that a timezone-aware end datetime is rejected."""
        self.assertRaises(ValueError, fuzzy.FuzzyNaiveDateTime,
            self.jan1, self.jan31.replace(tzinfo=compat.UTC))

    def test_force_year(self):
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31, force_year=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.year)

    def test_force_month(self):
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31, force_month=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.month)

    def test_force_day(self):
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31, force_day=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.day)

    def test_force_hour(self):
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31, force_hour=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.hour)

    def test_force_minute(self):
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31, force_minute=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.minute)

    def test_force_second(self):
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31, force_second=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.second)

    def test_force_microsecond(self):
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31, force_microsecond=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.microsecond)

    def test_invalid_definition(self):
        self.assertRaises(ValueError, fuzzy.FuzzyNaiveDateTime,
            self.jan31, self.jan1)

    def test_invalid_partial_definition(self):
        with utils.mocked_datetime_now(self.jan1, fuzzy):
            self.assertRaises(ValueError, fuzzy.FuzzyNaiveDateTime,
                self.jan31)

    def test_biased(self):
        """Tests a FuzzyDate with a biased random.randint."""

        fake_randint = lambda low, high: (low + high) // 2
        fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1, self.jan31)

        with mock.patch('random.randint', fake_randint):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(datetime.datetime(2013, 1, 16), res)

    def test_biased_partial(self):
        """Tests a FuzzyDate with a biased random and implicit upper bound."""
        with utils.mocked_datetime_now(self.jan3, fuzzy):
            fuzz = fuzzy.FuzzyNaiveDateTime(self.jan1)

        fake_randint = lambda low, high: (low + high) // 2
        with mock.patch('random.randint', fake_randint):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(datetime.datetime(2013, 1, 2), res)


class FuzzyDateTimeTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Setup useful constants
        cls.jan1 = datetime.datetime(2013, 1, 1, tzinfo=compat.UTC)
        cls.jan3 = datetime.datetime(2013, 1, 3, tzinfo=compat.UTC)
        cls.jan31 = datetime.datetime(2013, 1, 31, tzinfo=compat.UTC)

    def test_accurate_definition(self):
        """Tests explicit definition of a FuzzyDateTime."""
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertLessEqual(self.jan1, res)
            self.assertLessEqual(res, self.jan31)

    def test_partial_definition(self):
        """Test defining a FuzzyDateTime without passing an end date."""
        with utils.mocked_datetime_now(self.jan3, fuzzy):
            fuzz = fuzzy.FuzzyDateTime(self.jan1)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertLessEqual(self.jan1, res)
            self.assertLessEqual(res, self.jan3)

    def test_invalid_definition(self):
        self.assertRaises(ValueError, fuzzy.FuzzyDateTime,
            self.jan31, self.jan1)

    def test_invalid_partial_definition(self):
        with utils.mocked_datetime_now(self.jan1, fuzzy):
            self.assertRaises(ValueError, fuzzy.FuzzyDateTime,
                self.jan31)

    def test_naive_start(self):
        """Tests that a timezone-naive start datetime is rejected."""
        self.assertRaises(ValueError, fuzzy.FuzzyDateTime,
            self.jan1.replace(tzinfo=None), self.jan31)

    def test_naive_end(self):
        """Tests that a timezone-naive end datetime is rejected."""
        self.assertRaises(ValueError, fuzzy.FuzzyDateTime,
            self.jan1, self.jan31.replace(tzinfo=None))

    def test_force_year(self):
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31, force_year=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.year)

    def test_force_month(self):
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31, force_month=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.month)

    def test_force_day(self):
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31, force_day=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.day)

    def test_force_hour(self):
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31, force_hour=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.hour)

    def test_force_minute(self):
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31, force_minute=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.minute)

    def test_force_second(self):
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31, force_second=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.second)

    def test_force_microsecond(self):
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31, force_microsecond=4)

        for _i in range(20):
            res = fuzz.evaluate(2, None, False)
            self.assertEqual(4, res.microsecond)

    def test_biased(self):
        """Tests a FuzzyDate with a biased random.randint."""

        fake_randint = lambda low, high: (low + high) // 2
        fuzz = fuzzy.FuzzyDateTime(self.jan1, self.jan31)

        with mock.patch('random.randint', fake_randint):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(datetime.datetime(2013, 1, 16, tzinfo=compat.UTC), res)

    def test_biased_partial(self):
        """Tests a FuzzyDate with a biased random and implicit upper bound."""
        with utils.mocked_datetime_now(self.jan3, fuzzy):
            fuzz = fuzzy.FuzzyDateTime(self.jan1)

        fake_randint = lambda low, high: (low + high) // 2
        with mock.patch('random.randint', fake_randint):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual(datetime.datetime(2013, 1, 2, tzinfo=compat.UTC), res)


class FuzzyTextTestCase(unittest.TestCase):

    def test_unbiased(self):
        chars = ['a', 'b', 'c']
        fuzz = fuzzy.FuzzyText(prefix='pre', suffix='post', chars=chars, length=12)
        res = fuzz.evaluate(2, None, False)

        self.assertEqual('pre', res[:3])
        self.assertEqual('post', res[-4:])
        self.assertEqual(3 + 12 + 4, len(res))

        for char in res[3:-4]:
            self.assertIn(char, chars)

    def test_mock(self):
        fake_choice = lambda chars: chars[0]

        chars = ['a', 'b', 'c']
        fuzz = fuzzy.FuzzyText(prefix='pre', suffix='post', chars=chars, length=4)
        with mock.patch('random.choice', fake_choice):
            res = fuzz.evaluate(2, None, False)

        self.assertEqual('preaaaapost', res)

    def test_generator(self):
        def options():
            yield 'a'
            yield 'b'
            yield 'c'

        fuzz = fuzzy.FuzzyText(chars=options(), length=12)
        res = fuzz.evaluate(2, None, False)

        self.assertEqual(12, len(res))

        for char in res:
            self.assertIn(char, ['a', 'b', 'c'])