Mocking Django query using Mox

955 Views Asked by At

I'm trying to mock a django filter query using Mox. I am following the instructions on Mox website, however, since my django query is a chained method, it complains that the AndReturn() method doesn't exist.

Here is my method:

def CheckNameUniqueness(device):
    ex_device = device.__class__.objects.filter(name__iexact=device.name)
    if not ex_device:
        return None
    if ex_device.count() > 0:
        return ex_device

In my unit test, I'm trying to mock the filter method to return an empty list.

class testCheckNameUniqeness(unittest.TestCase):
    """ Unit test for CheckNameUniqueness function """

    def setUp(self):
        self.device_mocker = mox.Mox()

    def testCheckNameUniqenessNotExists(self):

        device = self.device_mocker.CreateMock(models.Device)
        device.name = "some name"
        device.objects.filter(name__iexact=device.name).AndReturn(None)

        # Put all mocks created by mox into replay mode
        self.device_mocker.ReplayAll()

        # Run the test
        ret = CheckNameUniqueness(device)
        self.device_mocker.VerifyAll()
        self.assertEqual(None, ret)

When I run my test case, I get the following error: AttributeError: 'QuerySet' object has no attribute 'AndReturn'

Note that, because of the large number of database tables, oracle database, and other complications, this unit test has to be run without creating database.

2

There are 2 best solutions below

0
On

I ran into this same problem.

def testCheckNameUniqenessNotExists(self):
    self.device_mocker.StubOutWithMock(models.Device, "objects")

    models.Device.objects.filter(name__iexact=device.name).AndReturn(None)

    # Put all mocks created by mox into replay mode
    self.device_mocker.ReplayAll()

    # Run the test
    ret = CheckNameUniqueness(device)
    self.device_mocker.VerifyAll()
    self.assertEqual(None, ret)

If you want to chain QuerySets, you can make a mock of a QuerySet and have it be the return:

from django.db.models.query import QuerySet

def testCheckNameUniqenessNotExists(self):
    qs = self.device_mocker.CreateMock(QuerySet)
    self.device_mocker.StubOutWithMock(models.Device, "objects")

    models.Device.objects.filter(name__iexact=device.name).AndReturn(qs)
    qs.count().AndReturn(1)

    # Put all mocks created by mox into replay mode
    self.device_mocker.ReplayAll()

    # Run the test
    ret = CheckNameUniqueness(device)
    # etc...
0
On

Wouldn't it be

device.CheckNameUniqueness().AndReturn(None) 

? That's how I read the Mox documentation. I haven't actually used it myself yet though.