from models import MyModel
def myFunc():
#Query 1
queryset_exists = MyModel.objects.filter(id=0).exists())
#Query 2
queryset_exists = MyModel.objects.filter(id=0)
return True
from models
from func_to_test import myFunc
from unittest.mock import MagicMock, patch, Mock
class TestMyFunction(unittest.TestCase):
@patch('models.MyModel.objects')
def test_myFunc(self, mymodel_alias):
# Creating mock object for filter query response
MyModel_Obj = MagicMock(spec=MyModel)
MyModel_Obj.id=1
mymodel_alias.filter.return_value = [MyModel_Obj]
mymodel_alias.filter.return_value.exists.return_value = True
self.assertEqual(myFunc(), True)
mymodel_alias.filter.return_value.exists.return_value = True AttributeError:“列表”对象没有“存在”属性
如果我们将以下内容更改为 mymodel_alias.filter.return_value = [MyModel_Obj] ====到==== mymodel_alias.filter.return_value = MyModel_Obj
提高AttributeError(“模拟对象没有属性%r”%名称) AttributeError:模拟对象没有“存在”属性