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/ 本文主要翻译一些英文注释,添 ...
随机推荐
- Hadoop01的主要总结
Hadoop (离线) 分布式的计算框架 scala---spark(实时计算框架)
- PHPer未来路在何方...
PHP 从诞生到现在已经有20多年历史,从Web时代兴起到移动互联网退潮,互联网领域各种编程语言和技术层出不穷, Node.js . GO . Python 不断地在挑战 PHP 的地位.这些技术的推 ...
- PHP之CLI模式
转载: http://www.cnblogs.com/zcy_soft/archive/2011/12/10/2283437.html 所有的PHP发行版,不论是编译自源代码的版本还是预创建的版本,都 ...
- redux模块化demo
store.js 在redux中 store 是唯一的. import {createStore} from 'redux'; import reducer from './reducer' // 引 ...
- jquery on绑定事件
描述:给一个或多个元素(当前的或未来的)的一个或多个事件绑定一个事件处理函数.(1.7版本开始支持,是 bind().live() 和 delegate() 方法的新的替代品) 语法:.on( eve ...
- Python Note1: Pycharm的安装与使用
前言 曾经学过一段时间python,虽然现在工作了主要使用C#和C++,但是觉得还是有必要在业余的时候学习学习python,提升下自己的知识面,毕竟技多不压身,加油吧! 安装与激活Pycharm 个人 ...
- React 避免重渲染
组件的重新渲染 我们可以在 React 组件中的 props 和 state 存放任何类型的数据,通过改变 props 和 state,去控制整个组件的状态.当 props 和 state 发生变化时 ...
- js对字符串的一些操作方法
1.charCodeAt(index); 返回一个整数,代表下标位置上字符的Unicode的编码. 2.fromCharCode(code1,code2,code3,...); code1代表Unic ...
- 一、zipkin
zipkin是Twitter基于google的分布式监控系统Dapper(论文)的开发源实现,zipkin用于跟踪分布式服务之间的应用数据链路(具体就是收集微服务之间的调用情况,然后处理调用之间数据延 ...
- layui tips