學習筆記-Pytest(七)命令行傳參

1. 前言


命令行參數是根據命令行選項將不同的值傳遞給測試函數,比如平常在cmd執行”pytest —html=report.html”,這里面的”—html=report.html“就是從命令行傳入的參數
對應的參數名稱是html,參數值是report.html

2.contetest配置參數


1.首先需要在contetest.py添加命令行選項,命令行傳入參數”—cmdopt“, 用例如果需要用到從命令行傳入的參數,就調用cmdopt函數:

# 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"])

運行結果:

>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. 帶參數啟動


1.如果不帶參數執行,那么傳默認的default=”type1”,接下來在命令行帶上參數去執行

$ 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 ===========================
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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