简体   繁体   中英

Python instrumentation for unittests or pytest

My goal is to alter every test that runs in my virtualenv, to first print("Start test") and once the test is done to print("End of test").

For Example:

def test_numpy_func1():
    print("Start test")
    method_to_test.run()
    print("End test")

My problem is that I need to perform this task for every test that pytest or unittest executes (manual insertion is not an option).

Is there any specific method inside unittest that I can modify in order to achieve my goal? Im open to suggestion.

Thanks in advance for all the helpers

A simple decorator would suffice, though this kind of feature is something the test runner should provide. (The decorator is much easier to define than a custom test runner, though.)

from functools import wraps


def start_stop_logging(f):
    @wraps(f)
    def _(*args, **kwargs):
        print("Start test")
        f(*args, **kwargs)
        print("End test")
    return _

@start_stop_logging
def test_numpy_func1():
    method_to_test.run()

Better solutions would probably be specific to a particular test framework.

Eventually, for pytest I added a conftest.py file and override the pytest_runtest_setup() and pytest_runtest_teardown() functions. For unittest, search for run() function in case.py and you will see the usage of setup() or teardown() for each test, so you could add anything you want before or after calling those functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM