django-测试factory
2018-02-27 本文已影响99人
abelweiwencai
参考文档: http://factoryboy.readthedocs.io/en/latest/
创建
- model放在
meta
里面, 然后写字段 - 三种创建方法,build(创建instance不保存),create 创建instance并且保存(默认),stub 不创建instance返回属性
- UserFactory() 等同于 UserFactory.craeate()
- 批量创建 UserFactory.build_batch()
import factory
from . import models
class UserFactory(factory.Factory):
class Meta:
model = models.User
first_name = 'John'
last_name = 'Doe'
admin = False
切实的,随机值 faker
- first_name = factory.faker('first_name')
惰性属性
大多数值可以直接固定,但是有一些值是要在创建instance的时候计算出来的,
- factory.lazyAttribute()
- factory.lazyFunction()
factory.lazyAttribute会传递一个自身的instance作为参数进去使用,而factory.lazyFunction则没有传递参数
class UserFactory(factory.Factory):
class Meta:
model = models.User
first_name = 'Joe'
last_name = 'Blow'
email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower())
date_joined = factory.LazyFunction(datetime.now)
Sequences序列
对于一些unique的字段,可以用序列来避免重复
class UserFactory(factory.Factory):
class Meta:
model = models.User
email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n))
关联
有一些字段是需要他们自己定义factory的,比如外键。这个时候使用subfactory
class PostFactory(factory.Factory):
class Meta:
model = models.Post
author = factory.SubFactory(UserFactory)
ROM支持,不同行框架的使用
- Django, with factory.django.DjangoModelFactory
- Mogo, with factory.mogo.MogoFactory
- MongoEngine, with factory.mongoengine.MongoEngineFactory
- SQLAlchemy, with factory.alchemy.SQLAlchemyModelFactory
debug
with factory.debug():
obj = TestModel2Factory()
import logging
logger = logging.getLogger('factory')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
使用数据库里面的外键
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.User
language = factory.Iterator(models.Language.objects.all())
特殊函数
- setup():每个测试函数运行前运行
- teardown():每个测试函数运行完后执行
- setUpClass():必须使用@classmethod 装饰器,所有test运行前运行一次
- tearDownClass():必须使用@classmethod装饰器,所有test运行完后运行一次
- setUpTestData():这个testcase开始的时候运行一次