avatarSunil Kumar

Summary

The provided web content discusses the use of factory_boy in Python for creating flexible and dynamic test fixtures in place of static, hard-to-maintain fixtures.

Abstract

The article introduces factory_boy, a Python library designed to facilitate the creation of test fixtures. It emphasizes the benefits of using factory_boy over traditional static fixtures, which are often difficult to maintain. The library allows developers to generate complex objects with dynamic data for testing purposes. The author illustrates the usage of factory_boy by refactoring a test case for an Employee class, initially using a static fixture, and then demonstrating how factory_boy can be used to create a flexible EmployeeFactory that produces instances of Employee with automatically generated data. The article concludes by encouraging readers to explore the factory_boy documentation for more advanced features and applications.

Opinions

  • The author suggests that static fixtures are less desirable due to their inflexibility and maintenance challenges.
  • factory_boy is presented as a superior alternative for creating test data, as it simplifies the process and enhances the flexibility of tests.
  • The author's preference for factory_boy is evident through the demonstration of its ease of use and the dynamic nature of the test data it generates.
  • The article implies that using factory_boy can lead to more robust and maintainable test suites in Python applications.
  • By showcasing a simple example, the author conveys that factory_boy is accessible for beginners while also hinting at the library's potential for handling more complex scenarios.

What is Python factory_boy?

If you are working on building a python-based application, you might have also written unit tests for your programs. You could be aware of fixtures generally used in creating prepare static data for the test. You can learn more about it in my pytest blog.

As per the factory_boy documentation, it is a fixtures replacement tool, it aims to replace static, hard-to-maintain fixtures with easy-to-use factories for complex objects

We can install factory_boy using the below command.

$ pip install factory_boy

Let's see one sample example with fixture and fake created with factory_boy

In the following example, we have created an Employee class with two property methods.

## example2.py
import uuid
from dataclasses import dataclass
@dataclass
class Employee():
    id: uuid.UUID
    first_name: str
    last_name: str
    admin: bool
    address: str
    state:str
    country: str
    phone: str
    email: str
@property 
    def get_employee_name(self):
        return f"{self.first_name} {self.last_name}"
@property 
    def get_employee_email(self):
        return self.email

let's create a test case with a fixture. In the following test, we have created a fixture dummy_employee which created an instance of an Employee class with constant static values.

## test_example2.py
import uuid
import pytest
from src.example2 import  Employee
@pytest.fixture
def dummy_employee():
    return Employee(
        id = "943f4ff1-b5d6-4eeb-82f9-5640b4b7ecdb",
        first_name = "Sunil",
        last_name = "Kumar",
        admin = False,
        address = "address",
        state= "Oregon",
        country= "US",
        phone = "12345678",
        email = "[email protected]",
)
def test_get_employee_name(dummy_employee):
    emp= dummy_employee
    assert emp.get_employee_name == "Sunil Kumar"
def test_get_employee_email(dummy_employee):
    emp= dummy_employee
    assert emp.get_employee_email == "[email protected]"

Output:

Now let's refactor the above code and use the fake created using by factory_boy.

In the following tests, we have imported factory and created a fake EmployeeFactory which inherited factory.Factory class. You can see we are not hard coding any static values for EmployeeFactory. The values of each attribute are created automatically by factory.Faker(). We can the instance EmployeeFactory using its build() method. Each time we call the build() method create an instance of an Employee with different values.

## test_example2.py
import uuid
import factory
import pytest
from src.example2 import  Employee
class EmployeeFactory(factory.Factory):
    class Meta:
        model = Employee
    id = factory.Faker("uuid4")
    first_name = factory.Faker('first_name')
    last_name = factory.Faker('last_name')
    admin = False
    address = factory.Faker('address')
    state= factory.Faker('state')
    country= factory.Faker('country')
    phone = factory.Faker("phone_number")
    email = factory.Faker("safe_email")
def test_get_employee_namewith_fake():
    emp= EmployeeFactory.build()
    assert emp.get_employee_name == f"{emp.first_name} {emp.last_name}"
def test_get_employee_email_with_fake():
    emp= EmployeeFactory.build()
    assert emp.get_employee_email == emp.email

Output:

Conclusion :

In this blog, we have seen how we can use factory_boy to make fake data for testing. It is just a very simple example. You can do lot more with factory_boy. Please visit the documentation.

Reference :

https://github.com/FactoryBoy/factory_boy

Python Programming
Python3
Automation
Test Automation
Unittest
Recommended from ReadMedium