一、测试用例命名规范
-
.py测试文件必须以"test_"开头(或"_test"结尾)
-
测试方法必须以"test_"开头
-
测试类必须以“Test”开头,且不能有init方法
二、测试用例执行顺序:
- 默认执行顺序
- 使用“pytest-ordering”自定义顺序(需要安装pytest-ordering插件)
测试用例跳过的2种方法:
1、打标签
2、skip
(条件为真跳过,为假反之)
三、常用断言类型
等于 ==
不等于 !=
大于 >
小于 <
属于 in
不属于 not in
大于等于 >=
小于等于 <=
是 is
不是 is not
四、pytest指定目录、文件执行测试用例
- 输入pytest ,后面不跟其他:会在主目录下找符合规则的所有测试‘用例
- 指定目录,只收集该目录下的测试用例:pytest 目标路径
- 指定文件: pytest 目标路径/目标文件.py
五、pytest配置项.ini
1、pytest 配置testpaths
使用步骤:
1、主目录下新建一个new file,并命名pytest.ini
2、写入配置
2、ini指定运行参数
addopts:-q
addopts:-v
addopts:-s
六、常用运行参数
pytest -m :执行特定的测试用例,给测试用例打标签
pytest -k: 执行用例包含“关键字”的用例
pytest -q: 说明:简化控制台的输出
pytest -v: 可以输出用例更加详细的执行信息(包括当前环境配置项)
pytest -s: 输出用例中的调试信息(print信息)
使用步骤
- pytest.ini配置项中定义mark
- 测试用例上打上标签
(可能有些会报错(nicodeDecodeError),这是因为pytest.ini配置文件中markers中用了中文导致的,换成英文就不会报错了)
七、pytest前置(setup)和后置(teardown)
模块级: setup_module/teardown_module
开始于模块始末,生效一次(一个py文件属于一个模块)
函数级: setup_function/teardown_function
对每条函数用例生效(不在类中)
类级: setup_class/teardown_class
只在类中前后运行一次(在类中)
方法级: setup_method/teardown_metho
开始于方法始末(在类中)
import pytest
def setup_module():
print("准备测试数据")
def teardown_module():
print("清理测试数据")
def test_1():
print("test1")
def test_2():
print("test2")
def test_3():
print("test3")
八、pytest解决接口参数依赖
场景:
用户名 密码登录
拿到登录的token,获取用户信息
方法1
通过return
方法2
类中使用
方法三
通过类属性/类变量的定义