Testing From Trenches: How To Fake A Python List In FactoryBoy Using Faker
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.
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.
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>
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’)
Originally published at https://blog.tentamen.eu on June 26, 2019.