pytest: 将fixture作为函数参数

4
正如其文档所述,pytest将夹具作为函数参数接受。然而,这与几乎所有语言中的约定相矛盾,即参数名称不应影响函数的行为。例如:

以下代码可行:

import pytest

@pytest.fixture()
def name():
    return 'foo'

def test_me(name):
    assert name == 'foo'

但这个不行:
import pytest

@pytest.fixture()
def name():
    return 'foo'

def test_me(nam):
    assert nam == 'foo'

我认为在这里需要一些反思,需要测试函数参数是否有效。我的理解正确吗?


除了固定装置之外,还有其他使我感到困惑的神奇参数名称。其中之一是request

import pytest

@pytest.fixture(params=['foo', 'bar'])
def name(request):
    return request.param

def test_me(name):
    assert name == 'foo'

在不阅读文档的情况下,你可能会认为可以将request重命名为其他名称,例如req:

import pytest

@pytest.fixture(params=['foo', 'bar'])
def name(req):
    return req.param

def test_me(name):
    assert name == 'foo'

但是运行测试时会报错,提示找不到fixture req。更令我困惑的是,列出的可用fixtures中并没有包括request。我不确定在这里是否适合称request为fixture,但错误信息却自相矛盾:

E fixture 'req' not found

> available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, name, pytestconfig, record_xml_attribute, record_xml_property, recwarn, tmpdir, tmpdir_factory, worker_id

> use 'pytest --fixtures [testpath]' for help on them.

那么当我使用pytest时,有多少像这样的magic names需要注意,以免陷入陷阱?


对于第二段代码片段,您必须发送使用fixture装饰器的函数。 - Asif Mohammed
1个回答

5
是的,Py.test注入了一些参数名称内省魔法来使您的测试用例简洁。
除了您可用的所有固定装置(正如您使用pytest --fixtures发现的那样),我确实认为request是唯一的附加魔术参数(除非您使用,例如@ pytest.mark.parametrize('foo',(...)),在这种情况下,foo是标记测试用例或装置的魔术参数等)。
另外,我认为最好不要将Py.test test_函数视为常规函数,因为它们不会直接被Py.test调用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接