How to create a new model instance every time when factory called

  factory-boy, faker, pytest, python

I have a factoryboy factory for sqlalchemy model which uses faker

from faker import Faker
from db_init import session

fake = Faker()

class ClientAppFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = ClientApp
        sqlalchemy_session = session
        sqlalchemy_session_persistence = 'commit'

    name = fake.word()
    display_name = fake.word()

This factory creates rows in database. Field name of my model must be unique. When I call my factory several times in a row, I get several instances with the same name. How can I get different names in my instances?

import pytest
from pytest_factoryboy import register

register(ClientAppFactory)

@pytest.fixture
def several_client_apps():
    ca1 = client_app_factory()
    ca2 = client_app_factory()

In this case I get error about name field unique constraint.

Source: Python Questions

LEAVE A COMMENT