pytest.fixture 函数不能使用 ``yield``。而是编写 return 一个内部 function/generator 并让消费者调用并迭代它。:

pytest.fixture functions cannot use ``yield``. Instead write and return an inner function/generator and let the consumer call and iterate over it.:

我正在尝试 运行 selenium 和 pytest 用于我的 Django 项目并执行 fixture setup/teardown。

我尝试使用 yield 来遵循最好的 practice,但我收到一个错误:

--- ERROR at setup of test_browsing_check --- 
pytest.fixture functions cannot use ``yield``. Instead write and return an inner function/generator and let the consumer call and iterate over it.:

@pytest.fixture(scope="module")
def browser(request):
    selenium = webdriver.Firefox()
    selenium .implicitly_wait(3)
    yield selenium
    selenium.quit()

你知道为什么它不起作用吗?

后来我用了另一个很好用的代码

@pytest.fixture(scope="module")
def browser(request):
    selenium = webdriver.Firefox()
    selenium.implicitly_wait(3)
    def teardown():
        selenium.quit()
    request.addfinalizer(teardown)
    return selenium

但是不推荐这种方法:

This method is still fully supported, but yield is recommended from 2.10 onward because it is considered simpler and better describes the natural code flow.

关于版本的注意事项:

$ python -V
$ Python 3.5.2 :: Anaconda 4.2.0 (64-bit)

$ django-admin version
$ 1.10.3

$ pip show pytest
$ Name: pytest
$ Version: 2.9.2

根据文档:在 2.10 版之前,为了使用 yield 语句执行拆卸代码 必须使用 yield_fixture 标记来标记固定装置。 从 2.10 开始,普通的 fixtures 可以直接使用 yield,因此不再需要 yield_fixture 装饰器并被视为弃用。