12

I have a django view like this

# Django view

from some_module import f2
def f1(request, version):
    # some code

    f2(**kargs)

    # more code
    return HTTPResponse(response)

The function f2 is in another module

# some_module
def f2(**kargs):
    # some code

The Django view is part of an API so, the request and response are in json

How do I :

  1. write a unit test for this function while mocking the request
  2. mock f2, which is a database based function and avoid database connections entirely

EDIT:

The database I am using is Cassandra, so I cannot use django.db

2 Answers 2

22

You can use @mock.patch decorator to mock f2() method in your unittests.

import mock
import some_module
from django.test import TestCase

def mocked_f2(**kargs):
    return 'Hey'

class YourTestCase(TestCase):

    @mock.patch('some_module.f2', side_effect=mocked_f2)
    def test_case(self, mocked):
        print some_module.f2()  # will print: 'Hey'

In this case each time you call f2() in your code, mocked_f2 will be called.

4
  • What if I want to test f1()? Aug 20, 2015 at 11:54
  • 1
    It will mock all the f2() calls, even if you do them vía f1() method Aug 20, 2015 at 13:09
  • 1
    Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. Aug 20, 2015 at 14:02
  • 2
    I reckon the code doesn't need any more explanation
    – scytale
    Aug 20, 2015 at 21:15
2

django supplies some scaffolding for testing - see the docs

as for f2() - you can use fixtures to set up a db. Alternatively use mock to supply a dummy db connection.

1
  • f2() simply writes some data to db. I want it mocked completely inside f1. How do I achieve that? Aug 20, 2015 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.