简体   繁体   English

Python模拟获取地址而不是return_value

[英]Python Mock getting address instead return_value

I am trying to sub out a call to check a users full name. 我正在尝试取消通话以检查用户的全名。 I have written the below method using mock to do this. 我已经使用模拟编写了以下方法来做到这一点。

def test_UserDisplayName(self):
    appModel = Mock()
    eval = appModel.eval.return_value
    eval.userDisplayName.return_value = 'JohnDoe'
    self._SummaryModel.AppModel = appModel
    actual = self._SummaryModel.UserDisplayName()
    self.assertEqual(actual, 'JohnDoe')

This is the method it is calling. 这是它正在调用的方法。

def UserDisplayName(self):
    return self.AppModel().eval().userDisplayName()

If I attached debugger to the above line and the run it in the shell it works 如果我在上面的行中附加了调试器,并在外壳中运行它,那么它将起作用

[PAUSED] >>> self.AppModel().eval().userDisplayName()
'JohnDoe'
[PAUSED] >>> 

But when the run the test case for it fails as it I am getting the address back rather than the value. 但是当运行它的测试用例失败时,我得到的是地址而不是值。

   ======================================================================
   FAIL: test_UserDisplayName (unittests.model.SummaryModelTest)
   ----------------------------------------------------------------------
   Traceback (most recent call last):
     File "/unittests/summary_model.py", line 112, in test_UserDisplayName
       self.assertEqual(actual, 'JohnDoe')
   AssertionError: <Mock name='mock.userDisplayName()' id='233406864'> != 'JohnDoe'

   ----------------------------------------------------------------------
   Ran 1 test in 0.010s

   FAILED:  (failures=1)

What am I doing wrong? 我究竟做错了什么?

Your code calls AppModel as well, so you need to adjust the other references for that: 您的代码也会调用AppModel ,因此您需要为此调整其他引用:

eval = appModel.return_value.eval.return_value

Demo: 演示:

>>> from unittest.mock import Mock
>>> appModel = Mock()
>>> eval = appModel.return_value.eval.return_value
>>> eval.userDisplayName.return_value = 'JohnDoe'
>>> appModel().eval().userDisplayName()
'JohnDoe'

However, your <Mock name='mock.userDisplayName()' id='233406864'> object shows a name of mock.userDisplayName() which suggests that the return value was produced by using self.AppModel.userDisplayName() directly instead. 但是,您的<Mock name='mock.userDisplayName()' id='233406864'>对象显示了一个名字mock.userDisplayName() ,这表明返回值是直接使用self.AppModel.userDisplayName()生成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM