Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock module when testing django view

I have a custom function that authenticate a request. I'm trying to mock this module during test but no luck so far

This is my view

from auth_utils import authenticate_request, UnauthenticatedRequest

def my_view(request):
    try:
        authenticate_request(request)
    except UnauthenticatedRequest:
        return Http404()
    return render(request, 'ok.html', {'status': 'ok'})

And in the test i'm trying to mock authenticate_request so it would not raise an error

class TestMyView(MyAPITestCase, TestCase):

    @mock.patch('auth_utils.authenticate_request', side_effect=None)
    def setUp(self, mock_auth):
        self.response = self.client.get(reverse('my-view'))

    def test_should_return_ok(self):
        self.assertEqual(self.response.context.get('status'), 'ok')

Can't make it work. Any suggestions ?

Thanks, Python 2.7, Django 1.8.

like image 758
haki Avatar asked Aug 18 '15 07:08

haki


1 Answers

You need to mock the function authenticate_request where it's imported, not where it's defined.

So, for example, if my_view is defined in myapp/views.py, then authenticate_request is imported into myapp.views. So you want to call something like the following:

@mock.patch('myapp.views.authenticate_request', side_effect=None)
like image 131
Shaun O'Keefe Avatar answered Sep 29 '22 23:09

Shaun O'Keefe