Home > Software design >  mock queryset in Django unittest
mock queryset in Django unittest

Time:04-23

I have sample code and test:

def outer():
   inner_response = inner(param1)

def inner(something):
    queryset_response = something.object.filter(foo="bar", 
    foo1="bar1") #this should get a reponse when testing.
    response_list = []
    for count, queryset_res in enumerate(queryset_response):
        response_list.append(queryset_response[count].data)
        #get response for data in this line.
    return response_list    

I wanna test this situation using mock and probably return list of queryset using mock if possible.

def setup():
    something = mock.Mock()

def test_outer():
    # what should be done to the below line work so that 
    # response_list.append gets some value.
    something.objects.filter()[0].data = "some string"
    # Also is it possible to return queryset as like shown below.
    something.objects.filter().return_value = <queryset>  # list of objects in queryset.


CodePudding user response:

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.

CodePudding user response:

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)
  • Related