Test passes if ``first`` and ``second`` are approximately equal. This test passes if ``first`` and ``second`` are equal to within ``tol``, an absolute error, or ``rel``, a relative error. If either ``tol`` or ``rel`` are None or not given, they default to test attri
(
self, first, second, tol=None, rel=None, msg=None
)
| 215 | tol = rel = 0 |
| 216 | |
| 217 | def assertApproxEqual( |
| 218 | self, first, second, tol=None, rel=None, msg=None |
| 219 | ): |
| 220 | """Test passes if ``first`` and ``second`` are approximately equal. |
| 221 | |
| 222 | This test passes if ``first`` and ``second`` are equal to |
| 223 | within ``tol``, an absolute error, or ``rel``, a relative error. |
| 224 | |
| 225 | If either ``tol`` or ``rel`` are None or not given, they default to |
| 226 | test attributes of the same name (by default, 0). |
| 227 | |
| 228 | The objects may be either numbers, or sequences of numbers. Sequences |
| 229 | are tested element-by-element. |
| 230 | |
| 231 | >>> class MyTest(NumericTestCase): |
| 232 | ... def test_number(self): |
| 233 | ... x = 1.0/6 |
| 234 | ... y = sum([x]*6) |
| 235 | ... self.assertApproxEqual(y, 1.0, tol=1e-15) |
| 236 | ... def test_sequence(self): |
| 237 | ... a = [1.001, 1.001e-10, 1.001e10] |
| 238 | ... b = [1.0, 1e-10, 1e10] |
| 239 | ... self.assertApproxEqual(a, b, rel=1e-3) |
| 240 | ... |
| 241 | >>> import unittest |
| 242 | >>> from io import StringIO # Suppress test runner output. |
| 243 | >>> suite = unittest.TestLoader().loadTestsFromTestCase(MyTest) |
| 244 | >>> unittest.TextTestRunner(stream=StringIO()).run(suite) |
| 245 | <unittest.runner.TextTestResult run=2 errors=0 failures=0> |
| 246 | |
| 247 | """ |
| 248 | if tol is None: |
| 249 | tol = self.tol |
| 250 | if rel is None: |
| 251 | rel = self.rel |
| 252 | if ( |
| 253 | isinstance(first, collections.abc.Sequence) and |
| 254 | isinstance(second, collections.abc.Sequence) |
| 255 | ): |
| 256 | check = self._check_approx_seq |
| 257 | else: |
| 258 | check = self._check_approx_num |
| 259 | check(first, second, tol, rel, msg) |
| 260 | |
| 261 | def _check_approx_seq(self, first, second, tol, rel, msg): |
| 262 | if len(first) != len(second): |
no test coverage detected