单元测试与Django模型和很多关系涉及 [英] Unit Testing with Django Models and a lot of relations involved

查看:71
本文介绍了单元测试与Django模型和很多关系涉及的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



顺便提一下,这里有一个非常相似的问题:
如何使用外键测试Django中的模型



我试图跟踪使用框架Django的项目的TDD方法。我正在创建和测试模型及其功能(保存方法,信号,...)
和其他依赖于模型的高级功能。



我知道单元测试必须尽可能隔离,但是我发现自己的
为每个测试创建了很多表和关系,使用FactoryBoy,所以我的测试不够强大,因为如果某些模型发生变化,很多测试可能会被破坏。



如何避免所有这些依赖关系,使测试更清晰?



你们建议在实际测试之前避免所有样板?



最佳做法是什么?

解决方案

没有用于测试的最佳做法列表,很多 em>和您正在处理的特定项目。我同意pyriku他说:


你不应该根据你想要测试的方式来设计软件


但是,如果你有一个很好的模块化软件设计,我会添加,应该是容易测试正确。



我最近在我的工作中进行了单元测试,我在Python中发现了一些有趣和有用的工具, FactoryBoy 是这些工具之一,而不是在测试类的setUp()方法中准备很多对象,您可以为每个模型定义工厂,并在需要时批量生成。



您还可以尝试使用嘲笑者,它是一个用于模拟对象的库,因为在Python中所有是一个对象,您可以模拟函数也是如此,如果您需要测试一个在一天的特定时间生成X事件的函数,例如,在上午10:00发送消息,则会写入datetime.date的模拟time.now()总是返回10:00am,并使用调用该功能



如果还需要测试一些前端或您的测试需要一些人工交互(例如在执行OAuth时),您可以使用 Selenium 填写并提交表单。



在您的情况下,要准备与FactoryBoy关系的对象,您可以尝试覆盖Factory._prepare()方法,让我们用这个简单的django模型:

  class Group(models.Model):
name = models.CharField(max_length = 128)
members = models.ManyToManyField(User,blank = True,null = True )

#...

现在,我们来定义一个简单的UserFactory:

  class UserFactory(factory.Factory):
FACTORY_FOR =用户

first_name =' Foo'
last_name = factory.Sequence(lambda n:'Bar%s'%n)
username = factory.LazzyAttribute(lam bda obj:'%s。%s'%(obj.first_name,obj.last_name))

现在,我们想要或需要我的工厂生成有5个成员的组,GroupFactory应该看起来像这样

  class GroupFactory (factory.Factory):
FACTORY_FOR = Group

name = factory.Sequence(lambda n:'Test Group%s'%n)

@classmethod
def _prepare(cls,create,** kwargs):
group = super(GroupFactory,cls)._ prepare(create,** kwargs)
for _ in range(5):
group.members.add(UserFactory())
返回组

希望这有帮助,或至少给你一个光。在这里,我将留下一些与我提到的工具相关资源的链接:



工厂男孩: https://github.com/rbarrois/factory_boy



Mocker: http://niemeyer.net/mocker



Selenium: http://selenium-python.readthedocs.org/en/latest/index.html



另一个关于测试的有用线程:



测试不同层的最佳做法是什么?在Django?


Or, "How to design your Database Schema for easy Unit testing?"

By the way, there is a very similar question to this here: How to test Models in Django with Foreign Keys

I'm trying to follow TDD methodology for a project that uses the framework Django. I'm creating and testing models and its functionality (save methods, signals,...) and other high level functions that relies on the models.

I understand that unit testing must be as isolated as possible but I find myself creating a lot of tables and relations using FactoryBoy for each test, so my test is not strong enough because if something changes in a model many tests could be broken.

How to avoid all these dependencies and make the test cleaner?

What do you guys recommend to avoid all that boilerplate before the actual test?

What are the best practices?

解决方案

There is no list of best practices for testing, it's a lot of what works for you and the particular project you're working on. I agree with pyriku when he says:

You should not design your software basing on how you want to test it

But, I would add that if you have a good and modular software design, it should be easy to test properly.

I've been recently a little into unit testing in my job, and I've found some interesting and useful tools in Python, FactoryBoy is one of those tools, instead of preparing a lot of objects in the setUp() method of your test class, you can just define a factory for each model and generate them in bulk if needed.

You can also try Mocker, it's a library to mock objects and, since in Python everything is an object, you can mock functions too, it is useful if you need a test a function that generates X event at a certain time of the day, for example, send a message at 10:00am, you write a mock of datetime.datetime.now() that always returns '10:00am' and call that function with that mock.

If you also need to test some front-end or your test needs some human interaction (like when doing OAuth against ), you have those forms filled and submitted by using Selenium.

In your case, to prepare objects with relations with FactoryBoy, you can try to overwrite the Factory._prepare() method, let's do it with this simple django model:

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(User, blank=True, null=True)

    # ...

Now, let's define a simple UserFactory:

class UserFactory(factory.Factory):
    FACTORY_FOR = User

    first_name = 'Foo'
    last_name = factory.Sequence(lambda n: 'Bar%s' % n)
    username = factory.LazzyAttribute(lambda obj: '%s.%s' % (obj.first_name, obj.last_name))

Now, let's say that I want or need that my factory generates groups with 5 members, the GroupFactory should look like this

class GroupFactory(factory.Factory):
    FACTORY_FOR = Group

    name = factory.Sequence(lambda n: 'Test Group %s' % n)

    @classmethod
    def _prepare(cls, create, **kwargs):
        group = super(GroupFactory, cls)._prepare(create, **kwargs)
        for _ in range(5):
            group.members.add(UserFactory())
        return group

Hope this helps, or at least gave you a light. Here I'll leave some links to resources related with the tools I mentioned:

Factory Boy: https://github.com/rbarrois/factory_boy

Mocker: http://niemeyer.net/mocker

Selenium: http://selenium-python.readthedocs.org/en/latest/index.html

And another useful thread about testing:

What are the best practices for testing "different layers" in Django?

这篇关于单元测试与Django模型和很多关系涉及的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆