5

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_1test_2使用相同的驱动程序对象,我需要使用范围modulesession

4

1 回答 1

4

关于异常

使用时request.addfinalizer(),您应传递对函数的引用。

您的代码正在传递调用该​​函数的结果。

request.addfinalizer(module_setup.teardown())

你应该这样称呼它:

request.addfinalizer(module_setup.teardown)

关于夹具范围

如果您的夹具允许跨多个测试调用重用,请使用"session" 范围。如果它只允许在一个模块中重用测试,请使用"module"范围。

替代夹具解决方案

您使用固定装置的方式并没有太多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地方,为测试用例产生创建的值(驱动程序)。

测试结束后(或者更好的是,当我们的夹具范围结束时),它继续运行下面的指令yield并进行清理工作。

在所有情况下,您都可以按如下方式修改您的测试用例:

def test_1(firefox):
    print moduleSetup
    print '...'

并且moduleSetup夹具变得完全过时了。

于 2016-05-03T16:40:01.500 回答