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.
I ran into this same problem.
If you want to chain QuerySets, you can make a mock of a QuerySet and have it be the return: