Mike Mike - 1 year ago 241
Python Question

Python unittest.TestCase execution order

Is there a way in Python

to set the order in which test cases are run?

In my current
class, some testcases have side-effects that set conditions for the others to run properly. Now I realize the proper way to do this is to use
to do all setup realted things, but I would like to implement a design where each successive test builds slightly more state that the next can use. I find this much more elegant.

class MyTest(TestCase):
def test_setup(self):
#do something
def test_thing(self)
#do something that depends on test_setup()

Ideally, I would like the tests to be run in the order they appear in the class. It appears that they run in alphabetical order.

Answer Source

Don't make them independent tests - if you want a monolithic test, write a monolithic test.

class Monolithic(TestCase):
  def step1(self):

  def step2(self):

  def _steps(self):
    for name in sorted(dir(self)):
      if name.startswith("step"):
        yield name, getattr(self, name) 

  def test_steps(self):
    for name, step in self._steps():
      except Exception as e:
        self.fail("{} failed ({}: {})".format(step, type(e), e))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download