Faker一款基于Python的测试数据生成工具,无论是用于初始化数据库,创建XML文件,或是生成压测数据,Faker都是不错的选择。
使用pip安装:
pip install Faker
使用faker.Factory.create()创造并初始化faker生成器,faker生成器可以通过访问按所需数据类型命名的属性来生成数据。
from faker import Factory
fake = Factory.create()
fake.name()
fake.address()
fake.text()
方法fake.name()的每次调用都会产生不同的(随机)结果。这是因为faker向faker.Generator.method_name()调用了faker.Generator.format(method_name)。
for _ in range(10):
print(fake.name())
---------------------------------------------------------------
C:\Python27\python.exe "D:/Python Projects/paydayloan/aaa.py"
Leslie Mckinney
Thomas White
Anna Mcdowell
William Allen MD
Kelly House
Mrs. Yolanda Myers
Whitney Richard
Erika Davis
Ethan Harper
Monique Terry
faker可以同时指定所在区域与语言生成你想要的测试数据,如:
from faker import Factory
fake = Factory.create('zh_CN')
for _ in range(10):
print(fake.name())
--------------------------------------------------------------
C:\Python27\python.exe "D:/Python Projects/paydayloan/aaa.py"
卜林
苗桂英
童柳
归婷
蔺春梅
屠淑珍
滕桂花
延健
陆丹
田玉珍
如果不想写代码,也可直接通过命令行来生成数据,把生成的数据复制粘贴即可:
faker [-h] [--version] [-o output]
[-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}]
[-r REPEAT] [-s SEP]
[-i {module.containing.custom_provider othermodule.containing.custom_provider}]
[fake] [fake argument [fake argument ...]]
faker: is the script when installed in your environment, in development you could use python -m faker instead
-h, --help: shows a help message
--version: shows the program's version number
-o FILENAME: redirects the output to the specified filename
-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}: allows use of a localized provider
-r REPEAT: will generate a specified number of outputs
-s SEP: will generate the specified separator after each generated output
-i {my.custom_provider other.custom_provider} list of additional custom providers to use. Note that is the import path of the module containing your Provider class, not the custom Provider class itself.
fake: is the name of the fake to generate an output for, such as name, address, or text
[fake argument ...]: optional arguments to pass to the fake (e.g. the profile fake takes an optional list of comma separated field names as the first argument)
例如
[root@localhost ~]# faker address
29763 Bailey Unions Suite 613
Wayneville, OH 64319-6008
[root@localhost ~]# faker -l zh_CN name
卞云
[root@localhost ~]# faker -r=3 -s=";" name
Latasha Copeland;
Luis Nguyen;
Carlos Macdonald;
每个属性的生成器(如:’name’, ‘address’, ‘lorem’) 都有各自的provider,faker可以引用外部的provider来丰富所生成的数据。
from faker import Faker
fake = Faker()
# 首先import provider
from faker.providers import BaseProvider
# 创建一个新的类
class MyProvider(BaseProvider):
def foo(self):
return 'bar'
#把新provider加到fake实例中
fake.add_provider(MyProvider)
# 使用新provider:
fake.foo()
> 'bar'
Faker中还有许多其他方法没有在这里提及到, 可以自行查看其文档。