How to use a Faker value as part of another field with FactoryBoy
Asked Answered
C

2

5

I'm using FactoryBoy and Faker to generate some models for unit tests. Generating data for fields is easy enough, but how to I generate a string that incorporates a value produced from a Faker provider?

import factory
import MyModel

class MyFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = MyModel
        # my_ip will be a temporary variable that is not returned by the factory.
        exclude = (my_ip,)

    my_ip = factory.Faker("ipv4_private")
    my_string = f"String with IP address [{my_ip}]"

Using MyFactory then creates objects with my_string set to something like:

String with IP address [<factory.faker.Faker object at 0x7fc656aa6358>]

How can I get my_string to contain something like:

String with the IP address [192.168.23.112]

How do I resolve this to a value, rather than just getting the object? I've tried wrapping in str() with no luck. Do I need to use LazyAttribute or LazyFunction or something from FactoryBoy?

Carmina answered 29/7, 2021 at 7:7 Comment(0)
C
6

With some trial and error I figured out this did require using LazyAttribute so the my_string attribute is calculated after the rest of the object is generated.

However, I then discovered this is essentially a duplicate of: In Factory Boy, how to join strings created with Faker?

If anyone is wondering, the way to do this is:

my_string = factory.LazyAttribute(lambda o: f"String with IP address [{o.my_ip}]")
Carmina answered 29/7, 2021 at 7:33 Comment(0)
D
3

Use the Params feature of factory_boy to make the my_ip value available to LazyAttribute without factory_boy trying to set it on the model.

import factory
import MyModel

class MyFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = MyModel

    class Params:
        my_ip = factory.Faker("ipv4_private")

    my_string = factory.LazyAttribute(lambda o: f"String with IP address [{o.my_ip}]")
Drumfish answered 1/4, 2022 at 19:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.