How to run initialization code before tests when using Python's unittest module as a testrunner?

前端 未结 3 824
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 06:54

How can a user of a library run his own initialization code (setting debug levels of loggers for example) before running tests supplied with the library? Python\'s uni

相关标签:
3条回答
  • 2021-01-18 07:27

    You could do the set-up work before calling unittest.main.

    Or you could subclass the test suite and run a class-level setup method.

    Or you could have the test setup incorporate a callback to a user-defined setup method.

    0 讨论(0)
  • 2021-01-18 07:40

    You can try using pytest to run the unittests. If that works (many unittest based test suites work), then you can create a little module, for example "mymod.py", defining a pytest configuration hook:

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

    If you now execute py.test like this:

    $ py.test -p mymmod --pyargs mylib
    

    Then the "mylib" package will be searched for tests and ahead of running them the logging level is modified. The "-p" option specifies a plugin to load and the "--pyargs" tells pytest to try importing the arguments first, instead of treating them as directory or file names (the default).

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

    HTH, holger

    0 讨论(0)
  • 2021-01-18 07:43

    Answer from similar question is more helpful here:

    How to a run a specific code before & after each unit test in python

    I used 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 讨论(0)
提交回复
热议问题