pytest自定义命令行参数


1. 功能说明

有一个测试方法:

def test_train(framework):
    print(framework)
    assert framework == 'gbm'

希望该方法的framework的值可以通过 pytest的参数传递过来,比如:

pytest --framework=deeptables

2. 实现方法

自定义一个叫framework的fixture,它的值从命令行中读取,然后再把fixture 注入到测试方法中。

2.1. 自定义fixture

创建pytest配置文件conftest.py,内容如下:

# -*- encoding: utf-8 -*-
import pytest

def pytest_addoption(parser):
    parser.addoption("--framework", action="store", default="deeptables",
                     help="one of: deeptables, gbm")

@pytest.fixture
def framework(request):
    return request.config.getoption("--framework")

2.2. 编写测试方法,使用fixture

def test_train(framework):
    print(framework)
    assert framework == 'gbm'

2.3. 运行

pytest  --framework=xyz

输出:

framework = 'xyz'

    def test_train(framework):
        print(framework)
>       assert framework == 'gbm'
E       AssertionError: assert 'xyz' == 'gbm'

test/test_custom_option.py:8: AssertionError

Assertion failed

Assertion failed


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM