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 :
EDIT:
The database I am using is Cassandra, so I cannot use django.db
If you set autospec=True then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. ... So, you need just describe expected data. Also you can mock API using httpretty.
side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.
What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
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):
print some_module.f2() # will print: 'Hey'
In this case each time you call f2()
in your code, mocked_f2
will be called.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With