Django 测试没有实现对象

Django test not actualizing object

我有一个 django rest 框架测试,它只是常规 django 测试的包装器,其工作方式完全相同。代码如下所示:

user_created = User.objects.create_user(first_name="Wally", username="farseer@gmail.com", password="1234",
                                            email="farseer@gmail.com")

client_created = Client.objects.create(user=user_created, cart=cart)

data_client_profile["user"]["first_name"] = "Apoc"

response = self.client.put(reverse("misuper:client_profile"), data_client_profile, format="json")

client_created.refresh_from_db()  # Tried this too

self.assertEqual(response.status_code, status.HTTP_200_OK)

self.assertEqual(client_created.user.first_name, data_client_profile["user"]["first_name"])

所以,我想用字典 data_client_profile 中的一些数据更新 client_created 对象,然后 assertEqual client.user.first_name 是 "Apoc"。

这是视图中的代码,我添加了两个 pdb.set_trace(),这不仅仅是粘贴所有代码:

        pdb.set_trace()

        client_existing_user_obj.phone = phone
        client_existing_user_obj.user.email = email
        client_existing_user_obj.user.first_name = first_name # Updating here!
        client_existing_user_obj.user.last_name = last_name
        client_existing_user_obj.user.save()
        client_existing_user_obj.save()
        pdb.set_trace()

第一个 pdb 中断显示:

(Pdb) client_existing_user_obj.user.username
u'farseer@gmail.com'  # Make sure I'm updating the created object
(Pdb) client_existing_user_obj.user.first_name
u'Wally'  # First name is not updated yet

第二个 pdb 中断显示:

(Pdb) client_existing_user_obj.user.first_name
u'Apoc'  # Looks like the first name has being updated!

但是,当测试运行时我得到错误:

self.assertEqual(client_created.user.first_name, data_client_profile["user"]["first_name"])
AssertionError: 'Wally' != 'Apoc'

为什么会失败?我什至打电话给refresh_from_db()。我确认它已在视图中更新,但在测试中它看起来没有。没看懂。

这是您需要从数据库刷新的用户,因为这是您要修改的对象:

user_created.refresh_from_db()

请注意 refresh_from_db 的文档说 client_created.user 不会被 client_created.refresh_from_db() 刷新,因为 client_created.user_id 保持不变:

The previously loaded related instances for which the relation’s value is no longer valid are removed from the reloaded instance. For example, if you have a foreign key from the reloaded instance to another model with name Author, then if obj.author_id != obj.author.id, obj.author will be thrown away, and when next accessed it will be reloaded with the value of obj.author_id.

因此你需要刷新client_created.user:

client_created.user.refresh_from_db()

或自己重新获取client_created

client_created = Client.objects.get(pk=client_created.pk)