Run setUp only once for a set of automated tests

前端 未结 8 1248
逝去的感伤
逝去的感伤 2020-12-13 05:15

My Python version is 2.6.

I would like to execute the test setUp method only once since I do things there which are needed for all tests.

My idea was to crea

8条回答
  •  情深已故
    2020-12-13 06:07

    Place all code you want set up once outside the mySelTest.

    setup_done = False
    
    class mySelTest(unittest.TestCase):
    
        def setUp(self):
            print str(setup_done)
    
            if setup_done:
                return
    
            setup_done = True
            print str(setup_done)
    

    Another possibility is having a Singleton class that you instantiate in setUp(), which will only run the __new__ code once and return the object instance for the rest of the calls. See: Is there a simple, elegant way to define singletons?

    class Singleton(object):
        _instance = None
        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Singleton, cls).__new__(
                                cls, *args, **kwargs)
                # PUT YOUR SETUP ONCE CODE HERE!
                cls.setUpBool = True
    
            return cls._instance
    
    class mySelTest(unittest.TestCase):
    
        def setUp(self):
            # The first call initializes singleton, ever additional call returns the instantiated reference.
            print(Singleton().setUpBool)
    

    Your way works too though.

提交回复
热议问题