Mock queryset in Django unittest
I have sample code and test:
queryset_response = something.object.filter(foo="bar", foo1="bar1")
for count, queryset_res in enumerate(queryset_response):
store = queryset_response[0].data
print(store)
I wanna test this situation using mock and probably return list of queryset using mock if possible.
m_queryset = Mock()
m_queryset.filter.return_value = #<queryset> if possible
# also I wanna return data for the 0th value to test store = queryset_response[0].data
m_queryset.filter().data.return_value = "some string"
# i tried sending dict into m_qeueryset.filter.return_value. nothing works.
You shouldn't be mocking the result of a filter as that would be like unit testing django itself. Instead, you should be testing your own functions that will call Model.object.filter. You can create the objects you will be working with in the setup of your unit test, and assert that when you call your function, the expected result is the same as those objects. For example:
def my_own_function(foo, foo1):
queryset_response = Something.objects.filter(foo=foo, foo1=foo1)
store = queryset_response[0].data
return store
and in your unit test:
def test_my_own_function():
data = "mydata"
sample_obj = Something.objects.create(foo="bar", foo1="bar1", data=data)
result = my_own_function("bar", "bar1")
self.assertEqual(result, data)
i used a mock and returned namedtuple to make it behave like queryset and use (.) dot to access the data set. I could make a class and used it same way.
def test_func():
something = mock.Mock()
key = collections.namedtuple('key', 'data')
response = key('some_string')
something.objects.filter.return_value = [response]
this is kinda mocking django as gloo said, my ex-engineers decided to opt in that way.