【发布时间】:2018-06-08 19:08:20
【问题描述】:
我正在进行的一个项目基本上使用 django 来完成所有工作。在编写模型时,我发现有必要重写 save() 方法来分拆一个由工作人员运行的任务:
class MyModel(models.Model)
def _start_processing(self):
my_task.apply_async(args=['arg1', ..., 'argn'])
def save(self, *args, **kwargs):
"""Saves the model object to the database"""
# do some stuff
self._start_processing()
# do some more stuff
super(MyModel, self).save(*args, **kwargs)
在我的测试器中,我想测试由# do some stuff 和# do some more stuff 指定的保存覆盖部分,但不想运行该任务。为此,我相信我应该使用模拟(我很陌生)。
在我的测试类中,我已将其设置为跳过任务调用:
class MyModelTests(TestCase):
def setUp(self):
# Mock the _start_processing() method. Ha!
@patch('my_app.models.MyModel._start_processing')
def start_processing(self, mock_start_processing):
print('This is when the task would normally be run, but this is a test!')
# Create a model to test with
self.test_object = MyModelFactory()
由于工厂创建并保存了模型的实例,我需要在调用之前覆盖_start_processing() 方法。以上似乎不起作用(并且任务运行并失败)。我错过了什么?
【问题讨论】:
标签: python django unit-testing mocking