Python 为一组自动化测试只运行一次 setUp
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14305941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run setUp only once for a set of automated tests
提问by Kesandal
My Python version is 2.6.
我的 Python 版本是 2.6。
I would like to execute the test setUp method only once since I do things there which are needed for all tests.
我想只执行一次测试 setUp 方法,因为我在那里做所有测试都需要的事情。
My idea was to create a boolean variable which will be set to 'true' after the first execution and then disable more than one call to the setup method.
我的想法是创建一个布尔变量,该变量将在第一次执行后设置为“true”,然后禁用对 setup 方法的多次调用。
class mySelTest(unittest.TestCase):
? ? setup_done = False
? ? def setUp(self):
? ? ? ? print str(self.setup_done)
? ? ? ? ? ??
? ? ? ? if self.setup_done:
? ? ? ? ? ? return
? ? ? ? self.setup_done = True
? ? ? ? print str(self.setup_done)
The output:
输出:
False
True
--- Test 1 ---
False
True
--- Test 2 ---
why is this not working? Did I miss anything?
为什么这不起作用?我错过了什么吗?
回答by Daniel Roseman
You can use setUpClassto define methods that only run once per testsuite.
您可以使用setUpClass定义每个测试套件仅运行一次的方法。
回答by Paul Hankin
Don't try to dedupe the calls to setUp, just call it once.
不要尝试对 setUp 的调用进行重复数据删除,只需调用一次即可。
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.
这将在模块第一次加载时调用 _set_up()。我已将其定义为模块级函数,但您同样可以将其设为 MyClass 的类方法。
回答by NuclearPeon
Place all code you want set up once outside the mySelTest.
将您要设置的所有代码放在 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?
另一种可能性是拥有一个在 中实例化的 Singleton 类setUp(),它只会运行__new__一次代码并为其余的调用返回对象实例。请参阅:是否有一种简单、优雅的方式来定义单例?
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.
不过你的方法也行。
回答by Chemary
Daniel's answeris correct, but here is an example to avoid some common mistakes I found, such as not calling super()in setUpClass()when TestCaseis a subclass of unittest.TestCase(like in django.testor falcon.testing).
丹尼尔的回答是正确的,但在这里是为了避免一些常见的错误,我发现,如不调用一个例子super()中setUpClass(),当TestCase是的子类unittest.TestCase(如在django.test或falcon.testing)。
The documentation for setUpClass()doesn't mention that you need to call super()in such cases. You will get an error if you don't, as seen in this related question.
的文档setUpClass()没有提到您需要super()在这种情况下调用。如果你不这样做,你会得到一个错误,如这个相关问题中所见。
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()
回答by jersey bean
setup_done is a class variable, not an instance variable.
setup_done 是一个类变量,而不是一个实例变量。
You are referencing it as an instance variable:
您将其作为实例变量引用:
self.setup_done
self.setup_done
But you need to reference it as a class variable:
但是您需要将其作为类变量引用:
mySelTest.setup_done
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)
回答by andilabs
If you ended up here because of need to load some data for testing... then as far as you are using Django 1.9+ please go for setUpTestData:
如果您因为需要加载一些数据进行测试而来到这里......那么就您使用的 Django 1.9+ 而言,请选择setUpTestData:
class MyTests(TestCase):
@classmethod
def setUpTestData(cls):
# Set up data for the whole TestCase
cls.foo = Foo.objects.create(bar="Test")
def test1(self):
self.assertEqual(self.foo.bar, 'Test')
回答by Greg Ross
I'm using Python 3 and found that the clsreference is also available in the setupmethod and so the following works:
我正在使用 Python 3,发现cls该setup方法中也提供了该引用,因此以下工作:
class TestThing(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.thing = Thing() # the `thing` is only instantiated once
def setup(self):
self.thing = cls.thing # ...but set on each test case instance
def test_the_thing(self):
self.assertTrue(self.thing is not None)

