我正在为视图PersonRemoveView
创建一个单元测试,只需在名为deletion_date
的模型中修改名为Person
的日期时间字段。在执行此视图之前,此字段为None
,然后将其设置为timezone.now()
问题是从单元测试中执行视图后deletion_date
的值为None
。
这是测试:
def test_person_remove_view(self):
person = models.Person.objects.get(pk=1)
request = self.factory.post('/person/remove/{}'.format(person.id))
response = PersonRemoveView.as_view()(request, pk=person.id)
self.assertIsNotNone(person.deletion_date)
这是观点:
class PersonRemoveView(PermissionRequiredMixin, generic.DeleteView):
model = Person
success_url = reverse_lazy('control:person_list')
def dispatch(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.deletion_date = timezone.now()
self.object.save()
return HttpResponseRedirect(self.success_url)
我一直在调试,dispatch
方法按预期执行,但临时测试数据库没有改变,assertIsNotNone
方法失败
答案 0 :(得分:2)
在测试中,您从数据库中获取Person实例,然后执行修改数据库的视图,而不是之前检索的对象。执行视图后,您需要调用public function getEvents($notification) {
$tmp = array();
if ($notification["not_type"] == 16) {
$event = $this->getSingleEvent($notification["not_data"]); // required param is id of event
} else {
$event = $this->getSingleEvent($notification["source_id"]); // required param is id of event
}
// If event exists, get event details, otherwise, just skip it
if ($event["id"] != NULL) {
..... }
}
(documentation),以便从数据库中获取最新的更改。
答案 1 :(得分:1)
模型实例未共享,因此您必须在测试中重新加载实例,以确定视图是否正确更改了基础数据库记录:
def test_person_remove_view(self):
person = models.Person.objects.get(pk=1)
request = self.factory.post('/person/remove/{}'.format(person.id))
response = PersonRemoveView.as_view()(request, pk=person.id)
# reloads our instance values from the database
person.refresh_from_db()
self.assertIsNotNone(person.deletion_date)