pytest自定义命令行参数

实际使用场景:pytest运行用例的时候,启动mitmdump进程试试抓包,pytest命令行启动的时候,传入mitmdump需要的参数(1)抓包生成的文件地址 (2)mitm的proxy设置

python 复制代码
#  在pytest的固定文件中conftest.py中

def pytest_addoption(parser):
    """
    自定义pytest的命令行参数,@pytest.fixture配合下面的方法一起用
    :param parser:
    :return:
    """
    parser.addoption("--mitm_path", action="store",
                     default="",
                     type=str,
                     help="--mitm_path:mitmproxy生成的cvs文件名称")
    parser.addoption("--mitm_proxy", action="store",
                     default="127.0.0.1:8080",
                     type=str,
                     help="--mitm_proxy:mitmproxy设置代理")

@pytest.fixture(scope="session", autouse=True)
def set_env_mitm_path(request):
    """
    将--mitm_path从命令行中获取放入环境变量中,给mitmdump工具用
    :param request:
    :return:
    """
    mitm_value = request.config.getoption("--mitm_path")
    os.environ['mitm_path'] = mitm_value
    print('\n --mitm_path参数值:', mitm_value)
    return mitm_value


@pytest.fixture(scope="session", autouse=True)
def set_env_mitm_proxy(request):
    """
    将--mitm_proxy从命令行中获取放入环境变量中,给mitmdump工具用
    :param request:
    :return:
    """
    mitm_proxy = request.config.getoption("--mitm_proxy")
    os.environ['mitm_proxy'] = mitm_proxy
    print('\n --mitm_proxy参数值:', mitm_proxy)
    return mitm_proxy


@pytest.fixture(scope="session")
def setup_mitmdump():
    """
    pytest启动,cmd启动一个mitmdump的进程
    :return: 
    """
    if not os.environ.get("mitm_path"):
        # 命令行没有传入mitm_path的值,给默认值一个
        caller = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]
        mitm_path = "./testdata/" + caller + ".csv"
        os.environ["mitm_path"] = mitm_path
    cmd = r"mitmdump -p {}".format(os.environ.get("mitm_proxy") if os.environ.get("mitm_proxy") else '8080')
    process = subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE)
    time.sleep(1)
    yield
    time.sleep(6)
    print("stop mitm")
    process.kill()

测试文件

python 复制代码
import csv
import os
import time

import pytest
import requests


class TestDemo:

    @pytest.mark.usefixtures("setup_mitmdump")
    @pytest.mark.parametrize(
        "name,assert_word",
        [
            pytest.param("1", "smart", id="第一个"),
            pytest.param("2", "smart", id="第二个")
        ]
    )
    def test_001(self, name, assert_word):
        print("我是用例test_%s" % name)
        url = "http://httpbin.org/get"
        params = {}
        headers = {"content-type": "application/json; charset=UTF-8"}
        proxies = {'http': 'http://127.0.0.1:%s' % os.environ.get("mitm_proxy")}  # ip地址
        option = requests.get(url=url, headers=headers, params=params, proxies=proxies)
        time.sleep(10)

运行效果

pytest -s test1.py --mitm_path=D:/hf.csv

pytest -s test1.py --mitm_path=D:/hf.csv --mitm_proxy 8989

相关推荐
我的xiaodoujiao2 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 22--数据驱动--参数化处理 Json 文件
python·学习·测试工具·pytest
胜天半月子2 天前
Python自动化测试 | 快速认识并了解pytest的基本使用
服务器·python·pytest
北珣.6 天前
自动化框架pytest基础
自动化·pytest
程序员杰哥7 天前
Pytest之收集用例规则与运行指定用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
学习3人组8 天前
Python + requests + pytest + allure + Jenkins 构建完整的接口自动化测试框架
python·jenkins·pytest
shao91851611 天前
Gradio全解14——使用Gradio构建MCP的服务器与客户端(4)——Python包命令:uv与uvx实战
pytest·uv·1024程序员节·npx·uvx·uv pip·ruff
我的xiaodoujiao12 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest
sky0Lan12 天前
一个类似 pytest 的 html 报告
android·html·pytest
一半烟火以谋生13 天前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
一半烟火以谋生14 天前
pytest conftest.py 使用教程
pytest