Ignore unittests that depend on the success of other tests

When writing unit tests, it often happens that some tests "depend" on other tests.

For example, let's say I have a test that checks if I can instantiate a class. I have other tests that go straight ahead and create it, and then test other functions.

Let's also assume that a class cannot for any reason instantiate.

The result is a ton of tests that give errors. This is bad because I don’t see where the problem really is. I need a way to skip these tests if my instance test failed.

Is there a way to do this with the Python unittest module?

If this is not what I should do, what should I do to see where the problem really is when something breaks?

+4
source share
2 answers

Actually, contrary to my comment above, I think you need the setUpClass method. From the docs ,

If an exception occurs during setUpClass, tests in the class do not run, and tearDownClass does not start. [...] If the exception is a SkipTest exception, then the class will be declared as skipped instead of an error.

So something like this should work (I'm sure it could be more neat):

 class TestMyClass(unittest.TestCase): @classmethod def setUpClass(cls): # run the constructor test if constructor_test_failed: raise unittest.SkipTest("Constructor failed") def test_other_stuff(self): # will get run after setUpClass if it succeeded 
+2
source

I have no suggestions on how to avoid running "dependent" tests, but I have a suggestion on how you better live with them: make the dependencies more obvious and, therefore, simplify the analysis of test failures later. One simple possibility is as follows:

  • In the test code, you place tests for the low-level aspects at the top of the file, and more dependent tests at the bottom. Then, when several tests fail, first look at the test that is closest to the top of the file.
0
source

Source: https://habr.com/ru/post/1482832/


All Articles