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/ 本文主要翻译一些英文注释,添 ...
随机推荐
- 网站数据分析&初始来源
数据分析:如何追踪访客初始来源_搜索学院_百度搜索资源平台 https://ziyuan.baidu.com/college/articleinfo?id=260 网站数据分析:如何追踪访客初始来源 ...
- Python PEP8 编码规范中文版
原文链接:https://legacy.python.org/dev/peps/pep-0008/ 参考:https://blog.csdn.net/ratsniper/article/details ...
- Errors running builder 'DeploymentBuilder' on project
Errors running builder 'DeploymentBuilder' on project 1.修改java源代码后点击保存,IDE 自动编译并热部署,提示如下错误: Errors o ...
- [转帖]SAP S/4 HANA与SAP Business Suite/R3(ECC)的区别
SAP S/4 HANA与SAP Business Suite/R3(ECC)的区别 https://blog.csdn.net/zhongguomao/article/details/5351520 ...
- mybatis事务管理机制详解
1.mybatis事务的配置和使用 mybatis事务有两种使用方式: (a):使用JDBC的事务管理机制:即使用java.Sql.Connection对象完成对事务的提交,回滚和关闭操作. (b): ...
- AI算法第三天【矩阵分析与应用】
- 莫烦theano学习自修第二天【激励函数】
1. 代码如下: #!/usr/bin/env python #! _*_ coding:UTF-8 _*_ import numpy as np import theano.tensor as T ...
- Git官方推荐用书
用Git看了N多的Blog, 乱七八糟. 官方的推荐用书写得最好,最权威.还可以下载pdf.记录一笔. https://git-scm.com/book/zh/v2/
- APP test
在讲APP测试之前,先讲一下,目前APP的操作系统以及APP相关基础知识. 一.APP基础知识 1.操作系统# 现在移动端的操作系统主流的分为两种:(1)安卓系统 (2)IOS系统. 2.安卓系统# ...
- PHP namespace、require、use区别
假设 有文件a.php 代码 <?php class a{//类a public function afun()//函数afun { echo "aaaa"; } } ?&g ...