學(xué)習(xí)筆記-Pytest(七)命令行傳參

1. 前言


命令行參數(shù)是根據(jù)命令行選項(xiàng)將不同的值傳遞給測試函數(shù),比如平常在cmd執(zhí)行”pytest —html=report.html”,這里面的”—html=report.html“就是從命令行傳入的參數(shù)
對應(yīng)的參數(shù)名稱是html,參數(shù)值是report.html

2.contetest配置參數(shù)


1.首先需要在contetest.py添加命令行選項(xiàng),命令行傳入?yún)?shù)”—cmdopt“, 用例如果需要用到從命令行傳入的參數(shù),就調(diào)用cmdopt函數(shù):

# content of conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption(
        "--cmdopt", action="store", default="type1", help="my option: type1 or type2"
    )

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

2.測試用例編寫案例

# content of test_sample.py
import pytest
def test_answer(cmdopt):
    if cmdopt == "type1":
        print("first")
    elif cmdopt == "type2":
        print("second")
    assert 0  # to see what was printed

if __name__ == "__main__":
    pytest.main(["-s", "test_case1.py"])

運(yùn)行結(jié)果:

>pytest -s
============================= test session starts =============================
test_sample.py first
F

================================== FAILURES ===================================
_________________________________ test_answer _________________________________

cmdopt = 'type1'

    def test_answer(cmdopt):
        if cmdopt == "type1":
            print("first")
        elif cmdopt == "type2":
            print("second")
>       assert 0  # to see what was printed
E       assert 0

test_case1.py:8: AssertionError
========================== 1 failed in 0.05 seconds ===========================

3. 帶參數(shù)啟動


1.如果不帶參數(shù)執(zhí)行,那么傳默認(rèn)的default=”type1”,接下來在命令行帶上參數(shù)去執(zhí)行

$ pytest -s test_sample.py --cmdopt=type2
test_sample.py second
F

================================== FAILURES ===================================
_________________________________ test_answer _________________________________

cmdopt = 'type2'

    def test_answer(cmdopt):
        if cmdopt == "type1":
            print("first")
        elif cmdopt == "type2":
            print("second")
>       assert 0  # to see what was printed
E       assert 0

test_case1.py:8: AssertionError
========================== 1 failed in 0.05 seconds ===========================
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,721評論 0 5
  • Pytest 是一個比較成熟且功能完備的 Python 測試框架。其提供完善的在線文檔,并有著大量的第三方插件和內(nèi)...
    派派森森閱讀 4,465評論 0 12
  • 目錄: 安裝及入門 使用和調(diào)用方法 原有TestSuite使用方法 斷言的編寫和報(bào)告 Pytest fixture...
    韓志超閱讀 11,857評論 0 10
  • 寫在前面的話 代碼中的# > 表示的是輸出結(jié)果 輸入 使用input()函數(shù) 用法 注意input函數(shù)輸出的均是字...
    FlyingLittlePG閱讀 3,230評論 0 9
  • 布滿爬山虎的破舊樓房隱匿在這個學(xué)校后山的山腳,人跡罕至。偶爾有幾個學(xué)生閑暇無事打著“捉鬼”的旗號聚眾來踩踏長勢茂盛...
    周兌兌閱讀 291評論 0 0

友情鏈接更多精彩內(nèi)容