从命令行指定 py.test 的 fixture 参数

6

我希望能够在运行py.test时传递命令行参数以进行夹具创建。例如,我想要在下面创建夹具时传递数据库主机名,这样它就不是硬编码的:

import pytest

def pytest_addoption(parser):
    parser.addoption("--hostname", action="store", default='127.0.0.1', help="specify IP of test host")

@pytest.fixture(scope='module')
def db(request):
    return 'CONNECTED TO [' + request.config.getoption('--hostname') + '] SUCCESSFULLY!'

def test_1(db):
    print db
    assert 0

很遗憾,默认值未设置,如果从命令行中省略了参数:

$ py.test test_opt.py
=================================================================== test session starts ====================================================================
platform linux2 -- Python 2.7.5 -- pytest-2.3.5
collected 1 items

test_opt.py E

========================================================================== ERRORS ==========================================================================
_________________________________________________________________ ERROR at setup of test_1 _________________________________________________________________

request = <FixtureRequest for <Module 'test_opt.py'>>

    @pytest.fixture(scope='module')
    def db(request):
>       return 'CONNECTED TO [' + request.config.getoption('--hostname') + '] SUCCESSFULLY!'

test_opt.py:8:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <_pytest.config.Config object at 0x220c4d0>, name = '--hostname'

    def getoption(self, name):
        """ return command line option value.

            :arg name: name of the option.  You may also specify
                the literal ``--OPT`` option instead of the "dest" option name.
            """
        name = self._opt2dest.get(name, name)
        try:
            return getattr(self.option, name)
        except AttributeError:
>           raise ValueError("no option named %r" % (name,))
E           ValueError: no option named '--hostname'

我有什么遗漏的吗? ... 另外,在命令行上指定主机名也失败了:
$ py.test --hostname=192.168.0.1 test_opt.py
Usage: py.test [options] [file_or_dir] [file_or_dir] [...]

py.test: error: no such option: --hostname

TIA!

1个回答

13
您的文件布局是什么?看起来您正在尝试将所有这些代码放在 test_opt.py 模块中。然而,pytest_addoption() 钩子只会从 conftest.py 文件中读取。因此,您应该尝试将 pytest_addoption() 函数移动到与 test_opt.py 相同目录下的 conftest.py 文件中。
通常情况下,虽然 fixture 可以在测试模块中定义,但任何钩子都需要放置在 conftest.py 文件中供 py.test 使用。

是的,我正在尝试把所有东西都放在一个文件里。我会尝试分割它看看会发生什么。...我没有意识到conftest.py必须是一个单独的文件。...谢谢! - Trevor
1
那就是问题所在!我把除了实际测试函数test_1(db)之外的所有内容都移动到相邻的conftest.py文件中,然后一切顺利! - Trevor
钩子只能从conftest.py文件中读取。 - Tyathalae

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