classification
Title: unittest should have an assertChanges context manager
Type: enhancement Stage: resolved
Components: Tests Versions: Python 3.3
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: Jay.Moorthi, ezio.melotti, michael.foord, r.david.murray, rhettinger
Priority: normal Keywords:

Created on 2010-12-10 19:58 by Jay.Moorthi, last changed 2011-01-21 05:23 by ezio.melotti. This issue is now closed.

Messages (4)
msg123745 - (view) Author: Jay Moorthi (Jay.Moorthi) Date: 2010-12-10 19:58
It would be useful to have a new assert method in the unittest.TestCase class that checks to see if a value has changed.  I wrote a quick and dirty version like so:

class MySpecialTestCase(unittest.TestCase):
    @contextmanager
    def assertChanges(self, thing, attr=None, by=None):
        def get_value(thing, attr):
            if callable(thing):
                value = thing()
            else:
                value = getattr(thing, attr)
            return value

        old_value = get_value(thing, attr)
        yield
        new_value = get_value(thing, attr)

        if by is None:
            self.assertNotEqual(new_value, old_value)
        else:
            self.assertEqual(new_value - old_value, by)

I'm sure something better can be done to take better advantage of the unittest module's diffing tools, etc.
msg123749 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2010-12-10 20:12
I think this is the kind of thing where you are *much* better off writing a specialized assert method that exactly fits your use case.  There are too many variations on this theme, IMO, for it to make sense as an stdlib method.
msg123751 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2010-12-10 21:01
I concur with David Murray.  Usually you care about the specific value changed to, not whether it changed at all.  The changed-by variant is even more specialized and you're better of using assertEqual since you know what the new value is supposed to be:

  assertEqual(thing.attr, x)
     ...
  assertEqual(thing.attr, x+by)
msg123752 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2010-12-10 21:02
Thanks for submitting the idea though.
Perhaps, post it on the ASPN Cookbook
or on the newsgroup to see if others
are interested.
History
Date User Action Args
2011-01-21 05:23:32ezio.melottisetnosy: + ezio.melotti
components: + Tests
2010-12-10 21:02:57rhettingersetmessages: + msg123752
2010-12-10 21:01:40rhettingersetnosy: + rhettinger
messages: + msg123751
2010-12-10 20:20:41benjamin.petersonsetstatus: pending -> closed
2010-12-10 20:12:55r.david.murraysetstatus: open -> pending

versions: + Python 3.3, - Python 2.7
nosy: + r.david.murray, michael.foord

messages: + msg123749
resolution: rejected
stage: resolved
2010-12-10 19:58:34Jay.Moorthicreate