pytest_01_安装和入门
pytest
安装与入门
1.pip install -U pytest
2.创建一个test01.py的文件
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
3.在该目录下执行pytest(venv)
D:\4_code\study>pytest
============================= test session starts =============================
platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1
rootdir: D:\4_code\study, inifile:
collected 1 item
test01.py . [100%]
========================== 1 passed in 0.19 seconds ===========================
(venv) D:\4_code\study>pytest
4.执行多个,新建一个py文件 test02.py
def add(x, y):
return x + y
def test_add():
assert add(1, 0) == 1
assert add(1, 1) == 2
assert add(1, 99) == 100
执行pytest
(venv) D:\4_code\study>pytest
============================= test session starts =============================
platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1
rootdir: D:\4_code\study, inifile:
collected 2 items
test01.py . [ 50%]
test02.py . [100%]
========================== 2 passed in 0.30 seconds ===========================
pytest将在当前目录及其子目录中运行test _ * .py或* _test.py形式的所有文件。
5.在一个类中组合多个测试
一旦开发了多个测试,您可能希望将它们分组到一个类中。pytest可以很容易地创建一个包含多个测试的类:
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
(venv) D:\4_code\study>pytest
============================= test session starts =============================
platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1
rootdir: D:\4_code\study, inifile:
collected 4 items
test_calc.py . [ 25%]
test_class.py .F [ 75%]
test_quick_start.py . [100%]
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________
self = <test_class.TestClass object at 0x058A59F0>
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:16: AssertionError
===================== 1 failed, 3 passed in 0.37 seconds ======================
6.指定测试 用例
(venv) D:\4_code\study>pytest -q test_calc.py
. [100%]
1 passed in 0.02 seconds
7.Assert
pytest使用的是python自带的assert关键字来进行断言
assert关键字后面可以接一个表达式,只要表达式的最终结果为True,那么断言通过,用例执行成功,否则用例执行失败
断言异常抛出
如
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
1/0的时候应该抛出ZeroDivisionError,否则用例失败,断言不通过。
8.Fixture
如测试数据为
[
{"name":"jack","password":"Iloverose"},
{"name":"rose","password":"Ilovejack"},
{"name":"tom","password":"password123"}
]
import pytest
import json
class TestUserPassword(object):
@pytest.fixture
def users(self):
return json.loads(open('./users.dev.json', 'r').read()) # 读取当前路径下的users.dev.json文件,返回的结果是dict
def test_user_password(self, users):
# 遍历每条user数据
for user in users:
passwd = user['password']
assert len(passwd) >= 6
msg = "user %s has a weak password" %(user['name'])
assert passwd != 'password', msg
assert passwd != 'password123', msg
(venv) D:\4_code\study>pytest test_user_password.py
============================= test session starts =============================
platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1
rootdir: D:\4_code\study, inifile:
collected 1 item
test_user_password.py F [100%]
================================== FAILURES ===================================
_____________________ TestUserPassword.test_user_password _____________________
self = <test_user_password.TestUserPassword object at 0x044783B0>
users = [{'name': 'jack', 'password': 'Iloverose'}, {'name': 'rose', 'password': 'Ilovejack'}, {'name': 'tom', 'password': 'password123'}]
def test_user_password(self, users):
# 遍历每条user数据
for user in users:
passwd = user['password']
assert len(passwd) >= 6
msg = "user %s has a weak password" %(user['name'])
assert passwd != 'password', msg
> assert passwd != 'password123', msg
E AssertionError: user tom has a weak password
E assert 'password123' != 'password123'
test_user_password.py:16: AssertionError
========================== 1 failed in 0.26 seconds ===========================
使用@pytest.fixture装饰器可以定义feature
在用例的参数中传递fixture的名称以便直接调用fixture,拿到fixture的返回值
3个assert是递进关系,前1个assert断言失败后,后面的assert是不会运行的,因此重要的assert放到前面
E AssertionError: user tom has a weak password可以很容易的判断出是哪条数据出了问题,所以定制可读性好的错误信息是很必要的
任何1个断言失败以后,for循环就会退出,所以上面的用例1次只能发现1条错误数据,换句话说任何1个assert失败后,用例就终止运行了
执行顺序
pytest找到以test_开头的方法,也就是test_user_password方法,执行该方法时发现传入的参数里有跟fixture users名称相同的参数
pytest认定users是fixture,执行该fixture,读取json文件解析成dict实例
test_user_password方法真正被执行,users fixture被传入到该方法
使用下面的命令来查看用例中可用的fixtures
pytest --fixtures test_user_password.py
------------------ fixtures defined from test_user_password -------------------
users
test_user_password.py:6: no docstring available
======================== no tests ran in 0.07 seconds =========================
数据清理
有时候我们需要在用例结束的时候去清理一些测试数据,或清除测试过程中创建的对象,我们可以使用下面的方式
import smtplib
import pytest
@pytest.fixture(scope="module")
def smtp():
smtp = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
yield smtp # provide the fixture value
print("teardown smtp")
smtp.close()
yield 关键字返回了fixture中实例化的对象smtp
module中的用例执行完成后smtp.close()方法会执行,无论用例的运行状态是怎么样的,都会执行
pytest_01_安装和入门的更多相关文章
- Apache Hadoop2.x 边安装边入门
完整PDF版本:<Apache Hadoop2.x边安装边入门> 目录 第一部分:Linux环境安装 第一步.配置Vmware NAT网络 一. Vmware网络模式介绍 二. NAT模式 ...
- bower安装使用入门详情
bower安装使用入门详情 bower自定义安装:安装bower需要先安装node,npm,git全局安装bower,命令:npm install -g bower进入项目目录下,新建文件1.tx ...
- [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍
前面介绍了很多Selenium基于自动测试的Python爬虫程序,主要利用它的xpath语句,通过分析网页DOM树结构进行爬取内容,同时可以结合Phantomjs模拟浏览器进行鼠标或键盘操作.但是,更 ...
- 虚拟光驱 DAEMON Tools Lite ——安装与入门
DAEMON Tools Lite 是什么?它不仅仅是虚拟光驱.是的,你可以使用它制作.加载光盘映像,但是 DAEMON Tools 产品那么多,Lite版与其他版本究竟有什么不同呢?或者说,是什么让 ...
- Python 3.6.3 官网 下载 安装 测试 入门教程 (windows)
1. 官网下载 Python 3.6.3 访问 Python 官网 https://www.python.org/ 点击 Downloads => Python 3.6.3 下载 Python ...
- 八:Lombok 安装、入门 - 消除冗长的 java 代码
Lombok 安装.入门 - 消除冗长的 java 代码 前言: 逛开源社区的时候无意发现的,用了一段时间,觉得还可以,特此推荐一下. lombok 提供了简单的注解的形式来帮助我们简化消 ...
- robotframework安装及入门指南
将很久之前自己在本地记录的一些笔记发表到随笔来,希望能够帮到一些童鞋~ robotframework安装及入门指南 本文主要介绍robotframework在windows环境的安装过程! 安装步骤 ...
- windows下nodejs express安装及入门网站,视频资料,开源项目介绍
windows下nodejs express安装及入门网站,视频资料,开源项目介绍,pm2,supervisor,npm,Pomelo,Grunt安装使用注意事项等总结 第一步:下载安装文件下载地址: ...
- Tensoflw.js - 01 - 安装与入门(中文注释)
Tensoflw.js - 01 - 安装与入门(中文注释) 参考 W3Cschool 文档:https://www.w3cschool.cn/tensorflowjs/ 本文主要翻译一些英文注释,添 ...
随机推荐
- 百度地图开发者API学习笔记一(转载)
一,实现功能: 在地图上标记点,划线等操作.如下图. 2.代码: <!DOCTYPE html> <html> <head> <meta http-equiv ...
- shell脚本--eval执行shell命令
和其他语言的eval功能差不多,都是将一个保存执行语句的变量作为参数,eval会让变量所保存的语句执行. 下面是一个执行表单提交的命令:注意,这里只是示例,应用中不要这么使用,很危险 #!/bin/b ...
- [转帖]FORFILES 的简单介绍。
FORFILES https://blog.csdn.net/sandy9919/article/details/82932460 命令格式: forfiles.exe /p "D:\备份& ...
- Java中List集合去除重复数据的四种方法
1. 循环list中的所有元素然后删除重复 public static List removeDuplicate(List list) { for ( int i = 0 ; i < lis ...
- 在layui中使用ajax不起作用
又是一个坑,坑了我一个下午.在layui插件中使用jquery的ajax请求,一点反应都没有,不管是改成get还是post请求,后台毫无反应,前端谷歌调试也没有报半点错. js代码如下: layui. ...
- python raise
当程序出现错误,python会自动引发异常,也可以通过raise显示地引发异常.一旦执行了raise语句,raise后面的语句将不能执行. 演示raise用法 try: s = None if s ...
- java学习之—队列
/** * 队列 * Create by Administrator * 2018/6/11 0011 * 下午 3:27 **/ public class Queue { private int m ...
- rbac组件引用
一. 批量操作思路 # 待新增 路由系统中有,但是数据库中还没有 路由系统的集合 - 数据库中权限集合 # 待更新 路由系统中有,数据库中也有, 只是更改了一些信息 路由系统的集合 & 数据库 ...
- 在python中定义二维数组
发表于 http://liamchzh.0fees.net/?p=234&i=1 一次偶然的机会,发现python中list非常有意思. 先看一段代码 [py]array = [0, 0, 0 ...
- delphi 怎么实现主窗口退出时,有一个提示框?
无论点窗口上的[按钮]还是[右上角的叉],能出现一个提示窗口,“是”-退出窗口,“否”-重新登录(调出登录窗口),“取消”-返回.MessageBox能实现吗?还是要调用新窗口(我调用窗口,有些错误) ...