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