Python 如何为所有鼻测试定义一个设置功能?
我正在使用googleappengine和python,并希望使用notest运行一些测试。 我希望每个测试运行相同的设置功能。我已经有很多测试了,所以我不想把它们全部检查一遍,然后复制粘贴相同的函数。我可以在某个地方定义一个设置函数,并且每个测试都会首先运行它吗Python 如何为所有鼻测试定义一个设置功能?,python,nosetests,Python,Nosetests,我正在使用googleappengine和python,并希望使用notest运行一些测试。 我希望每个测试运行相同的设置功能。我已经有很多测试了,所以我不想把它们全部检查一遍,然后复制粘贴相同的函数。我可以在某个地方定义一个设置函数,并且每个测试都会首先运行它吗 谢谢。您可以编写设置函数,并使用with\u setup装饰器应用它: from nose.tools import with_setup def my_setup(): ... @with_setup(my_setup
谢谢。您可以编写设置函数,并使用
with\u setup
装饰器应用它:
from nose.tools import with_setup
def my_setup():
...
@with_setup(my_setup)
def test_one():
...
@with_setup(my_setup)
def test_two():
...
def my_setup(self):
#do the setup for the test-case
def apply_setup(setup_func):
def wrap(cls):
cls.setup = setup_func
return cls
return wrap
@apply_setup(my_setup)
class MyTestCaseOne(unittest.TestCase):
def test_one(self):
...
def test_two(self):
...
@apply_setup(my_setup)
class MyTestCaseTwo(unittest.TestCase):
def test_one(self):
...
如果您想对多个测试用例使用相同的设置,可以使用类似的方法。
首先创建setup函数,然后使用decorator将其应用于所有测试用例:
from nose.tools import with_setup
def my_setup():
...
@with_setup(my_setup)
def test_one():
...
@with_setup(my_setup)
def test_two():
...
def my_setup(self):
#do the setup for the test-case
def apply_setup(setup_func):
def wrap(cls):
cls.setup = setup_func
return cls
return wrap
@apply_setup(my_setup)
class MyTestCaseOne(unittest.TestCase):
def test_one(self):
...
def test_two(self):
...
@apply_setup(my_setup)
class MyTestCaseTwo(unittest.TestCase):
def test_one(self):
...
或者,另一种方法可以是简单地分配设置:
class MyTestCaseOne(unittest.TestCase):
setup = my_setup
您好,谢谢您的回答,但这不仅仅是复制函数。我不能在每次测试之前告诉nosetests每次运行哪个设置函数吗?这怎么可能是更多的工作呢?复制函数需要每个测试至少3-4行代码,此解决方案每个测试只需要多1行代码。你的考试是如何组织的?它们在
TestCase
s内部,或者它们只是函数?它们在TestCase内部。但我在项目中已经有很多测试文件,到目前为止,我一直在使用gaeunit进行测试。我想使用nosetest,但我想在每次测试之前初始化我的db存根。也许现在我能更好地解释自己。gaeunit自己处理这个问题,在每次测试之前清除db。现在我想鼻子做同样的事情,我能做到吗?到目前为止,无法在internet上找到解决方案。我认为没有此选项。您有包/模块/类和测试级装置,但没有“全局装置”这样的东西。无论如何,你可以利用我的解决方案。创建安装程序和装饰程序,然后将其应用于所有测试用例。我现在正在更新我的答案。解决方案很好,但我必须在测试类中显式调用my_setup
,以触发设置内容。仅放置装饰器不会调用my\u setup
。我所做的是从测试类内部的setup(self)
调用my\u setup
。