1. 程式人生 > 其它 >pytest - 自定義引數

pytest - 自定義引數

conftest.py: 檔名字固定寫法,自定義命令列引數資訊

import pytest

hosts = {
    "dev": "http://dev.xxxx.com",
    "test": "http://test.xxxx.com",
    "uat": "http://uat.xxxx.com",
    "prod": "http://prod.xxxx.com",
}


# 自定義引數
def pytest_addoption(parser):
    parser.addoption("--host",
                     action="store",
                     default="test",
                     choices=["dev", "test", "uat", "prod"],
                     help="""
                        dev:表示開發環境,
                        test:表示測試環境
                        uat:表示功能測試環境
                        prod:表示生產環境
                        default:測試環境
                     """)


@pytest.fixture(scope="session")
def get_cmdopts(pytestconfig):  # 方法名字可以隨便寫,但是需要與測試用例使用的地方保持一致
    if hosts.get(pytestconfig.getoption("--host")):
        return hosts.get(pytestconfig.getoption("--host"))


# # fixture 寫法二:
# @pytest.fixture(scope="session")
# def get_cmdopts(request):  # request 引數名字固定寫法
#     if hosts.get(request.config.getoption("--host")):
#         return hosts.get(request.config.getoption("--host"))

test_addoption.py: 測試用例檔案,使用命令列中的引數

import pytest

def test_option(get_cmdopts):  # get_cmdopts: 名字要與conftest.py中用fixture標記的方法保持一致
    print(get_cmdopts)

命令列指定引數值:

--host 的預設值: