Testing From Trenches: How To Fake A Python List In FactoryBoy Using Faker

Image for post
Image for post

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>

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 provider s:

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.

Written by

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store