TL;DR
Among other artifacts, every software tester is responsible for creating test data. This post gives the recipe how to create a ‘fake’ Python list using FactoryBoy library.
The Problem
As part of testing framework, I needed to have a Python list of strings that would contain random values. When you are using some library in any programming language, you should always consult library documentation. If library documentation simply describes how to use some library feature, that reveals quality for that library. Simple documentation means more library users.
Solution
Here is FactoryBoy documentation that explains how to use Faker library for generating random fake name values.
import factory from . import models class RandomUserFactory(factory.Factory): class Meta: model = models.User first_name = factory.Faker('first_name') last_name = factory.Faker('last_name')
And you get this:
>>> UserFactory() <User: Lucy Murray>
In order to figure out how to create other types of fake data, we need to consult Faker library documentation. I found list provider in python providers:
fake.pylist(nb_elements=10, variable_nb_elements=True, *value_types) # [ 'xHlTHzlRrhqENIrtklPn', # 'pLIBqjFoTRMQFLyoymYx', # 1578, # 'xDOZZoCTmEfUERfgmfyT', # 515557232061889.0, # 'lkrENLrowyOxjDnIMtDU']
Default documentation gives example for list with mixed data types. Using python interpreter, I figured out value for rather cryptic parameter, *value_types. This means that pylist faker accepts variable list of parameters:
from faker import Faker
fake = Faker()
fake.pylist(10, True, ‘str’)
Which always gives list of strings.
In FactoryBoy this is:
factory.Faker(‘pylist’, nb_elements=10, variable_nb_elements=True, value_types=’str’)
factory.Faker(‘pylist’, nb_elements=10, variable_nb_elements=True, vlaue_types=’str’, value_types=’int’)