Backend Development 8 min read

Common Faker Library Functions – Usage and Code Examples

This article provides a comprehensive list of frequently used Faker library functions for generating mock data, explains how to install Faker, and includes practical Python code examples demonstrating random data generation, custom generators, and handling unique identifiers in test datasets.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Common Faker Library Functions – Usage and Code Examples

The article presents a detailed catalogue of commonly used Faker library functions, covering location data (e.g., country() , province() , city_suffix() ), address components, numeric and text generators, internet‑related data, personal information, and many other utilities.

It also describes functions for generating specific data types such as pybool() , pydecimal() , pyfloat() , pyint() , and user‑agent strings like chrome() , firefox() , and safari() . Additionally, it mentions functions for creating IDs, file paths, emails, and various locale‑specific values.

Installation is straightforward with the command:

pip install Faker

Below is a Python code example that imports Faker, creates a factory for the Chinese locale, and defines helper functions to generate random phone numbers, names, countries, IDs, addresses, emails, IPv4 addresses, and random strings of configurable length.

import random
from faker import Factory
fake = Factory().create('zh_CN')

def random_phone_number():
    """随机手机号"""
    return fake.phone_number()

def random_name():
    """随机姓名"""
    return fake.name()

def random_country():
    """随机国家"""
    return fake.country()

def random_ssn():
    """随机身份证"""
    return fake.ssn()

def random_address():
    """随机地址"""
    return fake.address()

def random_email():
    """随机email"""
    return fake.email()

def random_ipv4():
    """随机IPV4地址"""
    return fake.ipv4()

def random_str(min_chars=0, max_chars=8):
    """长度在最大值与最小值之间的随机字符串"""
    return fake.pystr(min_chars=min_chars, max_chars=max_chars)

def factory_generate_ids(starting_id=1, increment=1):
    """返回一个生成器函数,调用这个函数产生生成器,从starting_id开始,步长为increment。"""
    def generate_started_ids():
        val = starting_id
        local_increment = increment
        while True:
            yield val
            val += local_increment
    return generate_started_ids

def factory_choice_generator(values):
    """返回一个生成器函数,调用这个函数产生生成器,从给定的list中随机取一项。"""
    def choice_generator():
        my_list = list(values)
        rand = random.Random()
        while True:
            yield random.choice(my_list)
    return choice_generator

if __name__ == '__main__':
    print(random_phone_number())
    print(random_name())
    print(random_ssn())
    print(random_country())
    print(random_address())
    print(random_email())
    print(random_ipv4())
    print(random_str(min_chars=6, max_chars=8))
    # 常规生成有规则数据
    id_gen = factory_generate_ids(starting_id=0, increment=2)()
    for i in range(5):
        print(next(id_gen))
    # 常规生成姓名
    choices = ['张三', '李四', '王五', '赵六']
    choice_gen = factory_choice_generator(choices)()
    for i in range(5):
        print(next(choice_gen))

A second example demonstrates how to generate a list of dictionaries with unique IDs read from a local file, replace the IDs in each dictionary, and write back the remaining IDs to avoid duplication.

# encoding:utf-8
'''\n1、生成测试数据\n'''
sum = 5
def appendList():
    channel = []
    channels = {"id": 2, "remark": ""}
    print(type(channels))
    for i in range(sum):
        channel.append(channels)
    eee = str(channel).strip().strip('[]')
    w = eval("[" + eee + "]")  # 将t转成list类型
    # 2、按照数据,生成列表
    fin = open('/Users/xxx/id.txt')
    a = fin.readlines()
    if len(a) < sum:
        print('数量不足,请先生成,再继续')
    else:
        f = open('/Users/xxx/id.txt', 'r')
        s = f.readlines()[0:sum]
        chain = list(map(lambda x: x.strip(), s))
    c = []
    for i in range(len(w)):
        if i < len(w):
            w[i]['id'] = chain[i]
            c.append(w[i])
        else:
            break
    # 删除使用过的ID
    fout = open('/Users/xxx/id.txt', 'w')
    b = ''.join(a[sum:])
    fout.write(b)
    # 返回生成好的参数
    print(c)

The article concludes with a friendly invitation to share the QR code.

PythonData Generationtestingmock-datafaker
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.