Django unittest function with redirect based on mock return_value
Asked Answered
I

1

1

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

Illegitimacy answered 14/11, 2022 at 18:23 Comment(0)
I
0

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"))
Illegitimacy answered 14/11, 2022 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.