From 5bfd073802d9b9b66e0704895851f910e63d8ce1 Mon Sep 17 00:00:00 2001 From: Steven Loria Date: Sat, 19 Apr 2014 01:18:29 -0400 Subject: [PATCH] Add BaseFactory which flushes the db on create --- .../tests/factories.py | 19 +++++++++++++++---- .../{{cookiecutter.app_name}}/user/models.py | 6 ++---- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/tests/factories.py b/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/tests/factories.py index 96d87b8..d70936b 100644 --- a/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/tests/factories.py +++ b/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/tests/factories.py @@ -1,12 +1,23 @@ # -*- coding: utf-8 -*- -from factory import Sequence, PostGenerationMethodCall +from factory import Sequence from factory.alchemy import SQLAlchemyModelFactory -from {{cookiecutter.app_name}}.user.models import User -from {{cookiecutter.app_name}}.database import db +from myflaskapp.user.models import User +from myflaskapp.database import db +class BaseFactory(SQLAlchemyModelFactory): -class UserFactory(SQLAlchemyModelFactory): + @classmethod + def _create(cls, target_class, *args, **kwargs): + """Create an instance of the model, and save it to the database.""" + session = cls.FACTORY_SESSION + obj = target_class(*args, **kwargs) + session.add(obj) + session.commit() + return obj + + +class UserFactory(BaseFactory): FACTORY_SESSION = db.session FACTORY_FOR = User diff --git a/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/user/models.py b/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/user/models.py index 663d917..9345b84 100644 --- a/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/user/models.py +++ b/{{cookiecutter.app_name}}/{{cookiecutter.app_name}}/user/models.py @@ -26,7 +26,7 @@ class User(UserMixin, CRUDMixin, db.Model): username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=True, nullable=False) password = Column(BcryptType, nullable=True) - created_at = Column(db.DateTime, nullable=False) + created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) first_name = Column(db.String(30), nullable=True) last_name = Column(db.String(30), nullable=True) active = Column(db.Boolean(), default=False) @@ -34,12 +34,10 @@ class User(UserMixin, CRUDMixin, db.Model): def __init__(self, username, email, **kwargs): db.Model.__init__(self, username=username, email=email, **kwargs) - if not self.created_at: - self.created_at = dt.datetime.utcnow() @property def full_name(self): return "{0} {1}".format(self.first_name, self.last_name) def __repr__(self): - return ''.format(username=self.username) + return ''.format(username=self.username)