在test1.py
中,我有以下代码
@pytest.fixture(scope="session")
def moduleSetup(request):
module_setup = Module_Setup()
request.addfinalizer(module_setup.teardown())
return module_setup
def test_1(moduleSetup):
print moduleSetup
print '...'
#assert 0
# def test_2(moduleSetup):
# print moduleSetup
# print '...'
# #assert 0
在conftest.py
中,我有
class Module_Setup:
def __init__(self):
self.driver = webdriver.Firefox()
def teardown(self):
self.driver.close()
当我运行时,它启动并关闭浏览器。
但我也得到错误self = <CallInfo when='teardown' exception: 'NoneType' object is not callable>, func = <function <lambda> at 0x104580488>, when = 'teardown'
此外,如果我想用相同的驱动程序对象运行测试test_1
和test_2
,我需要使用作用域module
还是session
?
关于异常
使用request.addfinalizer()
时,应传递对函数的引用。
您的代码正在传递调用该函数的结果。
request.addfinalizer(module_setup.teardown())
你应该这样称呼它:
request.addfinalizer(module_setup.teardown)
关于夹具范围
如果您的fixture允许在多个测试调用中重用,请使用"session"
范围如果只允许对一个模块中的测试进行重用,请使用"module"
作用域。
替代夹具解决方案
您使用fixture的方式不太符合pytest
风格,它更像是unittest。
从你展示的代码来看,你唯一需要的就是运行Firefox,驱动程序允许你在测试中使用它,完成后,你需要关闭它。
这可以通过单个夹具完成:
@pytest.fixture(scope="session")
def firefox(request):
driver = webdriver.Firefox()
def fin():
driver.close()
request.addfinalizer(fin)
或者使用@pytest.yield_fixture
更好
@pytest.yield_fixture(scope="session")
def firefox(request):
driver = webdriver.Firefox()
yield driver
driver.close()
yield
是fixture停止执行的地方,为测试用例生成创建的值(驱动程序)。
测试结束后(或者更好的是,当我们的夹具范围结束时)继续按照yield
运行指令并执行清理工作
在所有情况下,您都可以按照以下方式修改您的测试用例:
def test_1(firefox):
print moduleSetup
print '...'
并且CCD_ 15固定装置变得完全废弃。