简体   繁体   中英

How can I define a setup and tear down for all tests inside a module

I'm using nosetest as my testing framework, and all of my tests are functions.
The test functions aren't inside a class.

I don't won't to decorate each function with with setup, instead I wish to define a setup & teardown function that will be written once and operate before and after every test in the module.

Does anyone knows of an elegant way to to this?

This is the default behavior of unittest :

test.py:
import unittest

class TestFixture(unittest.TestCase):
    def setUp(self):
        print "setting up"

    def tearDown(self):
        print "tearing down"

    def test_sample1(self):
        print "test1"

    def test_sample2(self):
        print "test2"

Here is what is does:

    $ python -m unittest test
    setting up
    test1
    tearing down
    .setting up
    test2
    tearing down
    .
    ----------------------------------------------------------------------
    Ran 2 tests in 0.000s

    OK

This may not be elegant but it will get the job done. First, in the package where your tests are defined, write to a decorators.py file:

def setup_func():
    "set up test fixtures"

def teardown_func():
    "tear down test fixtures"

Then, in a tests.py file, import the following:

from decorators import setup_func, teardown_func
from inspect import getmodule
from nose.tools import with_setup
from types import FunctionType

From here you can define all of your tests as usual. When you're done, at the very bottom of the file, write in:

for k, v in globals().items():
    if isinstance(v, FunctionType) and getmodule(v).__name__ == __name__:
        v = with_setup(setup_func, teardown_func)(v)

This will decorate every function defined in tests.py (and not the imported functions) with the setup and teardown procedures.

An important note though is that even functions that don't match nose 's criteria for a test will be decorated. So helper and utility functions will be decorated as well as the rest of your functions. In the vast majority of situations this will be a fairly safe operation. However, if you're concerned about it somehow mucking up your actual tests, you can define them in another module and import them in.

Edit: So this all works, and it fits the very narrow solution set you're looking for. No classes, per function decoration, no manual @with_setup decoration, etc. However, I highly suggest that you just move your test functions into a TestCase . It's painless, it's portable, and it's the standard way of grouping tests that have identical setups and teardowns.

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