[unittest] Run setUp only once
roy at panix.com
Wed Jul 30 03:20:53 CEST 2008
In article <871w1cr49a.fsf at nokile.rath.org>,
Nikolaus Rath <Nikolaus at rath.org> wrote:
> But at least this variation doesn't work, because unittest apparently
> also creates two separate TwoTests instances for the two tests. Isn't
> there some way to convince unittest to reuse the same instance instead
> of trying to solve the problem in the test code itself?
Nope. It's a fundamental part of the Xunit design that every test gets a
complete, virgin environment in which to run.
The sample code that Jean-Paul gave you:
> class TwoTests(unittest.TestCase):
> setUpResult = None
> def setUp(self):
> if self.setUpResult is None:
> self.setUpResult = computeIt()
does indeed create two instances of TwoTests, but it only calls computeIt()
once, into which (presumably) all the expensive stuff has been refactored.
This is, of course, a violation of the rule that says each test must run in
a clean environment, but if you want to violate that rule, that's up to
you. Presumably you know your system and have made an informed decision as
a consenting adult that you understand the risks and this is what you want
Another variation on this would be to take this code out of setUp(), and
instead create a singleton class (there's a good recipe for this on active
state) which does your shared setup. Then in the two tests which need
this, explicitly call the singleton factory. I think this is a little
cleaner than Jean-Paul's way, because at least it isolates the shared stuff
to exactly the two tests which need it.
More information about the Python-list