I have a view function similar to
def my_function(request):
session = create_something('some_random_string')
return redirect(session.url, code=303)
To test it
import unittest
from django.test import TestCase
from unittest.mock import patch
from my_app.views import my_function
class TestMyFunction(TestCase):
@patch('my_app.views.create_something', return_value={
"url": "https://tiagoperes.eu/"
})
def test_my_function(self, mock_create_something):
response = self.client.get("/my-function/")
This gives
AttributeError: 'dict' object has no attribute 'url'
This question is similar the following questions
redirect()
that takes dynamic values coming from the mocked function, so can also reach easily the error TypeError: quote_from_bytes() expected bytes
)return_value
I'd get TypeError: expected string or bytes-like object
)I had to substitute the return_value in patch to use MagicMock
@patch('my_app.views.create_something', return_value=MagicMock(url="https://tiagoperes.eu"))