Skip to content

Instantly share code, notes, and snippets.

@hectorcanto
Created February 8, 2019 16:02
Show Gist options
  • Save hectorcanto/bd919a87a36a19c63f89f908ecc8262c to your computer and use it in GitHub Desktop.
Save hectorcanto/bd919a87a36a19c63f89f908ecc8262c to your computer and use it in GitHub Desktop.
DictFactory for APIs derived from the DB Model Factory
# -*- coding: utf-8 -*-
import random
import string
import unicodedata
from uuid import uuid4
from functools import partial
from _datetime import datetime, timezone
from factory import Factory, Sequence, LazyFunction as LF, LazyAttribute as LA
from factory.fuzzy import FuzzyChoice as Choice
first_names = ["José", "Pedro", "Bruce", "Wade", "Robin", "Walter", "Diana", "James", "Monty"]
last_names = ["Pérez", "Wilson", "Wayne", "Lee", "Kovacs", "Kent", "López", "Howlett"]
def normalize(string):
adapted = string.strip().replace(" ", "_").lower()
return unicodedata.normalize("NFKD", adapted).encode("ascii", "ignore").decode("utf-8")
def random_alphanumeric(length):
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))
class UserFactory(Factory):
ABSTRACT_FATORY = False
class Meta:
abstract = False
"""
class Meta:
model = models.User
If you have a model defined in an ORM, you can import and use it as base
"""
id = LF(uuid4)
member_number = Sequence(lambda n: n)
first_name = Choice(first_names)
last_name = Choice(last_names)
username = LA(lambda obj:
f"{normalize(obj.first_name)}_{normalize(obj.last_name)}{random_alphanumeric(3)}")
email = LA(lambda obj: f"{normalize(obj.first_name)}_{normalize(obj.last_name)}@company.com")
created_at = LF(lambda: datetime.now(tz=timezone.utc))
def dict_factory(factory, **kwargs):
"""We create the factory this way to allow internal mechanism of factory boy to work
"""
return factory.stub(**kwargs).__dict__
UserDictFactory = partial(dict_factory, UserFactory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment