Python 使用标记和文本固定装置选项时,无法从命令行运行py.test

Python 使用标记和文本固定装置选项时,无法从命令行运行py.test,python,pytest,Python,Pytest,我这样设置夹具: def pytest_addoption(parser): parser.addoption('--env', action='store', default='qa', help='Specify environment: "qa", "aws", "prod".') @pytest.fixture(scope='module') def testenv(request): return request.confi

我这样设置夹具:

def pytest_addoption(parser):
    parser.addoption('--env', action='store', default='qa', 
                     help='Specify environment: "qa", "aws", "prod".')

@pytest.fixture(scope='module')
def testenv(request):
    return request.config.getoption('--env')
当我对一个文件名调用py.test时,这就起作用了,例如:

  • py.test-v--env prod functionaltests/test_health_apps.py
但当我使用标记调用py.test时,它不起作用,如下所示:

  • py.test-m硒-环境产品
  • py.test-m‘硒’——环境产品
  • py.test——环境产品-m硒
  • py.test—环境产品-m'硒'
这些回报:

用法:py.test[options][file_或_dir][file_或_dir][…]

py.test:错误:没有这样的选项:--env


标记和命令行选项不兼容吗?

它们是兼容的。我猜您的配置文件(
conftest.py
)与启动测试的目录不在同一目录中。(我可能错了)

我的建议是为配置创建单独的文件:

#configs.py
def pytest_addoption(parser):
    parser.addoption('--env', 
    dest='testenv',
    choices=["qa","aws","prod"],
    default='qa', 
    help='Specify environment: "qa", "aws", "prod".')

@pytest.fixture(scope='session')
def testenv(request):
    return request.config.option.testenv
并创建将用作
py.test
命令的
runner.py

#runner.py
import pytest
import sys
import configs

def main():    
    plgns = [configs]
    pytest.main(sys.argv[1:], plugins=plgns)

if __name__=="__main__":
    main()
然后您可以从
python runner.py--env prod-m selenium


这对我来说非常有效。

谢谢Alex,这成功了。conftest.py与测试文件位于同一目录中;不过,我将runner.py放在根目录中,这样就可以避免将其路径用于命令行指令。