How to run initialization code before testing when using the Uittest module for Python as a tester?

How can a library user run their own initialization code (for example, set logging debug levels) before running the tests that come with the library? The Python unittest module is used as a tester.

+5
source share
3 answers

You can try using pytest to run unittests. If this works (a lot of unittest-based test suites work), you can create a small module, for example "mymod.py", which defines the pytest configuration hook:

 # content of mymod.py def pytest_configure(): import logging logging.getLogger().setLevel(logging.WARN) 

If you now do py.test as follows:

 $ py.test -p mymmod --pyargs mylib 

The "mylib" package will then search for tests and the logging level will be changed before running them. The -p option tells the plugin to load, and -pyargs tells pytest to try to import the arguments first, rather than treat them as directory or file names (by default).

For more information: http://pytest.org and http://pytest.org/latest/unittest.html

NTN, Holger

+2
source

You can configure before calling unittest.main .

Or you can subclass the test suite and run the class level setup method .

Or you can set up a test setup with a callback to a custom setup method.

+1
source

The answer from a similar question is more useful here:

How to run specific code before and after each unit test in Python

I used the python setUpClass method https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUpClass

 setUpClass() A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod(): @classmethod def setUpClass(cls): ... 

I run my tests like this:

 python -m unittest discover -v 
0
source

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


All Articles