为什么要使用Pytest
就Python的测试框架而言,目前比较流行的就是pytest和unittest,unittest广为人知,但就现在而言是老框架了,但是依旧有那么多喜欢使用他来做自动化测试。
pytest是基于unittest开发的另一款更高级更好用的单元测试框架,作为知识更新,也更该去学习新知识了,它就和Testng和junit一样,无论从逼格和好用程度来看,都是完胜后者。
pytest特点
- 非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考
- 能够支持简单的单元测试和复杂的功能测试
- 支持参数化
- 执行测试过程中可以将某些测试跳过(skip),或者对某些预期失败的case标记成失败
- 支持重复执行(rerun)失败的 case
- 支持运行由 nose, unittest 编写的测试 case
- 可生成 html 报告
- 方便的和持续集成工具 jenkins 集成
- 可支持执行部分用例
- 具有很多第三方插件,并且可以自定义扩展
快速入门
示例代码如下:
# -*- coding: utf-8 -*-
# @Time : 2020/10/15 20:10
# @Author : longrong.lang
# @FileName: test_demo.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
def add(x):
return x + 2;
class TestClass(object):
# 测试是否相等
def test_add(self):
assert add(2) == 5
# 测试包含
def test_in(self):
a = 'hello world'
b = 'he'
assert b in a
# 测试不包含
def test_not_in(self):
a = 'Hello'
b = 'hi'
assert b not in a
1、执行
命令行当前文件同级目录下,输入如下命令:
pytest
说明:
-
只执行 pytest ,会查找当前目录及其子目录下以 test_*.py 或 *_test.py 文件,找到文件后,在文件中找到以
-
test 开头函数并执行只想执行某个文件,可以 pytest test_demo.py
-
加上-q,就是显示简单的结果: pytest -q test_demo.py
用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的
Pytest用例的设计原则
1.文件名以 test_.py 文件和_test.py
2.以 test_ 开头的函数
3.以 Test 开头的类,不能包含 init 方法
4.以 test_ 开头的类里面的方法
5.所有的包 pakege 必项要有__init__.py 文件
Pytest执行用例规则
下面以windows系统为例,使用命令来来执行pytest
1、指定目录下的所有用例
pytest
2、执行某一个py文件下用例
pytest 文件名.py
3、运行test_demo.py文件中模块里面的某个函数,或者某个类,某个类里面的方法
说明:加v和不加-v都可以,加-v的话,打印的信息更详细
pytest -v test_demo.py::TestClass::test_add
pytest test_demo.py::TestClass::test_not_in
pytest test_demo.py::test_in
4、运行test_demo.py 模块里面,测试类里面的某个方法
pytest test_demo.py::test_in
5、-m 标记表达式(后面有详解)
pytest -m login
将运行用 @pytest.mark.login 装饰器修饰的所有测试,后面有详解!
6、-q 简单打印,只打印测试用例的执行结果
pytest -q test_demo.py
7、-s 详细打印
pytest -s test_demo.py
8、-x 遇到错误时停止测试
pytest test_demo.py -x
9、—maxfail=num,当用例错误个数达到指定数量时,停止测试
pytest test_demo.py --maxfail=1
10、-k 匹配用例名称
pytest -s -k _in test_demo.py
11、-k 根据用例名称排除某些用例
pytest -s -k "not _in" test_demo.py
12、-k 同时匹配不同的用例名称
pytest -s -k "add or _in" test_demo.py
使用Pycharm执行pytest
1、File->settings->python integrated tools->Testing下的default testrunner修改为Pytest
注意:
pytest兼容unittest脚本,所以不影响之前使用unittest编写的脚本
2、并不是修改完以上配置,就一定好用,如上面方法修改完仍不好用,参考下面方案:
- 检查pycharm中的python interpreter是否设置为Python安装目录下的Python.exe
- pycharm设置为国内源,如豆瓣、清华、阿里云等等!
3、如果和我一样之前使用IDEA中pytest插件编码的话,在进行完以上两步操作后,执行如下操作:
-
打开IDEA,将settings->python integrated tools->Testing下的default
testrunner修改为Pytest -
你会在打开的.py文件右上角看到提示,提示你选择Python的sdk路径,选择为Python安装目录下的Python.exe,确定后,会自动编译更新,更新完你会发现使用IDEA可以使用pytest运行了
-
再回头查看pycharm这时候也提示你选择sdk的安装目录,同上选择好Python安装目录,也会自动编译更新,更新完后,你会发现使用pycharm也可以使用pytest运行了
看完点赞 ~养成好习惯,以上内容希望对你有帮助,如果对软件测试、接口测试、自动化测试、面试经验交流感兴趣可以加入我们。642830685,免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一起交流。