一 安装
1.1 安装包安装
1进入下载包路径
2.python setup install
3 安装出现权限问题:
3.1.mac/linux 添加sudo,运行:sudo python setup install
3.2.windows 管理员方式运行cmd窗口,运行:python setup install
1.2 命令行安装
1.mac/linux:sudo pip3 install -U pytest # -U:可以理解为--upgrade,表示已安装就升级为最新版本
2.管理员方式运行cmd:pip3 install -U pytest
1.3 安装成功校验:
1.进入命令行
2.运行:pytest --version # 会展示当前已安装版本
1.4 Pytest运行方式
1.测试类主函数模式
pytest.main("-s test_abc.py")
2.命令行模式
pytest 文件路径/测试文件名
例如:
pytest ./test_abc.py
1.5 例子
file_name: test_abc.py
import pytest # 引入pytest包
def test_a(): # test开头的测试函数
print("------->test_a")
assert 1 # 断言成功
def test_b():
print("------->test_b")
assert 0 # 断言失败
if __name__ == '__main__':
pytest.main("-s test_abc.py") # 调用pytest的main函数执行测试
执行结果:
test_abc.py
------->test_a
. # .(代表成功)
------->test_b
F # F(代表失败)
二 Pytest的setup和teardown函数
1 概述
1.setup和teardown主要分为:模块级,类级,功能级,函数级。
2.存在于测试类内部
2 函数级别setup()/teardown()
运行于测试方法的始末,即:运行一次测试函数会运行一次setup和teardown
代码示例:
import pytest
class Test_ABC:
# 函数级开始
def setup(self):
print("------->setup_method")
# 函数级结束
def teardown(self):
print("------,->teardown_method")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
if __name__ == '__main__':
pytest.main("-s test_abc.py")
执行结果:
------->setup_method # 第一次 setup()
------->test_a
.
------->teardown_method # 第一次 teardown()
------->setup_method # 第二次 setup()
------->test_b
.
------->teardown_method # 第二次 teardown()
3 类级别
运行于测试类的始末,即:在一个测试内只运行一次setup_class和teardown_class,不关心测试类内有多少个测试函数。
代码示例:
import pytest
class Test_ABC:
# 测试类级开始
def setup_class(self):
print("------->setup_class")
# 测试类级结束
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
if __name__ == '__main__':
pytest.main("-s test_abc.py")
执行结果:
------->setup_class # 第一次 setup_class()
------->test_a
.
------->test_b
F
------->teardown_class # 第一次 teardown_class()
三 配置文件
pytest的配置文件通常放在测试目录下,名称为pytest.ini,命令行运行时会使用该配置文件中的配置.
1 配置pytest命令行运行参数
[pytest]
addopts = -s ... # 空格分隔,可添加多个命令行参数 -所有参数均为插件包的参数
2 配置测试搜索的路径
testpaths = ./scripts # 当前目录下的scripts文件夹 -可自定义
3 配置测试搜索的文件名
python_files = test_*.py
# 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件 -可自定义
4 配置测试搜索的测试类名
python_classes = Test_*
# 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类 -可自定义
5 配置测试搜索的测试函数名
[pytest]
python_functions = test_*
# 当前目录下的scripts文件夹下,以test_开头,以.py结尾的所有文件中,以Test_开头的类内,以test_开头的方法 -可自定义
四 常用插件
插件列表网址:https://plugincompat.herokuapp.com
修改后地址:https://docs.pytest.org/en/latest/reference/plugin_list.html
前置条件:
1.文件路径:
- Test_App
- - test_abc.py
- - pytest.ini
2.pyetst.ini配置文件内容:
[pytest]
# 命令行参数
addopts = -s
# 搜索文件名
python_files = test_*.py
# 搜索的类名