pytest

pytest安装

pip install pytest

测试文件

  • test_*.py
  • *_test.py

用例识别

  • Test类包含的所有test_的方法(测试类不能带有__init__方法)
  • 不在class中的所有的test_*方法
  • pytest也可以执行unittest框架写的用例与方法

测试用例的识别与运行

  • pytest -v (最高级别信息)打印详细运行日志信息
  • pytest -v -s 文件名 (s时代控制台输出结构,也是输出详细)
  • pytest 文件名.py 执行单独一个pytest模块
  • pytest 文件名.py::类名 运行某个模块里面的某个类
  • pytest 文件名.py::类名::方法名 运行某个模块里面某个类里面的方法
  • pytest -v -k “类名 and not 方法名” 跳过运行某个用例
  • pytest -x 文件名 一旦运行到报错就停止运行
  • pytest -m [标记名] @pytest.mark.[标记名]将运行有这个标记的测试用例
  • pytest --maxfail=[num] 当运行到错误达到num的时候停止运行

pytest框架结构

  • 模块级(setup_module/teardown_module)模块始末,全局(优先级最高)
  • 函数级(setup_function/teardown_function)只对函数用例生效(不在类中)
  • 类级(setup_class/teardown_class)只在类中前后运行一次(在类中)
  • 方法级(setup_method/teardown_method)开始于方法始末(在类中)
  • 类里面(setup/teardown)运行再调用方法的前后

@pytest.fixture()

  • 场景:测试执行时有些需要登录,有些不需要登录。setup/teardown无法满足,使用fixture可以
  • 步骤:
  1. 导入pytest
  2. 在登录的函数上加上@pytest.fixture()
  3. 在要使用的测试方法中传入(登录函数名称),就先登录
  4. 不传入的就不登录直接执行测试方法

@pytest.mark.parametrize()

  • 场景:参数化
  • 步骤:
    在要参数化方法上加上@pytest.mark.parametrize(args_name,args_value)
    args_name:参数名,字符串,多个参数中间用逗号隔开
    args_value:参数值(列表,元组,字典列表,字典元组),有多个值用例就会执行多少次
posted @ 2022-07-14 15:25  红烧鱼块  阅读(55)  评论(0)    收藏  举报