如何使用python unittest模拟django链式查询

时间:2019-05-08 15:58:53

标签: python django unit-testing

func_to_test.py

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

test.py

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)

--------------------错误1 -------------------------- ---

mymodel_alias.filter.return_value.exists.return_value = True AttributeError:“列表”对象没有“存在”属性

注意

如果我们将以下内容更改为 mymodel_alias.filter.return_value = [MyModel_Obj] ====到==== mymodel_alias.filter.return_value = MyModel_Obj

--------------------错误2 -------------------------- ---

提高AttributeError(“模拟对象没有属性%r”%名称) AttributeError:模拟对象没有“存在”属性

0 个答案:

没有答案