The Hacker's Guide To Python 单元测试

基本方式

python中提供了非常简单的单元测试方式,利用nose包中的nosetests命令可以实现简单的批量测试。

安装nose

sudo pip install nose

编辑测试文件

# test_true.py
def test_true():
assert True def test_false():
assert False

执行测试

# 命令, nosetests命令会加载所有以test_开头的文件,并执行所有以test_开头的函数
nosetests -v
# 输出
test_true.test_true ... ok
test_true.test_false ... FAIL ======================================================================
FAIL: test_true.test_false
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/xxxx/workspace/py/test/test_true.py", line 5, in test_false
assert False
AssertionError ----------------------------------------------------------------------
Ran 2 tests in 0.007s FAILED (failures=1

unittest是python提供了单元测试的标准库。

# 为了兼容python 2.6和2.7
try:
import unittest2 as unittest
except ImportError:
import unittest class TestKey(unittest.TestCase):
def test_keyh(self):
a = ['a']
b = ['a', 'b']
self.assertEqual(a, b)

输出如下,

test_keyh (test_true.TestKey) ... FAIL

======================================================================
FAIL: test_keyh (test_true.TestKey)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/y/workspace/py/test/test_true.py", line 8, in test_keyh
self.assertEqual(a, b)
AssertionError: Lists differ: ['a'] != ['a', 'b'] Second list contains 1 additional elements.
First extra element 1:
b - ['a']
+ ['a', 'b'] ----------------------------------------------------------------------
Ran 1 test in 0.006s FAILED (failures=1)

此外,unittest.skipIf可以通过判断条件来选择是否进行测试,

class TestSkipped(unittest.TestCase):
@unitttest.skip("Do not run this")
def test_failt(self):
self.fail("This should not be run") @unittest.skipIf(mylib is None, "mylib is not available")
def test_mylib(self):
self.assertEqual(1, 1)

此外,自定义setUptearDown函数可以单元测试开始和结束时自动调用。

fixtures

fixtures模块可以用来临时改变当前的测试环境。

import fixtures
import os class TestEnviron(fixtures.TestWithFixtures):
def test_environ(self):
fixture = self.useFixture(
fixtures.EnvironmentVariable("FOOBAR", "42")) # 临时增加一个环境变量FOOBAR
self.assertEqual(os.environ.get("FOOBAR"), "42") def test_environ_no_fixture(self):
self.assertEqual(os.environ.get("FOOBAR"), None) # 上面增加的环境变量的操作对于其他函数无效

mock

mock模块可以用来进行模拟测试,其主要功能就是模拟一个函数,类或实例的行为。

由于网络测试环境的特殊性,最常用的使用就是模拟网络请求,具体例子如下,

# test_mock.py
import requests
import unittest
import mock class WhereIsPythonError(Exception):
pass def is_python():
try:
r = requests.get("http://python.org")
except IOError:
pass
else:
if r.status_code == 200:
return 'is python' in r.content
raise WhereIsPythonError('something happened') def get_fake_get(status_code, content):
m = mock.Mock()
m.status_code = status_code
m.content = content
def fake_get(url):
return m
return fake_get def raise_get(url):
raise IOError("unable to fetch url %s" % url) class TestPython(unittest.TestCase):
@mock.patch('requests.get', get_fake_get(
200, 'is python, hello'
))
def test_python_is(self):
self.assertTrue(is_python()) @mock.patch('requests.get', get_fake_get(
200, 'is not python, hello'
))
def test_python_is_not(self):
self.assertFalse(is_python())

输出如下,

# 命令
nosetests --tests=test_mock -v
# 结果
test_python_is (test_mock.TestPython) ... ok
test_python_is_not (test_mock.TestPython) ... ok ----------------------------------------------------------------------
Ran 2 tests in 0.001s OK

The Hacker's Guide To Python 单元测试的更多相关文章

  1. Hacker's guide to Neural Networks

    Hacker's guide to Neural Networks Hi there, I'm a CS PhD student at Stanford. I've worked on Deep Le ...

  2. [译]PyUnit—Python单元测试框架(1)

    1. 原文及参考资料 原文链接:http://docs.python.org/2/library/unittest.html# 参考文档: http://pyunit.sourceforge.net/ ...

  3. The Hitchhiker’s Guide to Python! — The Hitchhiker's Guide to Python

    The Hitchhiker's Guide to Python! - The Hitchhiker's Guide to Python The Hitchhiker's Guide to Pytho ...

  4. Python单元测试PyUnit框架轻度整改

    原理 参考:单元测试原理 背景 年后有段时间没写代码了,所以趁着周末找了个python单元测试玩下,测试自己的Android应用.发现PyUnit虽然在单个脚本文件中添加多个测试用例,比如官网提供的方 ...

  5. Python单元测试框架

    目录 概况 系统要求 使用PyUnit构建自己的测试 安装 测试用例介绍 创建一个简单测试用例 复用设置代码:创建固件 包含多个测试方法的测试用例类 将测试用例聚合成测试套件 嵌套测试用例 测试代码的 ...

  6. 一种数据与逻辑分离的Python单元测试工具

    一种数据与逻辑分离的Python单元测试工具 几个概念 TestCase TestCase是一个完整的测试单元,最小的测试执行实体,就是我们常说的测试用例. TestSuite 以某种特性将测试用例组 ...

  7. Python单元测试框架之pytest 4 -- 断言

    From: https://www.cnblogs.com/fnng/p/4774676.html Python单元测试框架之pytest -- 断言 2015-08-31 23:57 by 虫师, ...

  8. Python单元测试框架之pytest 3 -- fixtures

    From: https://www.cnblogs.com/fnng/p/4769020.html Python单元测试框架之pytest -- fixtures 2015-08-29 13:05 b ...

  9. Python单元测试框架之pytest 2 -- 生成测试报告

    From: https://www.cnblogs.com/fnng/p/4768239.html Python单元测试框架之pytest -- 生成测试报告 2015-08-29 00:40 by ...

随机推荐

  1. Mac/IOS/linux获取当前时间包含微秒毫秒的代码

    #include <sys/time.h> 1 struct UnityLocalTimeStat { int Year; int Month; int DayOfWeek; int Da ...

  2. HoloLens shell overview(Translation)

    HoloLens shell 概述 使用HoloLens时,shell是由你周围的世界和来自系统的全息图构成.我们可以称这个空间叫做混合现实(mixed world). 此shell由在你的世界里能让 ...

  3. mysql乐观锁总结和实践

    乐观锁介绍: 乐观锁( Optimistic Locking ) 相对悲观锁而言,乐观锁假设认为数据一般情况下不会造成冲突,所以在数据进行提交更新的时候,才会正式对数据的冲突与否进行检测,如果发现冲突 ...

  4. 【vuejs小项目——vuejs2.0版本】单页面搭建

    http://router.vuejs.org/zh-cn/essentials/nested-routes.html 使用嵌套路由开发,这里会出错主要把Vue.use(VueRouter);要进行引 ...

  5. 盘点销售一体机 打印POS一体的设备。 打印,盘点,销售PDA(手持终端)+移动销售POS软件

    一.产品介绍 本产品为一个PDA(手持终端)+移动销售POS管理软件组合.可以实现功能如下: 可以实现移动销售(销售退货).盘点.配送.移库.打印小票的功能. 销售时,可以选择客户.业务员.库房,并且 ...

  6. 如何用hypermesh生成包含interface的流体网格

    在计算气动声学的时候,有些情况是需要我们提取流体计算的结果作为声学分析的边界条件,但是,有些流体网格因为物理模型的问题需要我们设定interface,恰恰你是机械,对流体了解一点,又不想花费太多时间来 ...

  7. CODEVS 天梯 代码记录

    所有水题均被折叠 Lv.1 青铜 1201 #include<iostream> #include<cstring> #include<algorithm> #in ...

  8. BZOJ4516: [Sdoi2016]生成魔咒 后缀自动机

    #include<iostream> #include<cstdio> #include<cstring> #include<queue> #inclu ...

  9. 【系统篇】从int 3探索Windows应用程序调试原理

    探索调试器下断点的原理 在Windows上做开发的程序猿们都知道,x86架构处理器有一条特殊的指令——int 3,也就是机器码0xCC,用于调试所用,当程序执行到int 3的时候会中断到调试器,如果程 ...

  10. 第2章 新手必须掌握的Linux命令

      第2章 新手必须掌握的Linux命令 章节简述: 本章节讲述系统内核.Bash解释器的关系与作用,教给读者如何正确的执行Linux命令以及常见排错方法. 经验丰富的运维人员可以恰当的组合命令与参数 ...