Asked 3 months ago by UranianAdventurer394
How can I retrieve objects created by signals in Django test cases?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 3 months ago by UranianAdventurer394
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I'm writing test cases for my Django notifications view and encountering issues retrieving objects created by signals in the test environment. I have two models: UserNotification and FriendshipRequest. Normally, when a FriendshipRequest object is created, a signal creates a UserNotification object. I need to retrieve that notification (specifically its id) to test my views with URL parameters.
I've verified that the signals are registered correctly and work as expected. The problem is that when I try to retrieve the notification objects in my test functions, I get None
or must manually simulate the signal workflow in setUp()
.
Below is my test code:
PYTHONclass TestAcceptDeclineNotifications(APITestCase): def setUp(self): self.user = Profile.objects.create(firstName='test', lastName='test', email='testexample@email.com', username='testuser', password='password123') self.test_user = Profile.objects.create(firstName='test', lastName='test', email='testexample2@email.com', username='testuser2', password='password123') self.test_user_id = self.test_user.id self.friendship = FriendshipRequest.objects.create(initiator=self.test_user, recipient=self.user, status='pending') self.friend_content_type = ContentType.objects.get_for_model(self.friendship) self.friend_notification = UserNotification.objects.filter(content_type=self.friend_content_type, object_id=self.friendship.id).first() self.friend_notification_id = self.friend_notification.id self.token, _ = Token.objects.get_or_create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token.key}') def test_decline_friendship_view(self): url = reverse('decline_friendship', args=[self.friend_notification_id]) response = self.client.put(url) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_accept_friendship_view(self): url = reverse('accept_friendship', args=[self.friend_notification_id]) response = self.client.put(url) self.assertEqual(response.status_code, status.HTTP_200_OK)
Any advice on how to properly retrieve these signal-created objects in my test environment?
Comments 0
•Answers 0
•Views 37
No comments yet.