1. 程式人生 > >Faker--一種測試資料生成工具

Faker--一種測試資料生成工具

簡介

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;

引用外部的provider

每個屬性的生成器(如:’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中還有許多其他方法沒有在這裡提及到, 可以自行檢視其文件。