ยปCore Development>Code coverage>Lib/test/test_statistics.py

Python code coverage for Lib/test/test_statistics.py

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