'Mocking variable in method

I have DRF API view function to create a new Message:

class MessageCreate(generics.CreateAPIView):
    """Create new message by thread id."""

    serializer_class = MessageNewSerializer
    queryset = Message.objects.all()

    def post(self, request, *args, **kwargs):
        """Check that logged-in user is thread."""
        thread = Thread.objects.filter(pk=request.data["thread"]).first().participants.all()
        user = self.request.user
        request.data["sender"] = user.id #need to mock user.id with return value = 2
        if not user in thread:
            raise ValidationError("You are not in this thread.")
        return self.create(request, *args, **kwargs)

For testing, I need to mock (user.id) with return value = 2. But I can not understand how to implement this.

class TestMessageCreate(unittest.TestCase):
    def setUp(self):
        """Create Theread with two partisipants. Create two users."""
        self.user = User.objects.create_user(email="[email protected]", password="test")
        self.user2 = User.objects.create_user(email="[email protected]", password="test2")
        self.thread = Thread.objects.create()

    def test_message_create(self):
        """Create new Message."""
        data = {"text": "from_test", "sender": self.user.id, "thread": self.thread.id}
        url = reverse("message-create")
        response = self.client.post(url, data=data, format='json')
        print(response.json())
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)


Solution 1:[1]

Explanation

I think what you need is to authenticate the user in the test so that request.user will return the user that you want.

Solution

You can achieve this by using APIClient.force_authenticate or APIClient.login.

def test_message_create(self):
    ...
    # add this line
    self.client.force_authenticate(user=self.user2)
    response = self.client.post(url, data=data, format='json')
    ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 annonymous