2017-01-26 2 views
1

장고 휴식 프레임 워크 테스트가 있습니다. 정확히 같은 방식으로 작동하는 일반 장고 테스트보다 래퍼입니다. 코드는 다음과 같습니다장고 테스트가 객체를 구현하지 않습니다.

user_created = User.objects.create_user(first_name="Wally", username="[email protected]", password="1234", 
              email="[email protected]") 

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"]) 

그래서, 그때의 DICT data_client_profileclient.user.first_name는 "에이 팍스"입니다 assertEqual 일부 데이터와 client_created 개체를 업데이트하려고합니다.

 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.set_trace()을 추가 뷰의 코드 두 번째

(Pdb) client_existing_user_obj.user.username 
u'[email protected]' # 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 break는 이것을 보여줍니다 :

(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() 

답변

1

refresh_from_db에 대한 문서가 client_created.userclient_created.refresh_from_db()에 의해 갱신되지 말 것을 때문에 : 그건 당신이 수정하고있는 객체가 이후

그것은 당신이 데이터베이스에서 새로 고침 할 필요가 사용자
2

있어 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) 
관련 문제