python中强大的testdata库自动生成测试所需要的数据
testdata是用于生成测试数据的一个安装包,它不仅提供DictFactory类来生成数据,还提供特定的扩展功能。每个Factory实例均可用于生成用户所需要的特定个数的数据,这将使我们更好地统计分析结果
如果你的目的是生成数据并将其存储到数据库或基于数据库的文档,DictFactory将会变得更加快捷
首先安装testdata,我用的是python2.7版本,在用
pip install python-testdata
遇到下面的报错信息
Command "python setup.py egg_info" failed with error code 1 in c:\users\admini~1\appdata\local\temp\pip-build-k1cjcx\fake-factory\
如下是解决方法:先安装fake-factory
pip install fake-factory
接着安装
pip install --no-deps python-testdata
然后运行下面的程序,由于我所装的版本统一用name替代了firstName和 lastName,在原文的基础下进行下改动
import testdata
import random
class Users(testdata.DictFactory):
id = testdata.CountingFactory(10)
name = testdata.FakeDataFactory('name')
address = testdata.FakeDataFactory('address')
age = testdata.RandomInteger(10, 30)
gender = testdata.RandomSelection(['female', 'male'])
for user in Users().generate(10): # let say we only want 10 users
print user
出现如下的错误提醒:
raise ImportError(error)
ImportError: The ``fake-factory`` package is now called ``Faker``.
继续解决报错,原来是fake-factory的安装版本不对,重新安装并指定安装版本
pip install fake-factory==0.7.4
接下来就可以见证生成的数据啦
{'gender': 'male', 'age': 10, 'id': 10, 'address': u'09953 Sweeney Springs\nJenniferside, FM 00653-9018'}
{'gender': 'female', 'age': 14, 'id': 11, 'address': u'59348 Mike Trail Apt. 106\nNorth Scotthaven, DE 04666'}
{'gender': 'male', 'age': 28, 'id': 12, 'address': u'53128 Archer Island Suite 256\nSouth Michaelfurt, MI 83350'}
{'gender': 'male', 'age': 18, 'id': 13, 'address': u'3559 Kimberly Wall Apt. 924\nJustinfort, FM 41543-5666'}
{'gender': 'male', 'age': 14, 'id': 14, 'address': u'54451 Fisher Mount\nNorth Michelle, UT 50280-8984'}
{'gender': 'male', 'age': 22, 'id': 15, 'address': u'PSC 4666, Box 4608\nAPO AE 90517-5117'}
{'gender': 'male', 'age': 12, 'id': 16, 'address': u'6186 Lisa Groves Apt. 593\nStephenberg, TN 15302-7752'}
{'gender': 'female', 'age': 19, 'id': 17, 'address': u'3919 White Drives\nNorth Calvinport, MD 26577-9590'}
{'gender': 'female', 'age': 30, 'id': 18, 'address': u'148 Anthony Mountain\nStevenfort, RI 38933-9947'}
{'gender': 'female', 'age': 27, 'id': 19, 'address': u'2496 Michael Groves Apt. 021\nWest Kathleenside, PR 42583-3035'}
我们也可以构造一个数据依赖于另一个数据的情况,如下
import testdata class ExampleFactory(testdata.DictFactory):
a = testdata.CountingFactory(10)
b = testdata.ClonedField("a") # b will have the same value as field 'a' for e in ExampleFactory().generate(5):
print e
此时生成的数据为
{'a': 10, 'b': 10}
{'a': 11, 'b': 11}
{'a': 12, 'b': 12}
{'a': 13, 'b': 13}
{'a': 14, 'b': 14}
若我们的需求是生成事件数据,比如我们是构造一个事件的开始和结束时间,并且结束时间要在开始时间的20分钟后结束,并且,我们希望各个数据的开始时间间隔12分钟
import testdata
import datetime EVENT_TYPES = ["USER_DISCONNECT", "USER_CONNECTED", "USER_LOGIN", "USER_LOGOUT"]
class EventsFactory(testdata.DictFactory):
start_time = testdata.DateIntervalFactory(datetime.datetime.now(), datetime.timedelta(minutes=12))
end_time = testdata.RelativeToDatetimeField("start_time", datetime.timedelta(minutes=20))
event_code = testdata.RandomSelection(EVENT_TYPES) for event in EventsFactory().generate(5):
print event
若要生成百分比不同的数据,比如我们想要构造工作的数据,包含用户名、状态、描述,其中状态为pending的占90%,剩下的10%的状态为‘error’。除此之外,如果状态为error的用户该为‘support’,状态为pending的用户应为‘admin’
class Job(testdata.DictFactory):
state = testdata.StatisticalValuesFactory([('pending', 90), ('error', 10)])
assigned_user = testdata.ConditionalValueField('state', {'error': 'support'}, 'admin')
description = testdata.RandomLengthStringFactory() for i in Job().generate(10):
print i
生成的数据为
{'state': 'pending', 'assigned_user': 'admin', 'description': 'HKCVoGAOJZVKYqGktTakWqewxScyUSSGcMj'}
{'state': 'pending', 'assigned_user': 'admin', 'description': 'dyyLbtxfoqotlaNfWieoVvXFlzRYNOajYFVmwtXDRdVoQItDnjgptpEiBJHBgCuzqOZVwsxyWbByrJvgiTKKNyuiSsKO'}
{'state': 'error', 'assigned_user': 'support', 'description': 'nuvRQyhcvvXWJuXhCbWVUyWAmKoioTcYIBHtcPwvgRytCsPlWEvSHRFjXDUAIgPblhhHFTKzCmmitBErHzpXLBoI'}
{'state': 'pending', 'assigned_user': 'admin', 'description': 'IhrQoAkFNwqfZSxfkwCSmaGRFodFZYVHCegEnAMpTBtqUZMgaFGlAaznzUNbDrdgPDHNrAvJEQZRDUQxdDKsLvXJiMDR'}
{'state': 'pending', 'assigned_user': 'admin', 'description': 'ftINruSFdOeAqOuDyInNgIrQPoegOwlqWSFIHYNVY'}
另外,可以对字段进行重写和新增字段操作,在前面生成用户信息的例子中,我们可以将用户的名称设置为定值,并且新建email字段
for user in Users(name=testdata.Constant('John'), age=testdata.RandomInteger(40, 60), email=testdata.FakeDataFactory('email')).generate(10): # let say we only want 10 users
print user
生成的数据为
{'name': 'John', 'gender': 'male', 'age': 40, 'email': u'brownamy@yahoo.com', 'address': u'813 Donald Route\nSouth Andrea, SC 99925', 'id': 15}
{'name': 'John', 'gender': 'female', 'age': 58, 'email': u'gloriapatel@may-mitchell.com', 'address': u'73919 Hodges Courts\nTammyside, ME 89926-3945', 'id': 16}
{'name': 'John', 'gender': 'male', 'age': 45, 'email': u'ashley40@cooper.info', 'address': u'95546 Mary Flats\nWest Codystad, PA 34744', 'id': 17}
{'name': 'John', 'gender': 'female', 'age': 43, 'email': u'xwhite@pierce-sutton.com', 'address': u'4051 Reese Mission Suite 829\nNew Danny, NE 92155-8318', 'id': 18}
{'name': 'John', 'gender': 'male', 'age': 60, 'email': u'qpoole@rice.com', 'address': u'3584 Bright Ramp\nJohnstonmouth, NV 12566-4343', 'id': 19}
上面例子中所用的基类如下
| Factory类 | 简介 |
| Factory | 所有的Factory的基类 |
| DictFactory | 非常强大的基类,它可让子类创建Factory,具体可参考上面的例子 |
| ListFactory | A factory that returns on each iteration a list of elements_per_list items returned from calls to the given factory. |
| Callable | Gets a callable object as an argument and returns the result of calling the object on every iteration |
| DependentCallable | Gets a callable object as an argument and returns the result of calling the object passing the defined fields as arguments on every iteration |
| ClonedField | A factory that copies the value of another factory. |
日期类
| Factory类 | 简介 |
| RandomDateFactory | Generates random dates (python's datetime) between 2 dates |
| DateIntervalFactory | Generates datetime objects starting from base while adding delta to it each iteration. |
| RelativeToDatetimeField | Generates datetime object relative to another datetime field, like if you have start_timewhich is a RandomDateFactory field, and want an end_time field that is always 15 minutes later. |
本文是对https://github.com/arieb/python-testdata的粗略翻译
python中强大的testdata库自动生成测试所需要的数据的更多相关文章
- Python中使用模块和库编程
""" python中使用模块和库编程 导入模块 import modulename [as alias] from modulename import fun1,fun ...
- Python中导入第三方声源库Acoular的逻辑解释以及Acoular的下载
[声明]欢迎转载,但请保留文章原始出处→_→ 秦学苦练:http://www.cnblogs.com/Qinstudy/ 文章来源:http://www.cnblogs.com/Qinstudy/p/ ...
- 使用ctypes在Python中调用C++动态库
使用ctypes在Python中调用C++动态库 入门操作 使用ctypes库可以直接调用C语言编写的动态库,而如果是调用C++编写的动态库,需要使用extern关键字对动态库的函数进行声明: #in ...
- python之gui-tkinter可视化编辑界面 自动生成代码
首先提供资源链接 http://pan.baidu.com/s/1kVLOrIn#list/path=%2F
- python学习-- Django根据现有数据库,自动生成models模型文件
Django引入外部数据库还是比较方便的,步骤如下 : 创建一个项目,修改seting文件,在setting里面设置你要连接的数据库类型和连接名称,地址之类,和创建新项目的时候一致 运行下面代码可以自 ...
- Python中处理日期时间库的使用方法(转载)
<本文来自公众号“大邓带你玩python”,转载> 用百分之20时间,学会解决百分之80的问题. 常用的库有time.datetime.其中datetime库是对time库的封装,所以使用 ...
- python 中的json解析库
当一个json 数据很大的时候.load起来是很耗时的.python中常见的json解析库有cjson,simplesjson,json, 初步比较了一下, 对于loads来讲 simplejson ...
- 【日常记录】Unity3D 中的 Surface Shader 是不支持在 Pass中使用的,因为自动生成了 Pass
如题 搞了好久,一直报错: Shader error in 'custom_outline_effect': Parse error: syntax error, unexpected TOK_PAS ...
- Entity Framewrok 7beta7中不同版本sql server自动生成分页sql语句的问题
在EF中,使用linq进行分页是很方便的,假如我们有一个EMP表,结构如下: public class Emp { [Key] public Guid No { get; set; } public ...
随机推荐
- VLAN-4-在路由器上配置Trunk
VLAN Trunk技术可以用在路由器和主机上,也可以用在交换机上.路由器不支持DTP,所以工程师必须手动配置. 路由器Trunk需要使用子接口(在一个接口中实现多个vlan间的路由和通信),每个子接 ...
- centos 无界面 服务器 安装chrome部署chromedriver
转:https://blog.csdn.net/u013849486/article/details/79466359 基本 做完了,要弄进docker里面去了的时候,才搜到 docker-chrom ...
- TCP长链接调试利器nc
最近做了不少TCP长链接的开发,包括服务端和客户端.本人感觉服务器端与客户端通信时最好采用字符串形式,这样可以做要平台无关,跨语言.如果采用对象序列化机制通用性会较差.另外采用字符串形式用nc调试很方 ...
- zh-cn、en-us、zh-tw等表示语言(文化)代码与国家地区对照表(最全的各国地区对照表)
af 公用荷兰语 af-ZA 公用荷兰语 - 南非 sq 阿尔巴尼亚 sq-AL 阿尔巴尼亚 -阿尔巴尼亚 ar 阿拉伯语 ar-DZ 阿拉伯语 -阿尔及利亚 ar-BH 阿拉伯语 -巴林 ar-EG ...
- 手动释放Linux内存
查看内存: [root@iZ9dp52tlpqyihuisujjswZ bin]# free -h total used free shared buff/cache available Mem: 3 ...
- String的小笔记
String类的对象是不可变的! 在使用String类的时候要始终记着这个观念.一旦创建了String对象,它就不会改变. String类中也有可以改变String中字符串的方法,但只要是涉及改变的方 ...
- jQuery插件pagination.js源码解读
pagination的github地址:https://github.com/gbirke/jquery_pagination 公司用的是1.2的版本,所以我就读1.2的了. jQuery.fn.pa ...
- 玲珑杯”ACM比赛 Round #4 1054 - String cut 暴力。学到了扫描的另一种思想
http://www.ifrog.cc/acm/problem/1054 问删除一个字符后的最小循环节是多少. 比赛的时候想不出,不知道怎么暴力. 赛后看了别人代码才晓得.唉,还以为自己字符串还不错, ...
- java 利用c3p0管理数据库连接池
数据库连接池类,用于获取数据库连接.利用单例模式保证所有的连接都只通过一个连接池管理. package com.mousewheel.dbcon; import java.io.InputStream ...
- DataGridView使用技巧(七、设定列宽和行高自动调整)----.NET
DataGridView使用技巧(七.设定列宽和行高自动调整)----.NET 1) 设定行高和列宽自动调整 [VB.NET]' 设定包括Header和所有单元格的列宽自动调整DataGridView ...