specifying fixture argument for py.test from command line
我想将命令行参数传递给py.test来创建夹具。例如,我想将数据库主机名传递给下面的夹具??创建,因此它不会被硬编码:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
不幸的是,如果在命令行中省略了参数,则不会设置默认值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | $ 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' |
我想念什么? ...顺便说一句,在命令行上指定主机名也会失败:
1 2 3 4 | $ 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!
文件的布局是什么?似乎您正在尝试将所有这些代码放入test_opt.py模块中。但是
通常,虽然可以在测试模块中定义固定装置,但是任何挂钩都需要放置在conftest.py文件中,以便py.test使用它们。