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‘[email protected]‘, ‘address‘: u‘813 Donald Route\nSouth Andrea, SC 99925‘, ‘id‘: 15}
{‘name‘: ‘John‘, ‘gender‘: ‘female‘, ‘age‘: 58, ‘email‘: u‘[email protected]‘, ‘address‘: u‘73919 Hodges Courts\nTammyside, ME 89926-3945‘, ‘id‘: 16}
{‘name‘: ‘John‘, ‘gender‘: ‘male‘, ‘age‘: 45, ‘email‘: u‘[email protected]‘, ‘address‘: u‘95546 Mary Flats\nWest Codystad, PA 34744‘, ‘id‘: 17}
{‘name‘: ‘John‘, ‘gender‘: ‘female‘, ‘age‘: 43, ‘email‘: u‘[email protected]‘, ‘address‘: u‘4051 Reese Mission Suite 829\nNew Danny, NE 92155-8318‘, ‘id‘: 18}
{‘name‘: ‘John‘, ‘gender‘: ‘male‘, ‘age‘: 60, ‘email‘: u‘[email protected]‘, ‘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的粗略翻译

时间: 2024-08-30 02:39:38

python中强大的testdata库自动生成测试所需要的数据的相关文章

sharepoint 2013 中自建母版页,自动生成html中的顶部导航代码步骤

sharepoint 2013 中自建母版页,自动生成html中的顶部导航代码步骤 分类: SharePoint2013-07-05 11:21 738人阅读 评论(0) 收藏 举报 SharePointsharepoint 2013 1.点击打开设计编辑器:编辑母版页项目 2.找到或者新建一个测试页面(.html),点击网页右上方的"代码段"打开 3.点击代码段打开如下页面,点击对应导航便会自动生成html中可以直接是用的导航代码 4.复制代码段到html模板中相应位置(自行定义,可

使用ctypes在Python中调用C++动态库

使用ctypes在Python中调用C++动态库 入门操作 使用ctypes库可以直接调用C语言编写的动态库,而如果是调用C++编写的动态库,需要使用extern关键字对动态库的函数进行声明: #include <iostream> using namespace std; extern "C" { void greet() { cout << "hello python" << endl; } } 将上述的C++程序编译成动态链

Python中处理日期时间库的使用方法(转载)

<本文来自公众号"大邓带你玩python",转载> 用百分之20时间,学会解决百分之80的问题. 常用的库有time.datetime.其中datetime库是对time库的封装,所以使用起来更加便捷.date是指日期时间(年月日)处理,time往往更加细小的单位(小时分秒等)的时间处理. 一.datetime库 datetime.date类 表示日期的类,常用的属性有year.month.day.参数都为整数. import datetime #任何一天 someday

Entity Framewrok 7beta7中不同版本sql server自动生成分页sql语句的问题

在EF中,使用linq进行分页是很方便的,假如我们有一个EMP表,结构如下: public class Emp { [Key] public Guid No { get; set; } public int Age { get; set; } [Required] [StringLength(50)] public string Name { get; set; } } 如果我们进行分页的话,一般使用Skip和Take方法,这里一行最简单的代码如下: mContext.Emp.OrderBy(e

3. python中的包和库

3.1模块和包的概念 当代码越来越多时,当把所有的代码都集中于一个文件中时,难以维护 将代码分开放在不同的py文件中,易于维护,同一名字的变量和函数互不影响 如 #a.py x=5 def f1(): pass #b.py x='str' def f1(iterable): pass a.py和b.py中变量和函数互不影响 将a.py称为模块a,将b.py称为模块b,可见,模块的名字就是.py文件的名字 引入第三方的模块 #test.py import math print math.pow(2

python中的requirements.txt文件的生成和使用

程序中必须包含一个 requirements.txt 文件,用于记录所有依赖包及其精确的版本号.如果要在另一台电脑上重新生成虚拟环境. pip 可以使用如下命令自动生成这个文件: (venv) $ pip freeze >requirements.txt 如果你要创建这个虚拟环境的完全副本,可以创建一个新的虚拟环境,并在其上运行以下命令: (venv) $ pip install -r requirements.txt 原文地址:http://blog.51cto.com/13914991/21

python selenium利用 126.com id自动生成

访问的是126.com 但是教程中id是固定的,可是一查代码, id是auto-id-1476087946510 后面的数字是自动变化的. 这可怎么办呢? #coding=utf-8 from selenium import webdriver ''' 测试简单元素操作 ''' url="http://www.126.com/" driver=webdriver.Firefox() driver.get(url) driver.find_element_by_xpath(".

python中强大的format函数

自python2.6开始,新增了一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串.语法 它通过{}和:来代替%. 请看下面的示例,基本上总结了format函数在python的中所有用法 1 #通过位置 2 print '{0},{1}'.format('chuhao',20) 3 4 print '{},{}'.format('chuhao',20) 5 6 print '{1},{0},{1}'.format('chuhao',20) 7 8 #通过关键字参数 9

python中enumerate内置库的使用

使用enumerate,可以自动进行索引下标的赋值,本例代码中使用enumerate,进行excel单元格的赋值操作. 代码如果重复被调用,可将该代码封装成类进行使用 1 1 import openpyxl 2 2 #加载excel文件 3 3 wb = openpyxl.load_workbook('test_datas/test_cases.xlsx') 4 4 #定位工作簿 5 5 sheet = wb['test'] 6 6 #测试数据 7 7 datas = [ 8 8 {'origi