[Python-ideas] Test Class setup and teardown in unittest

Nick Coghlan ncoghlan at gmail.com
Thu Jan 21 23:05:04 CET 2010


On a slight tangent, I'd be happier if we could move away from the
setUp/tearDown model and move towards __enter__/__exit__. The existing
convention comes from a time before the with statement - extending it
further doesn't seem like it would be taking things in the right direction.

By allowing test suites to identify context managers that are invoked by
the test framework at various points, it allows the setup/teardown code
to be cleanly separated from the test classes themselves. E.g. the test
framework might promise to do the following for each test:

  with module_cm(test_instance): # However identified
    with class_cm(test_instance): # However identified
      with test_instance: # **
        test_instance.test_method()

(** Assuming the addition of "def __enter__(self): self.setUp()" and
"def __exit__(self, *args): self.tearDown()" to unittest.TestCase for
backwards compatibility)

Caching of expensive state on the module and class context managers
would then be the prerogative of those context managers rather than the
responsibility of the test cases themselves.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list