I'm new to testing in Django and I was wondering how to write tests for signals.
I went over the documentation but I couldn't find anything helpful.
我刚接触Django测试,我想知道如何编写信号测试。我查看了文档,但找不到任何有用的信息。
Let's say a have a simple pre_save
signal for Reservation
model and I want to change some attribute before saving it to the database.
假设有一个简单的pre_save信号用于Reservation模型,我想在保存到数据库之前更改一些属性。
My code looks like this:
我的代码如下所示:
@receiver(pre_save, sender=Reservation)
def set_destination_type(sender, instance, *args, **kwargs):
points = ['New York', 'Rome', 'Paris']
if instance.destination in points:
instance.international = True
instance.international = False
How would I approach this? Do I just create a reservation and assert that correct value was set? Do I test this function in isolation? I really don't know how to start.
我该如何处理?我只是创建一个预订并声明设置了正确的值吗?我是否单独测试此功能?我真的不知道如何开始。
Thanks!
谢谢!
1 个解决方案
#1
1
The easiest is indeed to create some reservations (where some have destination in points, others not), setting destination to 'foo' (for instance) then save them.
确实最简单的是创建一些保留(其中一些具有点的目的地,而另一些没有),将目的地设置为'foo'(例如)然后保存它们。
international seems to be a boolean field, so using 'foo' (which is not a boolean) and saving will allows you to check both cases (and as far as instance is not validated/saved you can assign whatever value you want)
国际似乎是一个布尔字段,因此使用“富”(这是不是一个布尔值),并节省将允许你检查这两种情况下(而据实例未验证/保存您可以指定任何你想要的值)
"Do I test this function in isolation" => I wouldn't do that, the signals framework is heavily coupled to Django models, to get isolation, you would have to mock a lot of libs making your test code far more difficult than the tested code itself
“我是否孤立地测试这个函数”=>我不会这样做,信号框架与Django模型紧密耦合,为了获得隔离,你必须模拟很多lib,使你的测试代码比测试代码本身
#1
1
The easiest is indeed to create some reservations (where some have destination in points, others not), setting destination to 'foo' (for instance) then save them.
确实最简单的是创建一些保留(其中一些具有点的目的地,而另一些没有),将目的地设置为'foo'(例如)然后保存它们。
international seems to be a boolean field, so using 'foo' (which is not a boolean) and saving will allows you to check both cases (and as far as instance is not validated/saved you can assign whatever value you want)
国际似乎是一个布尔字段,因此使用“富”(这是不是一个布尔值),并节省将允许你检查这两种情况下(而据实例未验证/保存您可以指定任何你想要的值)
"Do I test this function in isolation" => I wouldn't do that, the signals framework is heavily coupled to Django models, to get isolation, you would have to mock a lot of libs making your test code far more difficult than the tested code itself
“我是否孤立地测试这个函数”=>我不会这样做,信号框架与Django模型紧密耦合,为了获得隔离,你必须模拟很多lib,使你的测试代码比测试代码本身