簡介
Faker一款基于Python的測試數(shù)據(jù)生成工具,無論是用于初始化數(shù)據(jù)庫,創(chuàng)建XML文件又官,或是生成壓測數(shù)據(jù)左驾,F(xiàn)aker都是不錯的選擇镣隶。
使用方法
使用pip安裝:
pip install Faker
使用faker.Factory.create()創(chuàng)造并初始化faker生成器,faker生成器可以通過訪問按所需數(shù)據(jù)類型命名的屬性來生成數(shù)據(jù)什荣。
from faker import Factory
fake = Factory.create()
fake.name()
fake.address()
fake.text()
方法fake.name()的每次調(diào)用都會產(chǎn)生不同的(隨機)結(jié)果矾缓。這是因為faker向faker.Generator.method_name()調(diào)用了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可以同時指定所在區(qū)域與語言生成你想要的測試數(shù)據(jù)稻爬,如:
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"
卜林
苗桂英
童柳
歸婷
藺春梅
屠淑珍
滕桂花
延健
陸丹
田玉珍
命令行使用方法
如果不想寫代碼嗜闻,也可直接通過命令行來生成數(shù)據(jù),把生成的數(shù)據(jù)復(fù)制粘貼即可:
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;
引用外部的provider
每個屬性的生成器(如:'name', 'address', 'lorem') 都有各自的provider桅锄,faker可以引用外部的provider來豐富所生成的數(shù)據(jù)琉雳。
from faker import Faker
fake = Faker()
# 首先import provider
from faker.providers import BaseProvider
# 創(chuàng)建一個新的類
class MyProvider(BaseProvider):
def foo(self):
return 'bar'
#把新provider加到fake實例中
fake.add_provider(MyProvider)
# 使用新provider:
fake.foo()
> 'bar'
Faker中還有許多其他方法沒有在這里提及到, 可以自行查看其文檔。