[Python-ideas] Overloading operators for testing

Arek Bulski arek.bulski at gmail.com
Sat Sep 17 20:52:31 EDT 2016


I am using declarative testing a lot and I found out why unit tests are so
clunky. The reason why assertEquals(a,b) is used is because if we put
`assert a==b` then nose can catch the AssertionError but wont find out what
was returned or expected. This could be easily overcome if we allow
oveloading == operator from outside. Right now == would have to be changed
for every lefhand object that is compared in the tests, builtin types
including. We could use a way to change it from above, so to speak.
Consider this:

def __glob_eq__(a,b):
  if not a == b:
      raise FoundInequalityError(a,b)
  return True

assert obj1 == obj2   #<-- using eq above

Nose could easily catch FoundInequalityError and print whatever
assertEquals would. This goes very handy when you consider declarative unit
testing that I use in my project. I have a  unitest.TestCase derivative and
the actual testcase has a method that yields individual comparisons, like
this:

class TestBinary(declarativeunittest.TestCase):
    def alltestsinteractive(self):

        yield [func(1) == 2]
        shuffle(alist)
        yield [sorted(alist) == [1,2,3]]

Notice that this allows to put imperative statements in between declarative
cases. So shuffled() is no longer necessary in this code. :)

pozdrawiam,
Arkadiusz Bulski
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160918/3687d986/attachment-0001.html>


More information about the Python-ideas mailing list