Django unittest function with redirect based on mock return_value
Question:
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
- Cannot redirect when Django model class is mocked (in that I’m using the
redirect()
that takes dynamic values coming from the mocked function, so can also reach easily the error TypeError: quote_from_bytes() expected bytes
)
- How to debug patched method with unittest.mock (in that without the
return_value
I’d get TypeError: expected string or bytes-like object
)
Answers:
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"))
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
- Cannot redirect when Django model class is mocked (in that I’m using the
redirect()
that takes dynamic values coming from the mocked function, so can also reach easily the errorTypeError: quote_from_bytes() expected bytes
) - How to debug patched method with unittest.mock (in that without the
return_value
I’d getTypeError: 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"))