所在位置:首页 → 软件测试 → 测试框架 → Pytest测试框架之基础用法(规则,断言,前置后置,跳过,配置,运行,日志,报告)

Pytest测试框架之基础用法(规则,断言,前置后置,跳过,配置,运行,日志,报告)

发布: 更新时间:2022-09-06 22:50:17

安装库:pip install pytest

pytest相关插件:(了解)

  • 失败重跑 pytest-rerunfailures
  • 多重校验 pytest-assume
  • 设定执行顺序 pytest-ordering
  • 用例依赖 pytest-dependency
  • 分布式测试 pytest-xdist
  • 生成报告 pytest-html

完美报告:allure-pytest插件,allure报告插件(重点)

一、默认规则

  • 模块名必须以test_开头或者_test结尾
  • 类名必须以Test开头
  • 测试方法必须以test开头
pytest命名规则

二、断言

示例:assert "a" in "abc"

pytest常用断言

三、前置、后置方法

描述前置后置
模块级,开始于模块始末,全局setup_moduleteardown_module
函数级,只用函数用例生效(不在类中的)setup_functionteardown_function
类级,只在类中前后运行一次(在类中)setup_classteardown_class
方法级,每个方法用例前后执行(在类中)setup_methodteardown_method
pytest的前置、后置方法
示例:pytest类方法的前置方法使用

四、跳过执行

测试用例或测试类前加skip装饰器,可跳过执行

@pytest.mark.skip

@pytest.mark.skipif() #满足条件才跳过
示例:pytest使用skip装饰器跳过执行

五、pytest.ini配置文件

不论是主函数模式还是命令行模式都会优先读取这个配置文件来执行命令。

[pytest]
# 命令行参数,用空格分隔
addopts = -vs
# 定义标签
markers= p0:高优先级
         p1:中优先级
# 测试用例文件夹,可以自己配置
testpaths = ./test_demo
# 配置测试搜索的模块文件名称
python_files = test*.py
# 配置测试搜索的类名
python_classes = test*
# 配置搜索的函数名
python_functions = test

六、Pytest运行方式

主函数模式

import pytest
 
if __name__ == '__main__':
    pytest.main()  #运行所有的用例

# 指定模块运行
pytest.main(['-vs', 'test_login.py'])

# 指定目录
pytest.main(['-vs','./interface_testcase'])

# 通过nodeid指定用例运行:nodeid由模块名,分隔符,类名,方法名,函数名 组成,比如:
pytest.main(['-vs','./interface_testcase/test_interface.py::test_04_func'])
pytest.main(['-vs','./interface_testcase/test_interface.py::TestInterface::test_04_func'])

命令行模式

# 运行所有的用例:
pytest

# 指定模块运行:
pytest -vs test_login.py

# 指定目录:
pytest -vs ./interface_testcase

# 通过nodeid指定用例运行:nodeid由模块名,分隔符,类名,方法名,函数名 组成
pytest -vs ./interface_testcase/test_interface.py::TestInterface::test_04_func

七、Logging日志模块

[postsbox post_id="2393"]

八、Allure生成测试报告

安装pytest的allure插件:pip install allure-pytest

#执行pytest,生成allure所需要的数据源。--alluredir设置数据源存放目录
pytest --alluredir=./allure-results

# 执行此命令,将在默认浏览器中显示生成的报告
allure serve ./allure-results
标签:, , ,
文章排行