从查找表创建测试对象的更好方法?

时间:2014-05-14 15:50:42

标签: python django unit-testing factory-boy

有没有更好的方法来创建测试对象来表示Django应用程序中的PostgreSQL查找表?我有三个表,第一个是来自django.contrib.auth.models的User模型。第二个表是UserAccount,它与User:

具有一对一的关系
# models.py
class UserAccount(models.Model):
    user = models.OneToOneField(User, primary_key=True, unique=True)
    user_type = models.ForeignKey('UserType')

第三个表是与UserAccount具有1对多关系的查找表。它存储UserAccount引用的用户类型,并预先填充了注释中显示的三行:

# models.py
class UserType(models.Model):
    user_type_cd = models.CharField(max_length=4)  # 'cpl', 'sm', 'sf'
    descrip = models.CharField(max_length=75)      # 'couple', 'single male', 'single female'

我正在使用factory_boy代表我的测试用户:

# factories.py
import factory
from django.contrib.auth.models import User

class UserFactory(factory.django.DjangoModelFactory):
    FACTORY_FOR = User
    username = 'testuser'
    email = 'testuser@example.com'
    password = 'testpass'

这是我的测试:

# model_tests.py
from django.contrib.auth.models import User
from django.test import TestCase
from tests.signup.factories import UserFactory
from app.models import UserAccount, UserType

class TestUserAccountModel(TestCase):

    def setUp(self):
        self.user = UserFactory.build()
        self.user_type = UserType.objects.get(user_type_cd='cpl')  # <= hits the database!

    def test_valid_user_account(self):
        ua = UserAccount(user=self.user, user_type=self.user_type)
        self.assertTrue(isinstance(ua, UserAccount))

我对此测试的问题是它运行缓慢,因为我必须在setUp中点击数据库以查找用户类型。我不能用工厂代表UserType类(我不认为),因为它已经填充了。有没有更好的方法来构建这个测试,特别是一个能让它运行得更快的测试?这应该是一个单元测试,所以我希望它尽可能快地运行。感谢。

0 个答案:

没有答案