可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
My Python version is 2.6.
I would like execute the setUp method only once since I'm doing there things which are needed for every test.
My idea was to create a boolean var which will be set to 'true' after the first execution.
The output:
False True --- Test 1 --- False True --- Test 2 ---
why is this not working? Did I missed something?
回答1:
You can use setUpClass
to define methods that only run once per testsuite.
回答2:
Daniel's answer is correct, but here is an example to avoid some common mistakes I found, such as not calling super()
in setUpClass()
.
The documentation for setUpClass()
doesn't mention that you need to call super()
. You will get an error if you don't, as seen in this related question.
class SomeTest(TestCase): def setUp(self): self.user1 = UserProfile.objects.create_user(resource=SomeTest.the_resource) @classmethod def setUpClass(cls): """ get_some_resource() is slow, to avoid calling it for each test use setUpClass() and store the result as class variable """ super(SomeTest, cls).setUpClass() cls.the_resource = get_some_resource()
回答3:
Don't try to dedupe the calls to setUp, just call it once.
For example:
class MyClass(object): ... def _set_up(): code to do one-time setup _set_up()
This will call _set_up() when the module's first loaded. I've defined it to be a module-level function, but you could equally make it a class method of MyClass.
回答4:
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.
回答5:
setup_done is a class variable, not an instance variable.
You are referencing it as an instance variable:
self.setup_done
But you need to reference it as a class variable:
mySelTest.setup_done
Here's the corrected code:
class mySelTest(unittest.TestCase): setup_done = False def setUp(self): print str(mySelTest.setup_done) if mySelTest.setup_done: return mySelTest.setup_done = True print str(mySelTest.setup_done)