一、安装pytest
pip install -U pytest
二、快速入门
示例代码如下:
# coding: utf-8
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用例的设计原则
-
文件名以 test_.py 文件和_test.py
-
以 test_ 开头的函数
-
以 Test 开头的类,不能包含 init 方法
-
以 test_ 开头的类里面的方法
-
所有的包 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 装饰器修饰的所有测试,后面有详解!
五、使用Pycharm执行pytest
1、File->settings->python integrated tools->Testing下的default testrunner修改为Pytest
注意:
pytest兼容unittest脚本,所以不影响之前使用unittest编写的脚本
2、并不是修改完以上配置,就一定好用,如上面方法修改完仍不好用,参考下面方案:
-
检查pycharm中的python interpreter是否设置为Python安装目录下的Python.exe
-
pycharm设置为国内源,如豆瓣、清华、阿里云等等!