Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harobed/3002546 to your computer and use it in GitHub Desktop.
Save harobed/3002546 to your computer and use it in GitHub Desktop.
How to fill dict attribute with Factory-boy ?
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.InfiniteIterator([ 'Peggie', 'Gabe', 'King', 'Fredy', 'Ole', 'Vernice' ])
last_name = factory.InfiniteIterator([ 'Leannon', 'Barton', 'Sauer', 'Walker', 'Strosin'])
username = factory.LazyAttribute(
lambda o: '%s.%s@example.com' % (o.first_name.lower(), o.last_name.lower())
)
# How can I feed data in dict, metadata isn't another Entities (MongoDB context)
metadata = {
'a': factory.InfiniteIterator(['foobar', 'foo'])
'b': factory.InfiniteIterator(['foobar', 'foo'])
}
@rbarrois
Copy link

@factory.lazy_attribute_sequence
def metadata(self, seq):
    idx = seq % 2
    return {
        'a': ['foobar', 'foo'][idx],
        'b': ['foobar', 'foo'][idx],
    }

@rbarrois
Copy link

class MetadataFactory(factory.Factory):
    FACTORY_FOR = dict
    a = factory.InfiniteIterator(['foobar', 'foo'])
    b = factory.InfiniteIterator(['foobar', 'foo'])

    @classmethod
    def _prepare(cls, create, *args, **kwargs):
        # HACK: force 'build' mode
        return super(MetadataFactory, cls)._prepare(False, *args, **kwargs)

class UserFactory(factory.Factory):
    metadata = factory.SubFactory(MetadataFactory)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment