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_安装和入门的更多相关文章

  1. Apache Hadoop2.x 边安装边入门

    完整PDF版本:<Apache Hadoop2.x边安装边入门> 目录 第一部分:Linux环境安装 第一步.配置Vmware NAT网络 一. Vmware网络模式介绍 二. NAT模式 ...

  2. bower安装使用入门详情

    bower安装使用入门详情   bower自定义安装:安装bower需要先安装node,npm,git全局安装bower,命令:npm install -g bower进入项目目录下,新建文件1.tx ...

  3. [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍

    前面介绍了很多Selenium基于自动测试的Python爬虫程序,主要利用它的xpath语句,通过分析网页DOM树结构进行爬取内容,同时可以结合Phantomjs模拟浏览器进行鼠标或键盘操作.但是,更 ...

  4. 虚拟光驱 DAEMON Tools Lite ——安装与入门

    DAEMON Tools Lite 是什么?它不仅仅是虚拟光驱.是的,你可以使用它制作.加载光盘映像,但是 DAEMON Tools 产品那么多,Lite版与其他版本究竟有什么不同呢?或者说,是什么让 ...

  5. Python 3.6.3 官网 下载 安装 测试 入门教程 (windows)

    1. 官网下载 Python 3.6.3 访问 Python 官网 https://www.python.org/ 点击 Downloads => Python 3.6.3 下载 Python ...

  6. 八:Lombok 安装、入门 - 消除冗长的 java 代码

    Lombok 安装.入门 - 消除冗长的 java 代码 前言:    逛开源社区的时候无意发现的,用了一段时间,觉得还可以,特此推荐一下.    lombok 提供了简单的注解的形式来帮助我们简化消 ...

  7. robotframework安装及入门指南

    将很久之前自己在本地记录的一些笔记发表到随笔来,希望能够帮到一些童鞋~ robotframework安装及入门指南 本文主要介绍robotframework在windows环境的安装过程! 安装步骤 ...

  8. windows下nodejs express安装及入门网站,视频资料,开源项目介绍

    windows下nodejs express安装及入门网站,视频资料,开源项目介绍,pm2,supervisor,npm,Pomelo,Grunt安装使用注意事项等总结 第一步:下载安装文件下载地址: ...

  9. Tensoflw.js - 01 - 安装与入门(中文注释)

    Tensoflw.js - 01 - 安装与入门(中文注释) 参考 W3Cschool 文档:https://www.w3cschool.cn/tensorflowjs/ 本文主要翻译一些英文注释,添 ...

随机推荐

  1. haoop笔记

    : //:什么是hadoop? hadoop是解决大数据问题的一整套技术方案 :hadoop的组成? 核心框架 分布式文件系统 分布式计算框架 分布式资源分配框架 hadoop对象存储 机器计算 :h ...

  2. 【转】Linux下cp: omitting directory `XXX'问题解决

    在linux系统中复制文件夹时提示如下: Shell代码 [root@idtp4 site-packages]# /site-packages/ cp: omitting directory ‘yag ...

  3. 本地项目托管到github上

    一,步骤 1.在github上新建一个仓库 2.进入我的项目目录, git init //初始化本地仓库 3.git add . //把修改的代码提交到暂存区 4.git status 该命令会把你本 ...

  4. Linux watchdog

    使用 watchdog 构建高可用性的 Linux 系统及应用https://www.ibm.com/developerworks/cn/linux/l-cn-watchdog/index.html ...

  5. Notepad++快捷使用

    用Notepad++写代码,要是有一些重复的代码想copy一下有木有简单的方法呢,确实还是有的不过也不算太好用.主要是应用键盘上的 Home 键 和 End 键.鼠标光标停留在一行的某处,按 Home ...

  6. python selenium中如何测试360等基于chrome内核的浏览器

    转自:https://blog.csdn.net/five3/article/details/50013159 直接上代码,注意是基于chrome内核的浏览器,基于ie的请替换其中的chrome方法为 ...

  7. babel (三) babel polly-fill

    Babel includes a polyfill that includes a custom regenerator runtime and core-js. This will emulate ...

  8. nginx配置ssl证书后无法访问https

    一直听说https更安全,要安装证书,一直没试过,今天终于试了试 首先得有个http的域名网站,服务器. 到阿里云的安全-ssl证书管理申请一个免费的,可以绑定一个域名  然后完善资料,照着例子配置一 ...

  9. 使用withCount后再使用select设置查询的字段。就找不到withCount的数据了

    https://laravelacademy.org/index.php/discussion/1021 如:Article::withCount(['comments'])->select(' ...

  10. js发布订阅模式实现

    //可以用于无相关页面或组件的事件.数据传递,减少在onShow中的业务,降低代码耦合 let events = {} /**订阅**/ function on(name, self, callbac ...