Skip to content

Instantly share code, notes, and snippets.

@xuru
Last active July 10, 2020 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xuru/b5c09e2dbf0505cdc489447845b4a729 to your computer and use it in GitHub Desktop.
Save xuru/b5c09e2dbf0505cdc489447845b4a729 to your computer and use it in GitHub Desktop.
Factory boy example
# -*- coding: utf-8 -*-
"""Factories to help in tests."""
import random
from datetime import date
import factory
# noinspection PyPackageRequirements
from faker import Faker
from .database import db
from xxx.controllers import User
from xxx.models.types import GenderType, AccountStatusType, Role, KitStatus, HelixAccountStatus
from tests.flywheel_factory import FlywheelModelFactory
fake = Faker()
BASE_S3_URL = "https://xxxxxxx.s3.amazonaws.com"
class BaseFactory(FlywheelModelFactory):
"""Base factory."""
class Meta:
"""Factory configuration."""
flywheel = db
overwrite = True
class UserFactory(BaseFactory):
"""User factory."""
class Meta:
"""Factory configuration."""
model = User
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
email = factory.Faker("email")
phone = factory.Faker("phone_number")
password = "default"
roles = {Role.user}
terms_of_service = factory.Faker("pybool")
@factory.lazy_attribute
def birth_date(self):
return fake.date_time_between_dates(
datetime_start=date(1998, 1, 1),
datetime_end=date(2013, 1, 1)
).date()
@factory.lazy_attribute
def gender(self):
return random.choice(list(GenderType))
@factory.lazy_attribute
def status(self):
return random.choice(list(AccountStatusType))
@factory.lazy_attribute
def kit_status(self):
return random.choice(list(KitStatus))
@factory.lazy_attribute
def helix_account_status(self):
return random.choice(list(HelixAccountStatus))
@classmethod
def _build(cls, model_class, **kwargs):
password = None
if 'password' in kwargs:
password = kwargs.pop('password')
if 'gender' in kwargs and isinstance(kwargs['gender'], str):
kwargs['gender'] = GenderType[kwargs['gender']]
if 'status' in kwargs and isinstance(kwargs['status'], str):
kwargs['gender'] = AccountStatusType[kwargs['status']]
obj = super(UserFactory, cls)._build(model_class, **kwargs)
if password:
obj.password = password
obj.image_name = "{}.png".format(obj.identity)
obj.picture = "{}/{}.png?Signature={}&AWSAccessKeyId={}&Expires={}".format(
BASE_S3_URL,
obj.identity,
fake.pystr(min_chars=27, max_chars=27),
fake.pystr(min_chars=20, max_chars=20),
"1476319600" # TODO: make this something a bit more realistic...
)
return obj
from factory import base
class FlywheelOptions(base.FactoryOptions):
def _build_default_options(self):
return super(FlywheelOptions, self)._build_default_options() + [
base.OptionDefault('flywheel', None, inherit=True),
base.OptionDefault('overwrite', False, inherit=True)
]
class FlywheelModelFactory(base.Factory):
"""Factory for Flywheel models. """
_options_class = FlywheelOptions
class Meta:
abstract = True
@classmethod
def _build(cls, model_class, **kwargs):
obj = model_class(**kwargs)
return obj
@classmethod
def _create(cls, model_class, **kwargs):
"""Create an instance of the model, and save it to the database."""
engine = cls._meta.flywheel.engine
obj = super(FlywheelModelFactory, cls)._build(model_class, **kwargs)
engine.save(obj, overwrite=cls._meta.overwrite)
return obj
# -*- coding: utf-8 -*-
"""Model unit tests."""
import datetime as dt
import pytest
from xxx.models import User
from tests.factories import UserFactory
@pytest.mark.usefiures('db')
class TestUser:
"""User tests."""
def test_get_by_id(self):
"""Get user by ID."""
user = UserFactory()
retrieved = User.get_by_id(user.identity)
assert retrieved == user
def test_created_defaults_to_datetime(self):
"""Test creation date."""
user = UserFactory()
assert bool(user.created)
assert isinstance(user.created, dt.datetime)
def test_password_is_not_nullable(self):
"""Test null password."""
user = UserFactory()
user.password = 'bob'
user.save(overwrite=True)
hash = user.password_hash
user.password = None
user.save(overwrite=True)
assert hash == user.password_hash
def test_check_password(self):
"""Check password."""
user = UserFactory(password="fizbuzz")
assert user.is_password_valid('fizbuzz') is True
assert user.is_password_valid('bob') is False
def test_full_name(self):
"""User full name."""
user = UserFactory(first_name='Foo', last_name='Bar')
assert user.full_name == 'Foo Bar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment