Is it possible to assert tearDown in the unittest method?

I have TestCase with several tests and you need to state several conditions (the same for each test) at the end of each test. Is it possible to add these statements to the tearDown() method, or is it a bad habit, since they do not "clean" anything?

What will be the correct way?

+5
source share
2 answers

tearDown something in your tearDown means that you need to be careful that all cleanup is done before the actual statement, otherwise the cleanup code cannot be called if the assert statement fails and raises.

If the statement is only one line, it might be OK to have it in each test method, if it is more than the one that has a particular method, it would be possible - this method should not be a test of its own, that is, not recognized as a test your test environment. Using a method decorator or class decorator can also be an alternative.

The whole idea is that tearDown should not run any tests, and explicit is better than implicit.

+3
source

Mmh, I've never seen this before. Personally, I would not do this, because he does not belong there. I would do this through a decorator who ultimately claims you. Then simply decorate the test functions you want to have these statements.

For a great introduction to python decorators see answers to this question

+1
source

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


All Articles