Next: , Previous: Toward Better Buildbot Tests, Up: Buildbot Tests


7.9.2 Keeping State in Tests

Python does not allow assignment to anything but the innermost local scope or the global scope with the global keyword. This presents a problem when creating nested functions:

     def test_localVariable(self):
         cb_called = False
         def cb():
             cb_called = True
         cb()
         self.assertTrue(cb_called) # will fail!

The cb_called = True assigns to a different variable than cb_called = False. In production code, it's usually best to work around such problems, but in tests this is often the clearest way to express the behavior under test.

The solution is to change something in a common mutable object. While a simple list can serve as such a mutable object, this leads to code that is hard to read. Instead, use State:

     from buildbot.test.state import State
     
     def test_localVariable(self):
         state = State(cb_called=False)
         def cb():
             state.cb_called = True
         cb()
         self.assertTrue(state.cb_called) # passes

This is almost as readable as the first example, but it actually works.