django-测试factory

2018-02-27  本文已影响99人  abelweiwencai

参考文档: http://factoryboy.readthedocs.io/en/latest/

创建

import factory
from . import models

class UserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = 'John'
    last_name = 'Doe'
    admin = False

切实的,随机值 faker

惰性属性

大多数值可以直接固定,但是有一些值是要在创建instance的时候计算出来的,

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支持,不同行框架的使用

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())

特殊函数

上一篇下一篇

猜你喜欢

热点阅读