1"""Test suite for statistics module, including helper NumericTestCase and
2approx_equal function.
3
4"""
5
6import collections
7import collections.abc
8import decimal
9import doctest
10import math
11import random
12import sys
13import unittest
14
15from decimal import Decimal
16from fractions import Fraction
17
18
19# Module to be tested.
20import statistics
21
22
23# === Helper functions and class ===
24
25def sign(x):
26    """Return -1.0 for negatives, including -0.0, otherwise +1.0."""
27    return math.copysign(1, x)
28
29def _nan_equal(a, b):
30    """Return True if a and b are both the same kind of NAN.
31
32    >>> _nan_equal(Decimal('NAN'), Decimal('NAN'))
33    True
34    >>> _nan_equal(Decimal('sNAN'), Decimal('sNAN'))
35    True
36    >>> _nan_equal(Decimal('NAN'), Decimal('sNAN'))
37    False
38    >>> _nan_equal(Decimal(42), Decimal('NAN'))
39    False
40
41    >>> _nan_equal(float('NAN'), float('NAN'))
42    True
43    >>> _nan_equal(float('NAN'), 0.5)
44    False
45
46    >>> _nan_equal(float('NAN'), Decimal('NAN'))
47    False
48
49    NAN payloads are not compared.
50    """
51    if type(a) is not type(b):
52        return False
53    if isinstance(a, float):
54        return math.isnan(a) and math.isnan(b)
55    aexp = a.as_tuple()[2]
56    bexp = b.as_tuple()[2]
57    return (aexp == bexp) and (aexp in ('n', 'N'))  # Both NAN or both sNAN.
58
59
60def _calc_errors(actual, expected):
61    """Return the absolute and relative errors between two numbers.
62
63    >>> _calc_errors(100, 75)
64    (25, 0.25)
65    >>> _calc_errors(100, 100)
66    (0, 0.0)
67
68    Returns the (absolute error, relative error) between the two arguments.
69    """
70    base = max(abs(actual), abs(expected))
71    abs_err = abs(actual - expected)
72    rel_err = abs_err/base if base else float('inf')
73    return (abs_err, rel_err)
74
75
76def approx_equal(x, y, tol=1e-12, rel=1e-7):
77    """approx_equal(x, y [, tol [, rel]]) => True|False
78
79    Return True if numbers x and y are approximately equal, to within some
80    margin of error, otherwise return False. Numbers which compare equal
81    will also compare approximately equal.
82
83    x is approximately equal to y if the difference between them is less than
84    an absolute error tol or a relative error rel, whichever is bigger.
85
86    If given, both tol and rel must be finite, non-negative numbers. If not
87    given, default values are tol=1e-12 and rel=1e-7.
88
89    >>> approx_equal(1.2589, 1.2587, tol=0.0003, rel=0)
90    True
91    >>> approx_equal(1.2589, 1.2587, tol=0.0001, rel=0)
92    False
93
94    Absolute error is defined as abs(x-y); if that is less than or equal to
95    tol, x and y are considered approximately equal.
96
97    Relative error is defined as abs((x-y)/x) or abs((x-y)/y), whichever is
98    smaller, provided x or y are not zero. If that figure is less than or
99    equal to rel, x and y are considered approximately equal.
100
101    Complex numbers are not directly supported. If you wish to compare to
102    complex numbers, extract their real and imaginary parts and compare them
103    individually.
104
105    NANs always compare unequal, even with themselves. Infinities compare
106    approximately equal if they have the same sign (both positive or both
107    negative). Infinities with different signs compare unequal; so do
108    comparisons of infinities with finite numbers.
109    """
110    if tol < 0 or rel < 0:
111        raise ValueError('error tolerances must be non-negative')
112    # NANs are never equal to anything, approximately or otherwise.
113    if math.isnan(x) or math.isnan(y):
114        return False
115    # Numbers which compare equal also compare approximately equal.
116    if x == y:
117        # This includes the case of two infinities with the same sign.
118        return True
119    if math.isinf(x) or math.isinf(y):
120        # This includes the case of two infinities of opposite sign, or
121        # one infinity and one finite number.
122        return False
123    # Two finite numbers.
124    actual_error = abs(x - y)
125    allowed_error = max(tol, rel*max(abs(x), abs(y)))
126    return actual_error <= allowed_error
127
128
129# This class exists only as somewhere to stick a docstring containing
130# doctests. The following docstring and tests were originally in a separate
131# module. Now that it has been merged in here, I need somewhere to hang the.
132# docstring. Ultimately, this class will die, and the information below will
133# either become redundant, or be moved into more appropriate places.
134class _DoNothing:
135    """
136    When doing numeric work, especially with floats, exact equality is often
137    not what you want. Due to round-off error, it is often a bad idea to try
138    to compare floats with equality. Instead the usual procedure is to test
139    them with some (hopefully small!) allowance for error.
140
141    The ``approx_equal`` function allows you to specify either an absolute
142    error tolerance, or a relative error, or both.
143
144    Absolute error tolerances are simple, but you need to know the magnitude
145    of the quantities being compared:
146
147    >>> approx_equal(12.345, 12.346, tol=1e-3)
148    True
149    >>> approx_equal(12.345e6, 12.346e6, tol=1e-3)  # tol is too small.
150    False
151
152    Relative errors are more suitable when the values you are comparing can
153    vary in magnitude:
154
155    >>> approx_equal(12.345, 12.346, rel=1e-4)
156    True
157    >>> approx_equal(12.345e6, 12.346e6, rel=1e-4)
158    True
159
160    but a naive implementation of relative error testing can run into trouble
161    around zero.
162
163    If you supply both an absolute tolerance and a relative error, the
164    comparison succeeds if either individual test succeeds:
165
166    >>> approx_equal(12.345e6, 12.346e6, tol=1e-3, rel=1e-4)
167    True
168
169    """
170    pass
171
172
173
174# We prefer this for testing numeric values that may not be exactly equal,
175# and avoid using TestCase.assertAlmostEqual, because it sucks :-)
176
177class NumericTestCase(unittest.TestCase):
178    """Unit test class for numeric work.
179
180    This subclasses TestCase. In addition to the standard method
181    ``TestCase.assertAlmostEqual``,  ``assertApproxEqual`` is provided.
182    """
183    # By default, we expect exact equality, unless overridden.
184    tol = rel = 0
185
186    def assertApproxEqual(
187            self, first, second, tol=None, rel=None, msg=None
188            ):
189        """Test passes if ``first`` and ``second`` are approximately equal.
190
191        This test passes if ``first`` and ``second`` are equal to
192        within ``tol``, an absolute error, or ``rel``, a relative error.
193
194        If either ``tol`` or ``rel`` are None or not given, they default to
195        test attributes of the same name (by default, 0).
196
197        The objects may be either numbers, or sequences of numbers. Sequences
198        are tested element-by-element.
199
200        >>> class MyTest(NumericTestCase):
201        ...     def test_number(self):
202        ...         x = 1.0/6
203        ...         y = sum([x]*6)
204        ...         self.assertApproxEqual(y, 1.0, tol=1e-15)
205        ...     def test_sequence(self):
206        ...         a = [1.001, 1.001e-10, 1.001e10]
207        ...         b = [1.0, 1e-10, 1e10]
208        ...         self.assertApproxEqual(a, b, rel=1e-3)
209        ...
210        >>> import unittest
211        >>> from io import StringIO  # Suppress test runner output.
212        >>> suite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
213        >>> unittest.TextTestRunner(stream=StringIO()).run(suite)
214        <unittest.runner.TextTestResult run=2 errors=0 failures=0>
215
216        """
217        if tol is None:
218            tol = self.tol
219        if rel is None:
220            rel = self.rel
221        if (
222                isinstance(first, collections.abc.Sequence) and
223                isinstance(second, collections.abc.Sequence)
224            ):
225            check = self._check_approx_seq
226        else:
227            check = self._check_approx_num
228        check(first, second, tol, rel, msg)
229
230    def _check_approx_seq(self, first, second, tol, rel, msg):
231        if len(first) != len(second):
232            standardMsg = (
233                "sequences differ in length: %d items != %d items"
234                % (len(first), len(second))
235                )
236            msg = self._formatMessage(msg, standardMsg)
237            raise self.failureException(msg)
238        for i, (a,e) in enumerate(zip(first, second)):
239            self._check_approx_num(a, e, tol, rel, msg, i)
240
241    def _check_approx_num(self, first, second, tol, rel, msg, idx=None):
242        if approx_equal(first, second, tol, rel):
243            # Test passes. Return early, we are done.
244            return None
245        # Otherwise we failed.
246        standardMsg = self._make_std_err_msg(first, second, tol, rel, idx)
247        msg = self._formatMessage(msg, standardMsg)
248        raise self.failureException(msg)
249
250    @staticmethod
251    def _make_std_err_msg(first, second, tol, rel, idx):
252        # Create the standard error message for approx_equal failures.
253        assert first != second
254        template = (
255            '  %r != %r\n'
256            '  values differ by more than tol=%r and rel=%r\n'
257            '  -> absolute error = %r\n'
258            '  -> relative error = %r'
259            )
260        if idx is not None:
261            header = 'numeric sequences first differ at index %d.\n' % idx
262            template = header + template
263        # Calculate actual errors:
264        abs_err, rel_err = _calc_errors(first, second)
265        return template % (first, second, tol, rel, abs_err, rel_err)
266
267
268# ========================
269# === Test the helpers ===
270# ========================
271
272class TestSign(unittest.TestCase):
273    """Test that the helper function sign() works correctly."""
274    def testZeroes(self):
275        # Test that signed zeroes report their sign correctly.
276        self.assertEqual(sign(0.0), +1)
277        self.assertEqual(sign(-0.0), -1)
278
279
280# --- Tests for approx_equal ---
281
282class ApproxEqualSymmetryTest(unittest.TestCase):
283    # Test symmetry of approx_equal.
284
285    def test_relative_symmetry(self):
286        # Check that approx_equal treats relative error symmetrically.
287        # (a-b)/a is usually not equal to (a-b)/b. Ensure that this
288        # doesn't matter.
289        #
290        #   Note: the reason for this test is that an early version
291        #   of approx_equal was not symmetric. A relative error test
292        #   would pass, or fail, depending on which value was passed
293        #   as the first argument.
294        #
295        args1 = [2456, 37.8, -12.45, Decimal('2.54'), Fraction(17, 54)]
296        args2 = [2459, 37.2, -12.41, Decimal('2.59'), Fraction(15, 54)]
297        assert len(args1) == len(args2)
298        for a, b in zip(args1, args2):
299            self.do_relative_symmetry(a, b)
300
301    def do_relative_symmetry(self, a, b):
302        a, b = min(a, b), max(a, b)
303        assert a < b
304        delta = b - a  # The absolute difference between the values.
305        rel_err1, rel_err2 = abs(delta/a), abs(delta/b)
306        # Choose an error margin halfway between the two.
307        rel = (rel_err1 + rel_err2)/2
308        # Now see that values a and b compare approx equal regardless of
309        # which is given first.
310        self.assertTrue(approx_equal(a, b, tol=0, rel=rel))
311        self.assertTrue(approx_equal(b, a, tol=0, rel=rel))
312
313    def test_symmetry(self):
314        # Test that approx_equal(a, b) == approx_equal(b, a)
315        args = [-23, -2, 5, 107, 93568]
316        delta = 2
317        for a in args:
318            for type_ in (int, float, Decimal, Fraction):
319                x = type_(a)*100
320                y = x + delta
321                r = abs(delta/max(x, y))
322                # There are five cases to check:
323                # 1) actual error <= tol, <= rel
324                self.do_symmetry_test(x, y, tol=delta, rel=r)
325                self.do_symmetry_test(x, y, tol=delta+1, rel=2*r)
326                # 2) actual error > tol, > rel
327                self.do_symmetry_test(x, y, tol=delta-1, rel=r/2)
328                # 3) actual error <= tol, > rel
329                self.do_symmetry_test(x, y, tol=delta, rel=r/2)
330                # 4) actual error > tol, <= rel
331                self.do_symmetry_test(x, y, tol=delta-1, rel=r)
332                self.do_symmetry_test(x, y, tol=delta-1, rel=2*r)
333                # 5) exact equality test
334                self.do_symmetry_test(x, x, tol=0, rel=0)
335                self.do_symmetry_test(x, y, tol=0, rel=0)
336
337    def do_symmetry_test(self, a, b, tol, rel):
338        template = "approx_equal comparisons don't match for %r"
339        flag1 = approx_equal(a, b, tol, rel)
340        flag2 = approx_equal(b, a, tol, rel)
341        self.assertEqual(flag1, flag2, template.format((a, b, tol, rel)))
342
343
344class ApproxEqualExactTest(unittest.TestCase):
345    # Test the approx_equal function with exactly equal values.
346    # Equal values should compare as approximately equal.
347    # Test cases for exactly equal values, which should compare approx
348    # equal regardless of the error tolerances given.
349
350    def do_exactly_equal_test(self, x, tol, rel):
351        result = approx_equal(x, x, tol=tol, rel=rel)
352        self.assertTrue(result, 'equality failure for x=%r' % x)
353        result = approx_equal(-x, -x, tol=tol, rel=rel)
354        self.assertTrue(result, 'equality failure for x=%r' % -x)
355
356    def test_exactly_equal_ints(self):
357        # Test that equal int values are exactly equal.
358        for n in [42, 19740, 14974, 230, 1795, 700245, 36587]:
359            self.do_exactly_equal_test(n, 0, 0)
360
361    def test_exactly_equal_floats(self):
362        # Test that equal float values are exactly equal.
363        for x in [0.42, 1.9740, 1497.4, 23.0, 179.5, 70.0245, 36.587]:
364            self.do_exactly_equal_test(x, 0, 0)
365
366    def test_exactly_equal_fractions(self):
367        # Test that equal Fraction values are exactly equal.
368        F = Fraction
369        for f in [F(1, 2), F(0), F(5, 3), F(9, 7), F(35, 36), F(3, 7)]:
370            self.do_exactly_equal_test(f, 0, 0)
371
372    def test_exactly_equal_decimals(self):
373        # Test that equal Decimal values are exactly equal.
374        D = Decimal
375        for d in map(D, "8.2 31.274 912.04 16.745 1.2047".split()):
376            self.do_exactly_equal_test(d, 0, 0)
377
378    def test_exactly_equal_absolute(self):
379        # Test that equal values are exactly equal with an absolute error.
380        for n in [16, 1013, 1372, 1198, 971, 4]:
381            # Test as ints.
382            self.do_exactly_equal_test(n, 0.01, 0)
383            # Test as floats.
384            self.do_exactly_equal_test(n/10, 0.01, 0)
385            # Test as Fractions.
386            f = Fraction(n, 1234)
387            self.do_exactly_equal_test(f, 0.01, 0)
388
389    def test_exactly_equal_absolute_decimals(self):
390        # Test equal Decimal values are exactly equal with an absolute error.
391        self.do_exactly_equal_test(Decimal("3.571"), Decimal("0.01"), 0)
392        self.do_exactly_equal_test(-Decimal("81.3971"), Decimal("0.01"), 0)
393
394    def test_exactly_equal_relative(self):
395        # Test that equal values are exactly equal with a relative error.
396        for x in [8347, 101.3, -7910.28, Fraction(5, 21)]:
397            self.do_exactly_equal_test(x, 0, 0.01)
398        self.do_exactly_equal_test(Decimal("11.68"), 0, Decimal("0.01"))
399
400    def test_exactly_equal_both(self):
401        # Test that equal values are equal when both tol and rel are given.
402        for x in [41017, 16.742, -813.02, Fraction(3, 8)]:
403            self.do_exactly_equal_test(x, 0.1, 0.01)
404        D = Decimal
405        self.do_exactly_equal_test(D("7.2"), D("0.1"), D("0.01"))
406
407
408class ApproxEqualUnequalTest(unittest.TestCase):
409    # Unequal values should compare unequal with zero error tolerances.
410    # Test cases for unequal values, with exact equality test.
411
412    def do_exactly_unequal_test(self, x):
413        for a in (x, -x):
414            result = approx_equal(a, a+1, tol=0, rel=0)
415            self.assertFalse(result, 'inequality failure for x=%r' % a)
416
417    def test_exactly_unequal_ints(self):
418        # Test unequal int values are unequal with zero error tolerance.
419        for n in [951, 572305, 478, 917, 17240]:
420            self.do_exactly_unequal_test(n)
421
422    def test_exactly_unequal_floats(self):
423        # Test unequal float values are unequal with zero error tolerance.
424        for x in [9.51, 5723.05, 47.8, 9.17, 17.24]:
425            self.do_exactly_unequal_test(x)
426
427    def test_exactly_unequal_fractions(self):
428        # Test that unequal Fractions are unequal with zero error tolerance.
429        F = Fraction
430        for f in [F(1, 5), F(7, 9), F(12, 11), F(101, 99023)]:
431            self.do_exactly_unequal_test(f)
432
433    def test_exactly_unequal_decimals(self):
434        # Test that unequal Decimals are unequal with zero error tolerance.
435        for d in map(Decimal, "3.1415 298.12 3.47 18.996 0.00245".split()):
436            self.do_exactly_unequal_test(d)
437
438
439class ApproxEqualInexactTest(unittest.TestCase):
440    # Inexact test cases for approx_error.
441    # Test cases when comparing two values that are not exactly equal.
442
443    # === Absolute error tests ===
444
445    def do_approx_equal_abs_test(self, x, delta):
446        template = "Test failure for x={!r}, y={!r}"
447        for y in (x + delta, x - delta):
448            msg = template.format(x, y)
449            self.assertTrue(approx_equal(x, y, tol=2*delta, rel=0), msg)
450            self.assertFalse(approx_equal(x, y, tol=delta/2, rel=0), msg)
451
452    def test_approx_equal_absolute_ints(self):
453        # Test approximate equality of ints with an absolute error.
454        for n in [-10737, -1975, -7, -2, 0, 1, 9, 37, 423, 9874, 23789110]:
455            self.do_approx_equal_abs_test(n, 10)
456            self.do_approx_equal_abs_test(n, 2)
457
458    def test_approx_equal_absolute_floats(self):
459        # Test approximate equality of floats with an absolute error.
460        for x in [-284.126, -97.1, -3.4, -2.15, 0.5, 1.0, 7.8, 4.23, 3817.4]:
461            self.do_approx_equal_abs_test(x, 1.5)
462            self.do_approx_equal_abs_test(x, 0.01)
463            self.do_approx_equal_abs_test(x, 0.0001)
464
465    def test_approx_equal_absolute_fractions(self):
466        # Test approximate equality of Fractions with an absolute error.
467        delta = Fraction(1, 29)
468        numerators = [-84, -15, -2, -1, 0, 1, 5, 17, 23, 34, 71]
469        for f in (Fraction(n, 29) for n in numerators):
470            self.do_approx_equal_abs_test(f, delta)
471            self.do_approx_equal_abs_test(f, float(delta))
472
473    def test_approx_equal_absolute_decimals(self):
474        # Test approximate equality of Decimals with an absolute error.
475        delta = Decimal("0.01")
476        for d in map(Decimal, "1.0 3.5 36.08 61.79 7912.3648".split()):
477            self.do_approx_equal_abs_test(d, delta)
478            self.do_approx_equal_abs_test(-d, delta)
479
480    def test_cross_zero(self):
481        # Test for the case of the two values having opposite signs.
482        self.assertTrue(approx_equal(1e-5, -1e-5, tol=1e-4, rel=0))
483
484    # === Relative error tests ===
485
486    def do_approx_equal_rel_test(self, x, delta):
487        template = "Test failure for x={!r}, y={!r}"
488        for y in (x*(1+delta), x*(1-delta)):
489            msg = template.format(x, y)
490            self.assertTrue(approx_equal(x, y, tol=0, rel=2*delta), msg)
491            self.assertFalse(approx_equal(x, y, tol=0, rel=delta/2), msg)
492
493    def test_approx_equal_relative_ints(self):
494        # Test approximate equality of ints with a relative error.
495        self.assertTrue(approx_equal(64, 47, tol=0, rel=0.36))
496        self.assertTrue(approx_equal(64, 47, tol=0, rel=0.37))
497        # ---
498        self.assertTrue(approx_equal(449, 512, tol=0, rel=0.125))
499        self.assertTrue(approx_equal(448, 512, tol=0, rel=0.125))
500        self.assertFalse(approx_equal(447, 512, tol=0, rel=0.125))
501
502    def test_approx_equal_relative_floats(self):
503        # Test approximate equality of floats with a relative error.
504        for x in [-178.34, -0.1, 0.1, 1.0, 36.97, 2847.136, 9145.074]:
505            self.do_approx_equal_rel_test(x, 0.02)
506            self.do_approx_equal_rel_test(x, 0.0001)
507
508    def test_approx_equal_relative_fractions(self):
509        # Test approximate equality of Fractions with a relative error.
510        F = Fraction
511        delta = Fraction(3, 8)
512        for f in [F(3, 84), F(17, 30), F(49, 50), F(92, 85)]:
513            for d in (delta, float(delta)):
514                self.do_approx_equal_rel_test(f, d)
515                self.do_approx_equal_rel_test(-f, d)
516
517    def test_approx_equal_relative_decimals(self):
518        # Test approximate equality of Decimals with a relative error.
519        for d in map(Decimal, "0.02 1.0 5.7 13.67 94.138 91027.9321".split()):
520            self.do_approx_equal_rel_test(d, Decimal("0.001"))
521            self.do_approx_equal_rel_test(-d, Decimal("0.05"))
522
523    # === Both absolute and relative error tests ===
524
525    # There are four cases to consider:
526    #   1) actual error <= both absolute and relative error
527    #   2) actual error <= absolute error but > relative error
528    #   3) actual error <= relative error but > absolute error
529    #   4) actual error > both absolute and relative error
530
531    def do_check_both(self, a, b, tol, rel, tol_flag, rel_flag):
532        check = self.assertTrue if tol_flag else self.assertFalse
533        check(approx_equal(a, b, tol=tol, rel=0))
534        check = self.assertTrue if rel_flag else self.assertFalse
535        check(approx_equal(a, b, tol=0, rel=rel))
536        check = self.assertTrue if (tol_flag or rel_flag) else self.assertFalse
537        check(approx_equal(a, b, tol=tol, rel=rel))
538
539    def test_approx_equal_both1(self):
540        # Test actual error <= both absolute and relative error.
541        self.do_check_both(7.955, 7.952, 0.004, 3.8e-4, True, True)
542        self.do_check_both(-7.387, -7.386, 0.002, 0.0002, True, True)
543
544    def test_approx_equal_both2(self):
545        # Test actual error <= absolute error but > relative error.
546        self.do_check_both(7.955, 7.952, 0.004, 3.7e-4, True, False)
547
548    def test_approx_equal_both3(self):
549        # Test actual error <= relative error but > absolute error.
550        self.do_check_both(7.955, 7.952, 0.001, 3.8e-4, False, True)
551
552    def test_approx_equal_both4(self):
553        # Test actual error > both absolute and relative error.
554        self.do_check_both(2.78, 2.75, 0.01, 0.001, False, False)
555        self.do_check_both(971.44, 971.47, 0.02, 3e-5, False, False)
556
557
558class ApproxEqualSpecialsTest(unittest.TestCase):
559    # Test approx_equal with NANs and INFs and zeroes.
560
561    def test_inf(self):
562        for type_ in (float, Decimal):
563            inf = type_('inf')
564            self.assertTrue(approx_equal(inf, inf))
565            self.assertTrue(approx_equal(inf, inf, 0, 0))
566            self.assertTrue(approx_equal(inf, inf, 1, 0.01))
567            self.assertTrue(approx_equal(-inf, -inf))
568            self.assertFalse(approx_equal(inf, -inf))
569            self.assertFalse(approx_equal(inf, 1000))
570
571    def test_nan(self):
572        for type_ in (float, Decimal):
573            nan = type_('nan')
574            for other in (nan, type_('inf'), 1000):
575                self.assertFalse(approx_equal(nan, other))
576
577    def test_float_zeroes(self):
578        nzero = math.copysign(0.0, -1)
579        self.assertTrue(approx_equal(nzero, 0.0, tol=0.1, rel=0.1))
580
581    def test_decimal_zeroes(self):
582        nzero = Decimal("-0.0")
583        self.assertTrue(approx_equal(nzero, Decimal(0), tol=0.1, rel=0.1))
584
585
586class TestApproxEqualErrors(unittest.TestCase):
587    # Test error conditions of approx_equal.
588
589    def test_bad_tol(self):
590        # Test negative tol raises.
591        self.assertRaises(ValueError, approx_equal, 100, 100, -1, 0.1)
592
593    def test_bad_rel(self):
594        # Test negative rel raises.
595        self.assertRaises(ValueError, approx_equal, 100, 100, 1, -0.1)
596
597
598# --- Tests for NumericTestCase ---
599
600# The formatting routine that generates the error messages is complex enough
601# that it too needs testing.
602
603class TestNumericTestCase(unittest.TestCase):
604    # The exact wording of NumericTestCase error messages is *not* guaranteed,
605    # but we need to give them some sort of test to ensure that they are
606    # generated correctly. As a compromise, we look for specific substrings
607    # that are expected to be found even if the overall error message changes.
608
609    def do_test(self, args):
610        actual_msg = NumericTestCase._make_std_err_msg(*args)
611        expected = self.generate_substrings(*args)
612        for substring in expected:
613            self.assertIn(substring, actual_msg)
614
615    def test_numerictestcase_is_testcase(self):
616        # Ensure that NumericTestCase actually is a TestCase.
617        self.assertTrue(issubclass(NumericTestCase, unittest.TestCase))
618
619    def test_error_msg_numeric(self):
620        # Test the error message generated for numeric comparisons.
621        args = (2.5, 4.0, 0.5, 0.25, None)
622        self.do_test(args)
623
624    def test_error_msg_sequence(self):
625        # Test the error message generated for sequence comparisons.
626        args = (3.75, 8.25, 1.25, 0.5, 7)
627        self.do_test(args)
628
629    def generate_substrings(self, first, second, tol, rel, idx):
630        """Return substrings we expect to see in error messages."""
631        abs_err, rel_err = _calc_errors(first, second)
632        substrings = [
633                'tol=%r' % tol,
634                'rel=%r' % rel,
635                'absolute error = %r' % abs_err,
636                'relative error = %r' % rel_err,
637                ]
638        if idx is not None:
639            substrings.append('differ at index %d' % idx)
640        return substrings
641
642
643# =======================================
644# === Tests for the statistics module ===
645# =======================================
646
647
648class GlobalsTest(unittest.TestCase):
649    module = statistics
650    expected_metadata = ["__doc__", "__all__"]
651
652    def test_meta(self):
653        # Test for the existence of metadata.
654        for meta in self.expected_metadata:
655            self.assertTrue(hasattr(self.module, meta),
656                            "%s not present" % meta)
657
658    def test_check_all(self):
659        # Check everything in __all__ exists and is public.
660        module = self.module
661        for name in module.__all__:
662            # No private names in __all__:
663            self.assertFalse(name.startswith("_"),
664                             'private name "%s" in __all__' % name)
665            # And anything in __all__ must exist:
666            self.assertTrue(hasattr(module, name),
667                            'missing name "%s" in __all__' % name)
668
669
670class DocTests(unittest.TestCase):
671    @unittest.skipIf(sys.flags.optimize >= 2,
672                     "Docstrings are omitted with -OO and above")
673    def test_doc_tests(self):
674        failed, tried = doctest.testmod(statistics, optionflags=doctest.ELLIPSIS)
675        self.assertGreater(tried, 0)
676        self.assertEqual(failed, 0)
677
678class StatisticsErrorTest(unittest.TestCase):
679    def test_has_exception(self):
680        errmsg = (
681                "Expected StatisticsError to be a ValueError, but got a"
682                " subclass of %r instead."
683                )
684        self.assertTrue(hasattr(statistics, 'StatisticsError'))
685        self.assertTrue(
686                issubclass(statistics.StatisticsError, ValueError),
687                errmsg % statistics.StatisticsError.__base__
688                )
689
690
691# === Tests for private utility functions ===
692
693class ExactRatioTest(unittest.TestCase):
694    # Test _exact_ratio utility.
695
696    def test_int(self):
697        for i in (-20, -3, 0, 5, 99, 10**20):
698            self.assertEqual(statistics._exact_ratio(i), (i, 1))
699
700    def test_fraction(self):
701        numerators = (-5, 1, 12, 38)
702        for n in numerators:
703            f = Fraction(n, 37)
704            self.assertEqual(statistics._exact_ratio(f), (n, 37))
705
706    def test_float(self):
707        self.assertEqual(statistics._exact_ratio(0.125), (1, 8))
708        self.assertEqual(statistics._exact_ratio(1.125), (9, 8))
709        data = [random.uniform(-100, 100) for _ in range(100)]
710        for x in data:
711            num, den = statistics._exact_ratio(x)
712            self.assertEqual(x, num/den)
713
714    def test_decimal(self):
715        D = Decimal
716        _exact_ratio = statistics._exact_ratio
717        self.assertEqual(_exact_ratio(D("0.125")), (1, 8))
718        self.assertEqual(_exact_ratio(D("12.345")), (2469, 200))
719        self.assertEqual(_exact_ratio(D("-1.98")), (-99, 50))
720
721    def test_inf(self):
722        INF = float("INF")
723        class MyFloat(float):
724            pass
725        class MyDecimal(Decimal):
726            pass
727        for inf in (INF, -INF):
728            for type_ in (float, MyFloat, Decimal, MyDecimal):
729                x = type_(inf)
730                ratio = statistics._exact_ratio(x)
731                self.assertEqual(ratio, (x, None))
732                self.assertEqual(type(ratio[0]), type_)
733                self.assertTrue(math.isinf(ratio[0]))
734
735    def test_float_nan(self):
736        NAN = float("NAN")
737        class MyFloat(float):
738            pass
739        for nan in (NAN, MyFloat(NAN)):
740            ratio = statistics._exact_ratio(nan)
741            self.assertTrue(math.isnan(ratio[0]))
742            self.assertIs(ratio[1], None)
743            self.assertEqual(type(ratio[0]), type(nan))
744
745    def test_decimal_nan(self):
746        NAN = Decimal("NAN")
747        sNAN = Decimal("sNAN")
748        class MyDecimal(Decimal):
749            pass
750        for nan in (NAN, MyDecimal(NAN), sNAN, MyDecimal(sNAN)):
751            ratio = statistics._exact_ratio(nan)
752            self.assertTrue(_nan_equal(ratio[0], nan))
753            self.assertIs(ratio[1], None)
754            self.assertEqual(type(ratio[0]), type(nan))
755
756
757class DecimalToRatioTest(unittest.TestCase):
758    # Test _exact_ratio private function.
759
760    def test_infinity(self):
761        # Test that INFs are handled correctly.
762        inf = Decimal('INF')
763        self.assertEqual(statistics._exact_ratio(inf), (inf, None))
764        self.assertEqual(statistics._exact_ratio(-inf), (-inf, None))
765
766    def test_nan(self):
767        # Test that NANs are handled correctly.
768        for nan in (Decimal('NAN'), Decimal('sNAN')):
769            num, den = statistics._exact_ratio(nan)
770            # Because NANs always compare non-equal, we cannot use assertEqual.
771            # Nor can we use an identity test, as we don't guarantee anything
772            # about the object identity.
773            self.assertTrue(_nan_equal(num, nan))
774            self.assertIs(den, None)
775
776    def test_sign(self):
777        # Test sign is calculated correctly.
778        numbers = [Decimal("9.8765e12"), Decimal("9.8765e-12")]
779        for d in numbers:
780            # First test positive decimals.
781            assert d > 0
782            num, den = statistics._exact_ratio(d)
783            self.assertGreaterEqual(num, 0)
784            self.assertGreater(den, 0)
785            # Then test negative decimals.
786            num, den = statistics._exact_ratio(-d)
787            self.assertLessEqual(num, 0)
788            self.assertGreater(den, 0)
789
790    def test_negative_exponent(self):
791        # Test result when the exponent is negative.
792        t = statistics._exact_ratio(Decimal("0.1234"))
793        self.assertEqual(t, (617, 5000))
794
795    def test_positive_exponent(self):
796        # Test results when the exponent is positive.
797        t = statistics._exact_ratio(Decimal("1.234e7"))
798        self.assertEqual(t, (12340000, 1))
799
800    def test_regression_20536(self):
801        # Regression test for issue 20536.
802        # See http://bugs.python.org/issue20536
803        t = statistics._exact_ratio(Decimal("1e2"))
804        self.assertEqual(t, (100, 1))
805        t = statistics._exact_ratio(Decimal("1.47e5"))
806        self.assertEqual(t, (147000, 1))
807
808
809class IsFiniteTest(unittest.TestCase):
810    # Test _isfinite private function.
811
812    def test_finite(self):
813        # Test that finite numbers are recognised as finite.
814        for x in (5, Fraction(1, 3), 2.5, Decimal("5.5")):
815            self.assertTrue(statistics._isfinite(x))
816
817    def test_infinity(self):
818        # Test that INFs are not recognised as finite.
819        for x in (float("inf"), Decimal("inf")):
820            self.assertFalse(statistics._isfinite(x))
821
822    def test_nan(self):
823        # Test that NANs are not recognised as finite.
824        for x in (float("nan"), Decimal("NAN"), Decimal("sNAN")):
825            self.assertFalse(statistics._isfinite(x))
826
827
828class CoerceTest(unittest.TestCase):
829    # Test that private function _coerce correctly deals with types.
830
831    # The coercion rules are currently an implementation detail, although at
832    # some point that should change. The tests and comments here define the
833    # correct implementation.
834
835    # Pre-conditions of _coerce:
836    #
837    #   - The first time _sum calls _coerce, the
838    #   - coerce(T, S) will never be called with bool as the first argument;
839    #     this is a pre-condition, guarded with an assertion.
840
841    #
842    #   - coerce(T, T) will always return T; we assume T is a valid numeric
843    #     type. Violate this assumption at your own risk.
844    #
845    #   - Apart from as above, bool is treated as if it were actually int.
846    #
847    #   - coerce(int, X) and coerce(X, int) return X.
848    #   -
849    def test_bool(self):
850        # bool is somewhat special, due to the pre-condition that it is
851        # never given as the first argument to _coerce, and that it cannot
852        # be subclassed. So we test it specially.
853        for T in (int, float, Fraction, Decimal):
854            self.assertIs(statistics._coerce(T, bool), T)
855            class MyClass(T): pass
856            self.assertIs(statistics._coerce(MyClass, bool), MyClass)
857
858    def assertCoerceTo(self, A, B):
859        """Assert that type A coerces to B."""
860        self.assertIs(statistics._coerce(A, B), B)
861        self.assertIs(statistics._coerce(B, A), B)
862
863    def check_coerce_to(self, A, B):
864        """Checks that type A coerces to B, including subclasses."""
865        # Assert that type A is coerced to B.
866        self.assertCoerceTo(A, B)
867        # Subclasses of A are also coerced to B.
868        class SubclassOfA(A): pass
869        self.assertCoerceTo(SubclassOfA, B)
870        # A, and subclasses of A, are coerced to subclasses of B.
871        class SubclassOfB(B): pass
872        self.assertCoerceTo(A, SubclassOfB)
873        self.assertCoerceTo(SubclassOfA, SubclassOfB)
874
875    def assertCoerceRaises(self, A, B):
876        """Assert that coercing A to B, or vice versa, raises TypeError."""
877        self.assertRaises(TypeError, statistics._coerce, (A, B))
878        self.assertRaises(TypeError, statistics._coerce, (B, A))
879
880    def check_type_coercions(self, T):
881        """Check that type T coerces correctly with subclasses of itself."""
882        assert T is not bool
883        # Coercing a type with itself returns the same type.
884        self.assertIs(statistics._coerce(T, T), T)
885        # Coercing a type with a subclass of itself returns the subclass.
886        class U(T): pass
887        class V(T): pass
888        class W(U): pass
889        for typ in (U, V, W):
890            self.assertCoerceTo(T, typ)
891        self.assertCoerceTo(U, W)
892        # Coercing two subclasses that aren't parent/child is an error.
893        self.assertCoerceRaises(U, V)
894        self.assertCoerceRaises(V, W)
895
896    def test_int(self):
897        # Check that int coerces correctly.
898        self.check_type_coercions(int)
899        for typ in (float, Fraction, Decimal):
900            self.check_coerce_to(int, typ)
901
902    def test_fraction(self):
903        # Check that Fraction coerces correctly.
904        self.check_type_coercions(Fraction)
905        self.check_coerce_to(Fraction, float)
906
907    def test_decimal(self):
908        # Check that Decimal coerces correctly.
909        self.check_type_coercions(Decimal)
910
911    def test_float(self):
912        # Check that float coerces correctly.
913        self.check_type_coercions(float)
914
915    def test_non_numeric_types(self):
916        for bad_type in (str, list, type(None), tuple, dict):
917            for good_type in (int, float, Fraction, Decimal):
918                self.assertCoerceRaises(good_type, bad_type)
919
920    def test_incompatible_types(self):
921        # Test that incompatible types raise.
922        for T in (float, Fraction):
923            class MySubclass(T): pass
924            self.assertCoerceRaises(T, Decimal)
925            self.assertCoerceRaises(MySubclass, Decimal)
926
927
928class ConvertTest(unittest.TestCase):
929    # Test private _convert function.
930
931    def check_exact_equal(self, x, y):
932        """Check that x equals y, and has the same type as well."""
933        self.assertEqual(x, y)
934        self.assertIs(type(x), type(y))
935
936    def test_int(self):
937        # Test conversions to int.
938        x = statistics._convert(Fraction(71), int)
939        self.check_exact_equal(x, 71)
940        class MyInt(int): pass
941        x = statistics._convert(Fraction(17), MyInt)
942        self.check_exact_equal(x, MyInt(17))
943
944    def test_fraction(self):
945        # Test conversions to Fraction.
946        x = statistics._convert(Fraction(95, 99), Fraction)
947        self.check_exact_equal(x, Fraction(95, 99))
948        class MyFraction(Fraction):
949            def __truediv__(self, other):
950                return self.__class__(super().__truediv__(other))
951        x = statistics._convert(Fraction(71, 13), MyFraction)
952        self.check_exact_equal(x, MyFraction(71, 13))
953
954    def test_float(self):
955        # Test conversions to float.
956        x = statistics._convert(Fraction(-1, 2), float)
957        self.check_exact_equal(x, -0.5)
958        class MyFloat(float):
959            def __truediv__(self, other):
960                return self.__class__(super().__truediv__(other))
961        x = statistics._convert(Fraction(9, 8), MyFloat)
962        self.check_exact_equal(x, MyFloat(1.125))
963
964    def test_decimal(self):
965        # Test conversions to Decimal.
966        x = statistics._convert(Fraction(1, 40), Decimal)
967        self.check_exact_equal(x, Decimal("0.025"))
968        class MyDecimal(Decimal):
969            def __truediv__(self, other):
970                return self.__class__(super().__truediv__(other))
971        x = statistics._convert(Fraction(-15, 16), MyDecimal)
972        self.check_exact_equal(x, MyDecimal("-0.9375"))
973
974    def test_inf(self):
975        for INF in (float('inf'), Decimal('inf')):
976            for inf in (INF, -INF):
977                x = statistics._convert(inf, type(inf))
978                self.check_exact_equal(x, inf)
979
980    def test_nan(self):
981        for nan in (float('nan'), Decimal('NAN'), Decimal('sNAN')):
982            x = statistics._convert(nan, type(nan))
983            self.assertTrue(_nan_equal(x, nan))
984
985
986class FailNegTest(unittest.TestCase):
987    """Test _fail_neg private function."""
988
989    def test_pass_through(self):
990        # Test that values are passed through unchanged.
991        values = [1, 2.0, Fraction(3), Decimal(4)]
992        new = list(statistics._fail_neg(values))
993        self.assertEqual(values, new)
994
995    def test_negatives_raise(self):
996        # Test that negatives raise an exception.
997        for x in [1, 2.0, Fraction(3), Decimal(4)]:
998            seq = [-x]
999            it = statistics._fail_neg(seq)
1000            self.assertRaises(statistics.StatisticsError, next, it)
1001
1002    def test_error_msg(self):
1003        # Test that a given error message is used.
1004        msg = "badness #%d" % random.randint(10000, 99999)
1005        try:
1006            next(statistics._fail_neg([-1], msg))
1007        except statistics.StatisticsError as e:
1008            errmsg = e.args[0]
1009        else:
1010            self.fail("expected exception, but it didn't happen")
1011        self.assertEqual(errmsg, msg)
1012
1013
1014# === Tests for public functions ===
1015
1016class UnivariateCommonMixin:
1017    # Common tests for most univariate functions that take a data argument.
1018
1019    def test_no_args(self):
1020        # Fail if given no arguments.
1021        self.assertRaises(TypeError, self.func)
1022
1023    def test_empty_data(self):
1024        # Fail when the data argument (first argument) is empty.
1025        for empty in ([], (), iter([])):
1026            self.assertRaises(statistics.StatisticsError, self.func, empty)
1027
1028    def prepare_data(self):
1029        """Return int data for various tests."""
1030        data = list(range(10))
1031        while data == sorted(data):
1032            random.shuffle(data)
1033        return data
1034
1035    def test_no_inplace_modifications(self):
1036        # Test that the function does not modify its input data.
1037        data = self.prepare_data()
1038        assert len(data) != 1  # Necessary to avoid infinite loop.
1039        assert data != sorted(data)
1040        saved = data[:]
1041        assert data is not saved
1042        _ = self.func(data)
1043        self.assertListEqual(data, saved, "data has been modified")
1044
1045    def test_order_doesnt_matter(self):
1046        # Test that the order of data points doesn't change the result.
1047
1048        # CAUTION: due to floating point rounding errors, the result actually
1049        # may depend on the order. Consider this test representing an ideal.
1050        # To avoid this test failing, only test with exact values such as ints
1051        # or Fractions.
1052        data = [1, 2, 3, 3, 3, 4, 5, 6]*100
1053        expected = self.func(data)
1054        random.shuffle(data)
1055        actual = self.func(data)
1056        self.assertEqual(expected, actual)
1057
1058    def test_type_of_data_collection(self):
1059        # Test that the type of iterable data doesn't effect the result.
1060        class MyList(list):
1061            pass
1062        class MyTuple(tuple):
1063            pass
1064        def generator(data):
1065            return (obj for obj in data)
1066        data = self.prepare_data()
1067        expected = self.func(data)
1068        for kind in (list, tuple, iter, MyList, MyTuple, generator):
1069            result = self.func(kind(data))
1070            self.assertEqual(result, expected)
1071
1072    def test_range_data(self):
1073        # Test that functions work with range objects.
1074        data = range(20, 50, 3)
1075        expected = self.func(list(data))
1076        self.assertEqual(self.func(data), expected)
1077
1078    def test_bad_arg_types(self):
1079        # Test that function raises when given data of the wrong type.
1080
1081        # Don't roll the following into a loop like this:
1082        #   for bad in list_of_bad:
1083        #       self.check_for_type_error(bad)
1084        #
1085        # Since assertRaises doesn't show the arguments that caused the test
1086        # failure, it is very difficult to debug these test failures when the
1087        # following are in a loop.
1088        self.check_for_type_error(None)
1089        self.check_for_type_error(23)
1090        self.check_for_type_error(42.0)
1091        self.check_for_type_error(object())
1092
1093    def check_for_type_error(self, *args):
1094        self.assertRaises(TypeError, self.func, *args)
1095
1096    def test_type_of_data_element(self):
1097        # Check the type of data elements doesn't affect the numeric result.
1098        # This is a weaker test than UnivariateTypeMixin.testTypesConserved,
1099        # because it checks the numeric result by equality, but not by type.
1100        class MyFloat(float):
1101            def __truediv__(self, other):
1102                return type(self)(super().__truediv__(other))
1103            def __add__(self, other):
1104                return type(self)(super().__add__(other))
1105            __radd__ = __add__
1106
1107        raw = self.prepare_data()
1108        expected = self.func(raw)
1109        for kind in (float, MyFloat, Decimal, Fraction):
1110            data = [kind(x) for x in raw]
1111            result = type(expected)(self.func(data))
1112            self.assertEqual(result, expected)
1113
1114
1115class UnivariateTypeMixin:
1116    """Mixin class for type-conserving functions.
1117
1118    This mixin class holds test(s) for functions which conserve the type of
1119    individual data points. E.g. the mean of a list of Fractions should itself
1120    be a Fraction.
1121
1122    Not all tests to do with types need go in this class. Only those that
1123    rely on the function returning the same type as its input data.
1124    """
1125    def prepare_types_for_conservation_test(self):
1126        """Return the types which are expected to be conserved."""
1127        class MyFloat(float):
1128            def __truediv__(self, other):
1129                return type(self)(super().__truediv__(other))
1130            def __rtruediv__(self, other):
1131                return type(self)(super().__rtruediv__(other))
1132            def __sub__(self, other):
1133                return type(self)(super().__sub__(other))
1134            def __rsub__(self, other):
1135                return type(self)(super().__rsub__(other))
1136            def __pow__(self, other):
1137                return type(self)(super().__pow__(other))
1138            def __add__(self, other):
1139                return type(self)(super().__add__(other))
1140            __radd__ = __add__
1141        return (float, Decimal, Fraction, MyFloat)
1142
1143    def test_types_conserved(self):
1144        # Test that functions keeps the same type as their data points.
1145        # (Excludes mixed data types.) This only tests the type of the return
1146        # result, not the value.
1147        data = self.prepare_data()
1148        for kind in self.prepare_types_for_conservation_test():
1149            d = [kind(x) for x in data]
1150            result = self.func(d)
1151            self.assertIs(type(result), kind)
1152
1153
1154class TestSumCommon(UnivariateCommonMixin, UnivariateTypeMixin):
1155    # Common test cases for statistics._sum() function.
1156
1157    # This test suite looks only at the numeric value returned by _sum,
1158    # after conversion to the appropriate type.
1159    def setUp(self):
1160        def simplified_sum(*args):
1161            T, value, n = statistics._sum(*args)
1162            return statistics._coerce(value, T)
1163        self.func = simplified_sum
1164
1165
1166class TestSum(NumericTestCase):
1167    # Test cases for statistics._sum() function.
1168
1169    # These tests look at the entire three value tuple returned by _sum.
1170
1171    def setUp(self):
1172        self.func = statistics._sum
1173
1174    def test_empty_data(self):
1175        # Override test for empty data.
1176        for data in ([], (), iter([])):
1177            self.assertEqual(self.func(data), (int, Fraction(0), 0))
1178            self.assertEqual(self.func(data, 23), (int, Fraction(23), 0))
1179            self.assertEqual(self.func(data, 2.3), (float, Fraction(2.3), 0))
1180
1181    def test_ints(self):
1182        self.assertEqual(self.func([1, 5, 3, -4, -8, 20, 42, 1]),
1183                         (int, Fraction(60), 8))
1184        self.assertEqual(self.func([4, 2, 3, -8, 7], 1000),
1185                         (int, Fraction(1008), 5))
1186
1187    def test_floats(self):
1188        self.assertEqual(self.func([0.25]*20),
1189                         (float, Fraction(5.0), 20))
1190        self.assertEqual(self.func([0.125, 0.25, 0.5, 0.75], 1.5),
1191                         (float, Fraction(3.125), 4))
1192
1193    def test_fractions(self):
1194        self.assertEqual(self.func([Fraction(1, 1000)]*500),
1195                         (Fraction, Fraction(1, 2), 500))
1196
1197    def test_decimals(self):
1198        D = Decimal
1199        data = [D("0.001"), D("5.246"), D("1.702"), D("-0.025"),
1200                D("3.974"), D("2.328"), D("4.617"), D("2.843"),
1201                ]
1202        self.assertEqual(self.func(data),
1203                         (Decimal, Decimal("20.686"), 8))
1204
1205    def test_compare_with_math_fsum(self):
1206        # Compare with the math.fsum function.
1207        # Ideally we ought to get the exact same result, but sometimes
1208        # we differ by a very slight amount :-(
1209        data = [random.uniform(-100, 1000) for _ in range(1000)]
1210        self.assertApproxEqual(float(self.func(data)[1]), math.fsum(data), rel=2e-16)
1211
1212    def test_start_argument(self):
1213        # Test that the optional start argument works correctly.
1214        data = [random.uniform(1, 1000) for _ in range(100)]
1215        t = self.func(data)[1]
1216        self.assertEqual(t+42, self.func(data, 42)[1])
1217        self.assertEqual(t-23, self.func(data, -23)[1])
1218        self.assertEqual(t+Fraction(1e20), self.func(data, 1e20)[1])
1219
1220    def test_strings_fail(self):
1221        # Sum of strings should fail.
1222        self.assertRaises(TypeError, self.func, [1, 2, 3], '999')
1223        self.assertRaises(TypeError, self.func, [1, 2, 3, '999'])
1224
1225    def test_bytes_fail(self):
1226        # Sum of bytes should fail.
1227        self.assertRaises(TypeError, self.func, [1, 2, 3], b'999')
1228        self.assertRaises(TypeError, self.func, [1, 2, 3, b'999'])
1229
1230    def test_mixed_sum(self):
1231        # Mixed input types are not (currently) allowed.
1232        # Check that mixed data types fail.
1233        self.assertRaises(TypeError, self.func, [1, 2.0, Decimal(1)])
1234        # And so does mixed start argument.
1235        self.assertRaises(TypeError, self.func, [1, 2.0], Decimal(1))
1236
1237
1238class SumTortureTest(NumericTestCase):
1239    def test_torture(self):
1240        # Tim Peters' torture test for sum, and variants of same.
1241        self.assertEqual(statistics._sum([1, 1e100, 1, -1e100]*10000),
1242                         (float, Fraction(20000.0), 40000))
1243        self.assertEqual(statistics._sum([1e100, 1, 1, -1e100]*10000),
1244                         (float, Fraction(20000.0), 40000))
1245        T, num, count = statistics._sum([1e-100, 1, 1e-100, -1]*10000)
1246        self.assertIs(T, float)
1247        self.assertEqual(count, 40000)
1248        self.assertApproxEqual(float(num), 2.0e-96, rel=5e-16)
1249
1250
1251class SumSpecialValues(NumericTestCase):
1252    # Test that sum works correctly with IEEE-754 special values.
1253
1254    def test_nan(self):
1255        for type_ in (float, Decimal):
1256            nan = type_('nan')
1257            result = statistics._sum([1, nan, 2])[1]
1258            self.assertIs(type(result), type_)
1259            self.assertTrue(math.isnan(result))
1260
1261    def check_infinity(self, x, inf):
1262        """Check x is an infinity of the same type and sign as inf."""
1263        self.assertTrue(math.isinf(x))
1264        self.assertIs(type(x), type(inf))
1265        self.assertEqual(x > 0, inf > 0)
1266        assert x == inf
1267
1268    def do_test_inf(self, inf):
1269        # Adding a single infinity gives infinity.
1270        result = statistics._sum([1, 2, inf, 3])[1]
1271        self.check_infinity(result, inf)
1272        # Adding two infinities of the same sign also gives infinity.
1273        result = statistics._sum([1, 2, inf, 3, inf, 4])[1]
1274        self.check_infinity(result, inf)
1275
1276    def test_float_inf(self):
1277        inf = float('inf')
1278        for sign in (+1, -1):
1279            self.do_test_inf(sign*inf)
1280
1281    def test_decimal_inf(self):
1282        inf = Decimal('inf')
1283        for sign in (+1, -1):
1284            self.do_test_inf(sign*inf)
1285
1286    def test_float_mismatched_infs(self):
1287        # Test that adding two infinities of opposite sign gives a NAN.
1288        inf = float('inf')
1289        result = statistics._sum([1, 2, inf, 3, -inf, 4])[1]
1290        self.assertTrue(math.isnan(result))
1291
1292    def test_decimal_extendedcontext_mismatched_infs_to_nan(self):
1293        # Test adding Decimal INFs with opposite sign returns NAN.
1294        inf = Decimal('inf')
1295        data = [1, 2, inf, 3, -inf, 4]
1296        with decimal.localcontext(decimal.ExtendedContext):
1297            self.assertTrue(math.isnan(statistics._sum(data)[1]))
1298
1299    def test_decimal_basiccontext_mismatched_infs_to_nan(self):
1300        # Test adding Decimal INFs with opposite sign raises InvalidOperation.
1301        inf = Decimal('inf')
1302        data = [1, 2, inf, 3, -inf, 4]
1303        with decimal.localcontext(decimal.BasicContext):
1304            self.assertRaises(decimal.InvalidOperation, statistics._sum, data)
1305
1306    def test_decimal_snan_raises(self):
1307        # Adding sNAN should raise InvalidOperation.
1308        sNAN = Decimal('sNAN')
1309        data = [1, sNAN, 2]
1310        self.assertRaises(decimal.InvalidOperation, statistics._sum, data)
1311
1312
1313# === Tests for averages ===
1314
1315class AverageMixin(UnivariateCommonMixin):
1316    # Mixin class holding common tests for averages.
1317
1318    def test_single_value(self):
1319        # Average of a single value is the value itself.
1320        for x in (23, 42.5, 1.3e15, Fraction(15, 19), Decimal('0.28')):
1321            self.assertEqual(self.func([x]), x)
1322
1323    def prepare_values_for_repeated_single_test(self):
1324        return (3.5, 17, 2.5e15, Fraction(61, 67), Decimal('4.9712'))
1325
1326    def test_repeated_single_value(self):
1327        # The average of a single repeated value is the value itself.
1328        for x in self.prepare_values_for_repeated_single_test():
1329            for count in (2, 5, 10, 20):
1330                with self.subTest(x=x, count=count):
1331                    data = [x]*count
1332                    self.assertEqual(self.func(data), x)
1333
1334
1335class TestMean(NumericTestCase, AverageMixin, UnivariateTypeMixin):
1336    def setUp(self):
1337        self.func = statistics.mean
1338
1339    def test_torture_pep(self):
1340        # "Torture Test" from PEP-450.
1341        self.assertEqual(self.func([1e100, 1, 3, -1e100]), 1)
1342
1343    def test_ints(self):
1344        # Test mean with ints.
1345        data = [0, 1, 2, 3, 3, 3, 4, 5, 5, 6, 7, 7, 7, 7, 8, 9]
1346        random.shuffle(data)
1347        self.assertEqual(self.func(data), 4.8125)
1348
1349    def test_floats(self):
1350        # Test mean with floats.
1351        data = [17.25, 19.75, 20.0, 21.5, 21.75, 23.25, 25.125, 27.5]
1352        random.shuffle(data)
1353        self.assertEqual(self.func(data), 22.015625)
1354
1355    def test_decimals(self):
1356        # Test mean with Decimals.
1357        D = Decimal
1358        data = [D("1.634"), D("2.517"), D("3.912"), D("4.072"), D("5.813")]
1359        random.shuffle(data)
1360        self.assertEqual(self.func(data), D("3.5896"))
1361
1362    def test_fractions(self):
1363        # Test mean with Fractions.
1364        F = Fraction
1365        data = [F(1, 2), F(2, 3), F(3, 4), F(4, 5), F(5, 6), F(6, 7), F(7, 8)]
1366        random.shuffle(data)
1367        self.assertEqual(self.func(data), F(1479, 1960))
1368
1369    def test_inf(self):
1370        # Test mean with infinities.
1371        raw = [1, 3, 5, 7, 9]  # Use only ints, to avoid TypeError later.
1372        for kind in (float, Decimal):
1373            for sign in (1, -1):
1374                inf = kind("inf")*sign
1375                data = raw + [inf]
1376                result = self.func(data)
1377                self.assertTrue(math.isinf(result))
1378                self.assertEqual(result, inf)
1379
1380    def test_mismatched_infs(self):
1381        # Test mean with infinities of opposite sign.
1382        data = [2, 4, 6, float('inf'), 1, 3, 5, float('-inf')]
1383        result = self.func(data)
1384        self.assertTrue(math.isnan(result))
1385
1386    def test_nan(self):
1387        # Test mean with NANs.
1388        raw = [1, 3, 5, 7, 9]  # Use only ints, to avoid TypeError later.
1389        for kind in (float, Decimal):
1390            inf = kind("nan")
1391            data = raw + [inf]
1392            result = self.func(data)
1393            self.assertTrue(math.isnan(result))
1394
1395    def test_big_data(self):
1396        # Test adding a large constant to every data point.
1397        c = 1e9
1398        data = [3.4, 4.5, 4.9, 6.7, 6.8, 7.2, 8.0, 8.1, 9.4]
1399        expected = self.func(data) + c
1400        assert expected != c
1401        result = self.func([x+c for x in data])
1402        self.assertEqual(result, expected)
1403
1404    def test_doubled_data(self):
1405        # Mean of [a,b,c...z] should be same as for [a,a,b,b,c,c...z,z].
1406        data = [random.uniform(-3, 5) for _ in range(1000)]
1407        expected = self.func(data)
1408        actual = self.func(data*2)
1409        self.assertApproxEqual(actual, expected)
1410
1411    def test_regression_20561(self):
1412        # Regression test for issue 20561.
1413        # See http://bugs.python.org/issue20561
1414        d = Decimal('1e4')
1415        self.assertEqual(statistics.mean([d]), d)
1416
1417    def test_regression_25177(self):
1418        # Regression test for issue 25177.
1419        # Ensure very big and very small floats don't overflow.
1420        # See http://bugs.python.org/issue25177.
1421        self.assertEqual(statistics.mean(
1422            [8.988465674311579e+307, 8.98846567431158e+307]),
1423            8.98846567431158e+307)
1424        big = 8.98846567431158e+307
1425        tiny = 5e-324
1426        for n in (2, 3, 5, 200):
1427            self.assertEqual(statistics.mean([big]*n), big)
1428            self.assertEqual(statistics.mean([tiny]*n), tiny)
1429
1430
1431class TestHarmonicMean(NumericTestCase, AverageMixin, UnivariateTypeMixin):
1432    def setUp(self):
1433        self.func = statistics.harmonic_mean
1434
1435    def prepare_data(self):
1436        # Override mixin method.
1437        values = super().prepare_data()
1438        values.remove(0)
1439        return values
1440
1441    def prepare_values_for_repeated_single_test(self):
1442        # Override mixin method.
1443        return (3.5, 17, 2.5e15, Fraction(61, 67), Decimal('4.125'))
1444
1445    def test_zero(self):
1446        # Test that harmonic mean returns zero when given zero.
1447        values = [1, 0, 2]
1448        self.assertEqual(self.func(values), 0)
1449
1450    def test_negative_error(self):
1451        # Test that harmonic mean raises when given a negative value.
1452        exc = statistics.StatisticsError
1453        for values in ([-1], [1, -2, 3]):
1454            with self.subTest(values=values):
1455                self.assertRaises(exc, self.func, values)
1456
1457    def test_ints(self):
1458        # Test harmonic mean with ints.
1459        data = [2, 4, 4, 8, 16, 16]
1460        random.shuffle(data)
1461        self.assertEqual(self.func(data), 6*4/5)
1462
1463    def test_floats_exact(self):
1464        # Test harmonic mean with some carefully chosen floats.
1465        data = [1/8, 1/4, 1/4, 1/2, 1/2]
1466        random.shuffle(data)
1467        self.assertEqual(self.func(data), 1/4)
1468        self.assertEqual(self.func([0.25, 0.5, 1.0, 1.0]), 0.5)
1469
1470    def test_singleton_lists(self):
1471        # Test that harmonic mean([x]) returns (approximately) x.
1472        for x in range(1, 101):
1473            self.assertEqual(self.func([x]), x)
1474
1475    def test_decimals_exact(self):
1476        # Test harmonic mean with some carefully chosen Decimals.
1477        D = Decimal
1478        self.assertEqual(self.func([D(15), D(30), D(60), D(60)]), D(30))
1479        data = [D("0.05"), D("0.10"), D("0.20"), D("0.20")]
1480        random.shuffle(data)
1481        self.assertEqual(self.func(data), D("0.10"))
1482        data = [D("1.68"), D("0.32"), D("5.94"), D("2.75")]
1483        random.shuffle(data)
1484        self.assertEqual(self.func(data), D(66528)/70723)
1485
1486    def test_fractions(self):
1487        # Test harmonic mean with Fractions.
1488        F = Fraction
1489        data = [F(1, 2), F(2, 3), F(3, 4), F(4, 5), F(5, 6), F(6, 7), F(7, 8)]
1490        random.shuffle(data)
1491        self.assertEqual(self.func(data), F(7*420, 4029))
1492
1493    def test_inf(self):
1494        # Test harmonic mean with infinity.
1495        values = [2.0, float('inf'), 1.0]
1496        self.assertEqual(self.func(values), 2.0)
1497
1498    def test_nan(self):
1499        # Test harmonic mean with NANs.
1500        values = [2.0, float('nan'), 1.0]
1501        self.assertTrue(math.isnan(self.func(values)))
1502
1503    def test_multiply_data_points(self):
1504        # Test multiplying every data point by a constant.
1505        c = 111
1506        data = [3.4, 4.5, 4.9, 6.7, 6.8, 7.2, 8.0, 8.1, 9.4]
1507        expected = self.func(data)*c
1508        result = self.func([x*c for x in data])
1509        self.assertEqual(result, expected)
1510
1511    def test_doubled_data(self):
1512        # Harmonic mean of [a,b...z] should be same as for [a,a,b,b...z,z].
1513        data = [random.uniform(1, 5) for _ in range(1000)]
1514        expected = self.func(data)
1515        actual = self.func(data*2)
1516        self.assertApproxEqual(actual, expected)
1517
1518
1519class TestMedian(NumericTestCase, AverageMixin):
1520    # Common tests for median and all median.* functions.
1521    def setUp(self):
1522        self.func = statistics.median
1523
1524    def prepare_data(self):
1525        """Overload method from UnivariateCommonMixin."""
1526        data = super().prepare_data()
1527        if len(data)%2 != 1:
1528            data.append(2)
1529        return data
1530
1531    def test_even_ints(self):
1532        # Test median with an even number of int data points.
1533        data = [1, 2, 3, 4, 5, 6]
1534        assert len(data)%2 == 0
1535        self.assertEqual(self.func(data), 3.5)
1536
1537    def test_odd_ints(self):
1538        # Test median with an odd number of int data points.
1539        data = [1, 2, 3, 4, 5, 6, 9]
1540        assert len(data)%2 == 1
1541        self.assertEqual(self.func(data), 4)
1542
1543    def test_odd_fractions(self):
1544        # Test median works with an odd number of Fractions.
1545        F = Fraction
1546        data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7)]
1547        assert len(data)%2 == 1
1548        random.shuffle(data)
1549        self.assertEqual(self.func(data), F(3, 7))
1550
1551    def test_even_fractions(self):
1552        # Test median works with an even number of Fractions.
1553        F = Fraction
1554        data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7), F(6, 7)]
1555        assert len(data)%2 == 0
1556        random.shuffle(data)
1557        self.assertEqual(self.func(data), F(1, 2))
1558
1559    def test_odd_decimals(self):
1560        # Test median works with an odd number of Decimals.
1561        D = Decimal
1562        data = [D('2.5'), D('3.1'), D('4.2'), D('5.7'), D('5.8')]
1563        assert len(data)%2 == 1
1564        random.shuffle(data)
1565        self.assertEqual(self.func(data), D('4.2'))
1566
1567    def test_even_decimals(self):
1568        # Test median works with an even number of Decimals.
1569        D = Decimal
1570        data = [D('1.2'), D('2.5'), D('3.1'), D('4.2'), D('5.7'), D('5.8')]
1571        assert len(data)%2 == 0
1572        random.shuffle(data)
1573        self.assertEqual(self.func(data), D('3.65'))
1574
1575
1576class TestMedianDataType(NumericTestCase, UnivariateTypeMixin):
1577    # Test conservation of data element type for median.
1578    def setUp(self):
1579        self.func = statistics.median
1580
1581    def prepare_data(self):
1582        data = list(range(15))
1583        assert len(data)%2 == 1
1584        while data == sorted(data):
1585            random.shuffle(data)
1586        return data
1587
1588
1589class TestMedianLow(TestMedian, UnivariateTypeMixin):
1590    def setUp(self):
1591        self.func = statistics.median_low
1592
1593    def test_even_ints(self):
1594        # Test median_low with an even number of ints.
1595        data = [1, 2, 3, 4, 5, 6]
1596        assert len(data)%2 == 0
1597        self.assertEqual(self.func(data), 3)
1598
1599    def test_even_fractions(self):
1600        # Test median_low works with an even number of Fractions.
1601        F = Fraction
1602        data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7), F(6, 7)]
1603        assert len(data)%2 == 0
1604        random.shuffle(data)
1605        self.assertEqual(self.func(data), F(3, 7))
1606
1607    def test_even_decimals(self):
1608        # Test median_low works with an even number of Decimals.
1609        D = Decimal
1610        data = [D('1.1'), D('2.2'), D('3.3'), D('4.4'), D('5.5'), D('6.6')]
1611        assert len(data)%2 == 0
1612        random.shuffle(data)
1613        self.assertEqual(self.func(data), D('3.3'))
1614
1615
1616class TestMedianHigh(TestMedian, UnivariateTypeMixin):
1617    def setUp(self):
1618        self.func = statistics.median_high
1619
1620    def test_even_ints(self):
1621        # Test median_high with an even number of ints.
1622        data = [1, 2, 3, 4, 5, 6]
1623        assert len(data)%2 == 0
1624        self.assertEqual(self.func(data), 4)
1625
1626    def test_even_fractions(self):
1627        # Test median_high works with an even number of Fractions.
1628        F = Fraction
1629        data = [F(1, 7), F(2, 7), F(3, 7), F(4, 7), F(5, 7), F(6, 7)]
1630        assert len(data)%2 == 0
1631        random.shuffle(data)
1632        self.assertEqual(self.func(data), F(4, 7))
1633
1634    def test_even_decimals(self):
1635        # Test median_high works with an even number of Decimals.
1636        D = Decimal
1637        data = [D('1.1'), D('2.2'), D('3.3'), D('4.4'), D('5.5'), D('6.6')]
1638        assert len(data)%2 == 0
1639        random.shuffle(data)
1640        self.assertEqual(self.func(data), D('4.4'))
1641
1642
1643class TestMedianGrouped(TestMedian):
1644    # Test median_grouped.
1645    # Doesn't conserve data element types, so don't use TestMedianType.
1646    def setUp(self):
1647        self.func = statistics.median_grouped
1648
1649    def test_odd_number_repeated(self):
1650        # Test median.grouped with repeated median values.
1651        data = [12, 13, 14, 14, 14, 15, 15]
1652        assert len(data)%2 == 1
1653        self.assertEqual(self.func(data), 14)
1654        #---
1655        data = [12, 13, 14, 14, 14, 14, 15]
1656        assert len(data)%2 == 1
1657        self.assertEqual(self.func(data), 13.875)
1658        #---
1659        data = [5, 10, 10, 15, 20, 20, 20, 20, 25, 25, 30]
1660        assert len(data)%2 == 1
1661        self.assertEqual(self.func(data, 5), 19.375)
1662        #---
1663        data = [16, 18, 18, 18, 18, 20, 20, 20, 22, 22, 22, 24, 24, 26, 28]
1664        assert len(data)%2 == 1
1665        self.assertApproxEqual(self.func(data, 2), 20.66666667, tol=1e-8)
1666
1667    def test_even_number_repeated(self):
1668        # Test median.grouped with repeated median values.
1669        data = [5, 10, 10, 15, 20, 20, 20, 25, 25, 30]
1670        assert len(data)%2 == 0
1671        self.assertApproxEqual(self.func(data, 5), 19.16666667, tol=1e-8)
1672        #---
1673        data = [2, 3, 4, 4, 4, 5]
1674        assert len(data)%2 == 0
1675        self.assertApproxEqual(self.func(data), 3.83333333, tol=1e-8)
1676        #---
1677        data = [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6]
1678        assert len(data)%2 == 0
1679        self.assertEqual(self.func(data), 4.5)
1680        #---
1681        data = [3, 4, 4, 4, 5, 5, 5, 5, 6, 6]
1682        assert len(data)%2 == 0
1683        self.assertEqual(self.func(data), 4.75)
1684
1685    def test_repeated_single_value(self):
1686        # Override method from AverageMixin.
1687        # Yet again, failure of median_grouped to conserve the data type
1688        # causes me headaches :-(
1689        for x in (5.3, 68, 4.3e17, Fraction(29, 101), Decimal('32.9714')):
1690            for count in (2, 5, 10, 20):
1691                data = [x]*count
1692                self.assertEqual(self.func(data), float(x))
1693
1694    def test_odd_fractions(self):
1695        # Test median_grouped works with an odd number of Fractions.
1696        F = Fraction
1697        data = [F(5, 4), F(9, 4), F(13, 4), F(13, 4), F(17, 4)]
1698        assert len(data)%2 == 1
1699        random.shuffle(data)
1700        self.assertEqual(self.func(data), 3.0)
1701
1702    def test_even_fractions(self):
1703        # Test median_grouped works with an even number of Fractions.
1704        F = Fraction
1705        data = [F(5, 4), F(9, 4), F(13, 4), F(13, 4), F(17, 4), F(17, 4)]
1706        assert len(data)%2 == 0
1707        random.shuffle(data)
1708        self.assertEqual(self.func(data), 3.25)
1709
1710    def test_odd_decimals(self):
1711        # Test median_grouped works with an odd number of Decimals.
1712        D = Decimal
1713        data = [D('5.5'), D('6.5'), D('6.5'), D('7.5'), D('8.5')]
1714        assert len(data)%2 == 1
1715        random.shuffle(data)
1716        self.assertEqual(self.func(data), 6.75)
1717
1718    def test_even_decimals(self):
1719        # Test median_grouped works with an even number of Decimals.
1720        D = Decimal
1721        data = [D('5.5'), D('5.5'), D('6.5'), D('6.5'), D('7.5'), D('8.5')]
1722        assert len(data)%2 == 0
1723        random.shuffle(data)
1724        self.assertEqual(self.func(data), 6.5)
1725        #---
1726        data = [D('5.5'), D('5.5'), D('6.5'), D('7.5'), D('7.5'), D('8.5')]
1727        assert len(data)%2 == 0
1728        random.shuffle(data)
1729        self.assertEqual(self.func(data), 7.0)
1730
1731    def test_interval(self):
1732        # Test median_grouped with interval argument.
1733        data = [2.25, 2.5, 2.5, 2.75, 2.75, 3.0, 3.0, 3.25, 3.5, 3.75]
1734        self.assertEqual(self.func(data, 0.25), 2.875)
1735        data = [2.25, 2.5, 2.5, 2.75, 2.75, 2.75, 3.0, 3.0, 3.25, 3.5, 3.75]
1736        self.assertApproxEqual(self.func(data, 0.25), 2.83333333, tol=1e-8)
1737        data = [220, 220, 240, 260, 260, 260, 260, 280, 280, 300, 320, 340]
1738        self.assertEqual(self.func(data, 20), 265.0)
1739
1740    def test_data_type_error(self):
1741        # Test median_grouped with str, bytes data types for data and interval
1742        data = ["", "", ""]
1743        self.assertRaises(TypeError, self.func, data)
1744        #---
1745        data = [b"", b"", b""]
1746        self.assertRaises(TypeError, self.func, data)
1747        #---
1748        data = [1, 2, 3]
1749        interval = ""
1750        self.assertRaises(TypeError, self.func, data, interval)
1751        #---
1752        data = [1, 2, 3]
1753        interval = b""
1754        self.assertRaises(TypeError, self.func, data, interval)
1755
1756
1757class TestMode(NumericTestCase, AverageMixin, UnivariateTypeMixin):
1758    # Test cases for the discrete version of mode.
1759    def setUp(self):
1760        self.func = statistics.mode
1761
1762    def prepare_data(self):
1763        """Overload method from UnivariateCommonMixin."""
1764        # Make sure test data has exactly one mode.
1765        return [1, 1, 1, 1, 3, 4, 7, 9, 0, 8, 2]
1766
1767    def test_range_data(self):
1768        # Override test from UnivariateCommonMixin.
1769        data = range(20, 50, 3)
1770        self.assertRaises(statistics.StatisticsError, self.func, data)
1771
1772    def test_nominal_data(self):
1773        # Test mode with nominal data.
1774        data = 'abcbdb'
1775        self.assertEqual(self.func(data), 'b')
1776        data = 'fe fi fo fum fi fi'.split()
1777        self.assertEqual(self.func(data), 'fi')
1778
1779    def test_discrete_data(self):
1780        # Test mode with discrete numeric data.
1781        data = list(range(10))
1782        for i in range(10):
1783            d = data + [i]
1784            random.shuffle(d)
1785            self.assertEqual(self.func(d), i)
1786
1787    def test_bimodal_data(self):
1788        # Test mode with bimodal data.
1789        data = [1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8, 9, 9]
1790        assert data.count(2) == data.count(6) == 4
1791        # Check for an exception.
1792        self.assertRaises(statistics.StatisticsError, self.func, data)
1793
1794    def test_unique_data_failure(self):
1795        # Test mode exception when data points are all unique.
1796        data = list(range(10))
1797        self.assertRaises(statistics.StatisticsError, self.func, data)
1798
1799    def test_none_data(self):
1800        # Test that mode raises TypeError if given None as data.
1801
1802        # This test is necessary because the implementation of mode uses
1803        # collections.Counter, which accepts None and returns an empty dict.
1804        self.assertRaises(TypeError, self.func, None)
1805
1806    def test_counter_data(self):
1807        # Test that a Counter is treated like any other iterable.
1808        data = collections.Counter([1, 1, 1, 2])
1809        # Since the keys of the counter are treated as data points, not the
1810        # counts, this should raise.
1811        self.assertRaises(statistics.StatisticsError, self.func, data)
1812
1813
1814
1815# === Tests for variances and standard deviations ===
1816
1817class VarianceStdevMixin(UnivariateCommonMixin):
1818    # Mixin class holding common tests for variance and std dev.
1819
1820    # Subclasses should inherit from this before NumericTestClass, in order
1821    # to see the rel attribute below. See testShiftData for an explanation.
1822
1823    rel = 1e-12
1824
1825    def test_single_value(self):
1826        # Deviation of a single value is zero.
1827        for x in (11, 19.8, 4.6e14, Fraction(21, 34), Decimal('8.392')):
1828            self.assertEqual(self.func([x]), 0)
1829
1830    def test_repeated_single_value(self):
1831        # The deviation of a single repeated value is zero.
1832        for x in (7.2, 49, 8.1e15, Fraction(3, 7), Decimal('62.4802')):
1833            for count in (2, 3, 5, 15):
1834                data = [x]*count
1835                self.assertEqual(self.func(data), 0)
1836
1837    def test_domain_error_regression(self):
1838        # Regression test for a domain error exception.
1839        # (Thanks to Geremy Condra.)
1840        data = [0.123456789012345]*10000
1841        # All the items are identical, so variance should be exactly zero.
1842        # We allow some small round-off error, but not much.
1843        result = self.func(data)
1844        self.assertApproxEqual(result, 0.0, tol=5e-17)
1845        self.assertGreaterEqual(result, 0)  # A negative result must fail.
1846
1847    def test_shift_data(self):
1848        # Test that shifting the data by a constant amount does not affect
1849        # the variance or stdev. Or at least not much.
1850
1851        # Due to rounding, this test should be considered an ideal. We allow
1852        # some tolerance away from "no change at all" by setting tol and/or rel
1853        # attributes. Subclasses may set tighter or looser error tolerances.
1854        raw = [1.03, 1.27, 1.94, 2.04, 2.58, 3.14, 4.75, 4.98, 5.42, 6.78]
1855        expected = self.func(raw)
1856        # Don't set shift too high, the bigger it is, the more rounding error.
1857        shift = 1e5
1858        data = [x + shift for x in raw]
1859        self.assertApproxEqual(self.func(data), expected)
1860
1861    def test_shift_data_exact(self):
1862        # Like test_shift_data, but result is always exact.
1863        raw = [1, 3, 3, 4, 5, 7, 9, 10, 11, 16]
1864        assert all(x==int(x) for x in raw)
1865        expected = self.func(raw)
1866        shift = 10**9
1867        data = [x + shift for x in raw]
1868        self.assertEqual(self.func(data), expected)
1869
1870    def test_iter_list_same(self):
1871        # Test that iter data and list data give the same result.
1872
1873        # This is an explicit test that iterators and lists are treated the
1874        # same; justification for this test over and above the similar test
1875        # in UnivariateCommonMixin is that an earlier design had variance and
1876        # friends swap between one- and two-pass algorithms, which would
1877        # sometimes give different results.
1878        data = [random.uniform(-3, 8) for _ in range(1000)]
1879        expected = self.func(data)
1880        self.assertEqual(self.func(iter(data)), expected)
1881
1882
1883class TestPVariance(VarianceStdevMixin, NumericTestCase, UnivariateTypeMixin):
1884    # Tests for population variance.
1885    def setUp(self):
1886        self.func = statistics.pvariance
1887
1888    def test_exact_uniform(self):
1889        # Test the variance against an exact result for uniform data.
1890        data = list(range(10000))
1891        random.shuffle(data)
1892        expected = (10000**2 - 1)/12  # Exact value.
1893        self.assertEqual(self.func(data), expected)
1894
1895    def test_ints(self):
1896        # Test population variance with int data.
1897        data = [4, 7, 13, 16]
1898        exact = 22.5
1899        self.assertEqual(self.func(data), exact)
1900
1901    def test_fractions(self):
1902        # Test population variance with Fraction data.
1903        F = Fraction
1904        data = [F(1, 4), F(1, 4), F(3, 4), F(7, 4)]
1905        exact = F(3, 8)
1906        result = self.func(data)
1907        self.assertEqual(result, exact)
1908        self.assertIsInstance(result, Fraction)
1909
1910    def test_decimals(self):
1911        # Test population variance with Decimal data.
1912        D = Decimal
1913        data = [D("12.1"), D("12.2"), D("12.5"), D("12.9")]
1914        exact = D('0.096875')
1915        result = self.func(data)
1916        self.assertEqual(result, exact)
1917        self.assertIsInstance(result, Decimal)
1918
1919
1920class TestVariance(VarianceStdevMixin, NumericTestCase, UnivariateTypeMixin):
1921    # Tests for sample variance.
1922    def setUp(self):
1923        self.func = statistics.variance
1924
1925    def test_single_value(self):
1926        # Override method from VarianceStdevMixin.
1927        for x in (35, 24.7, 8.2e15, Fraction(19, 30), Decimal('4.2084')):
1928            self.assertRaises(statistics.StatisticsError, self.func, [x])
1929
1930    def test_ints(self):
1931        # Test sample variance with int data.
1932        data = [4, 7, 13, 16]
1933        exact = 30
1934        self.assertEqual(self.func(data), exact)
1935
1936    def test_fractions(self):
1937        # Test sample variance with Fraction data.
1938        F = Fraction
1939        data = [F(1, 4), F(1, 4), F(3, 4), F(7, 4)]
1940        exact = F(1, 2)
1941        result = self.func(data)
1942        self.assertEqual(result, exact)
1943        self.assertIsInstance(result, Fraction)
1944
1945    def test_decimals(self):
1946        # Test sample variance with Decimal data.
1947        D = Decimal
1948        data = [D(2), D(2), D(7), D(9)]
1949        exact = 4*D('9.5')/D(3)
1950        result = self.func(data)
1951        self.assertEqual(result, exact)
1952        self.assertIsInstance(result, Decimal)
1953
1954
1955class TestPStdev(VarianceStdevMixin, NumericTestCase):
1956    # Tests for population standard deviation.
1957    def setUp(self):
1958        self.func = statistics.pstdev
1959
1960    def test_compare_to_variance(self):
1961        # Test that stdev is, in fact, the square root of variance.
1962        data = [random.uniform(-17, 24) for _ in range(1000)]
1963        expected = math.sqrt(statistics.pvariance(data))
1964        self.assertEqual(self.func(data), expected)
1965
1966
1967class TestStdev(VarianceStdevMixin, NumericTestCase):
1968    # Tests for sample standard deviation.
1969    def setUp(self):
1970        self.func = statistics.stdev
1971
1972    def test_single_value(self):
1973        # Override method from VarianceStdevMixin.
1974        for x in (81, 203.74, 3.9e14, Fraction(5, 21), Decimal('35.719')):
1975            self.assertRaises(statistics.StatisticsError, self.func, [x])
1976
1977    def test_compare_to_variance(self):
1978        # Test that stdev is, in fact, the square root of variance.
1979        data = [random.uniform(-2, 9) for _ in range(1000)]
1980        expected = math.sqrt(statistics.variance(data))
1981        self.assertEqual(self.func(data), expected)
1982
1983
1984# === Run tests ===
1985
1986def load_tests(loader, tests, ignore):
1987    """Used for doctest/unittest integration."""
1988    tests.addTests(doctest.DocTestSuite())
1989    return tests
1990
1991
1992if __name__ == "__main__":
1993    unittest.main()
1994