0

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.

mohi666
  • 6,842
  • 9
  • 45
  • 51

2 Answers2

0

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...
Jearil
  • 126
  • 6
0

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.

joel3000
  • 1,249
  • 11
  • 22