我正在尝试测试我的Celery任务是否更新Django模型。它工作良好,但在测试过程中表现异常。
# someapp/models.py
class SomeModel(models.Model):
...
hidden = models.BooleanField(default=False)
# someapp/tasks.py
@shared_task()
def my_task(model_id):
model_instance = someapp.models.SomeModel.objects.get(id=model_id)
model_instance.hidden = True
model_instance.save()
logger.info(f'Uncovered model instance with id {model_id]')
为了测试这一点,我实现了以下工作流程:
- 我通过工厂男孩工厂创建SomeModel对象,因为SomeModel依赖于多个模型
- 我将此对象分配给变量model_instance
- 我在本地应用任务
- 我断言model_instance.hidden为True
下方的代码
# someapp/tests.py
@pytest.mark.django_db
@pytest.mark.celery(task_always_eager=True)
def test_celery_task_uncovers_model_instance() -> None:
SomeModelFactory.create(hidden=False)
some_model = someapp.models.SomeModel.objects.first()
assert some_model.hidden is True
my_task.apply((some_model.id, ))
assert some_model.hidden is True
在最后一行提高。然后我断言:
assert (model_instance.pk, model_instance.hidden) == (someapp.models.SomeModel.objects.first().pk,
someapp.models.SomeModel.objects.first().hidden)
它提出:
E assert (1, True) == (1, False)
E At index 1 diff: True != False
最后,我想检查ids:
assert id(model_instance) == id(authapp.models.SomeModel.objects.first())
它提出了这样的问题:
E AssertionError: assert 139938217188656 == 139938219885184
E + where 139938217188656 = id(<SomeModel: - 2022-02-01>)
E + and 139938219885184 = id(<SomeModel: - 2022-02-01>)
为什么任务不更新我测试中的some_model
对象?
实例在任务中更新,但在测试中没有,您需要在调用任务后使用Model.refresh_from_db()
从DB刷新实例的数据
@pytest.mark.django_db
@pytest.mark.celery(task_always_eager=True)
def test_celery_task_uncovers_model_instance() -> None:
SomeModelFactory.create(hidden=False)
some_model = someapp.models.SomeModel.objects.first()
assert some_model.hidden is False
my_task.apply((some_model.id, ))
some_model.refresh_from_db() # <<<
assert some_model.hidden is True