[issue27198] Adding an assertClose() method to unittest.TestCase

Robert Collins report at bugs.python.org
Fri Jun 3 19:30:13 EDT 2016


Robert Collins added the comment:

Future direction: hamcrest style matchers. You can read more about them in the context of unittest https://rbtcollins.wordpress.com/2010/05/10/maintainable-pyunit-test-suites/ and http://testtools.readthedocs.io/en/latest/for-test-authors.html#matchers - sorry about the formatting in the blog post, wordpress changed theme details some time after I wrote the post and it now renders horribly :(.

w.r.t. error messages, a regular function that raises AssertionError with a nice message will be precisely as usable.

def assert_math_isclose(first, second, rel_tol=1e-09, abs_tol=0.0, msg=None):
    if math.isclose(first, second, rel_tol=rel_tol, abs_tol=abs_tol):
        return
    standardMsg = ('%s != %s with relative tolerance of %.3g'
                   ' and absolute tolerance of %.3g' % (safe_repr(first),
                                                        safe_repr(second),
                                                        rel_tol,
                                                        abs_tol))
    if msg:
        raise AssertionError("{} : {}".format(standardMsg, msg))
    else:
        raise AssertionError(standardMsg)

The reason I'm pushing back on adding methods to TestCase is that every one we add collides with some number of subclasses out in the wild: the TestCase class has multiple distinct APIs in the same namespace - and thats very poor for maintaining compatibility.

Long term I want to have entirely separate interfaces for these things, but thats even more radical an overhaul than adding matchers as a stock facility, and I don't currently have a planned timeline for starting on that.

All of that said, I see that this isn't the same as assertAlmostEqual in mathematical terms - but in /user/ terms I think it is. So why can't we make assertAlmostEqual be this? Just add the extra parameter needed with a default value and change the implementation?

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue27198>
_______________________________________


More information about the Python-bugs-list mailing list