简体   繁体   English

如何模拟/修补.endswith()?

[英]How to mock/patch .endswith()?

I have a function I'm trying to test that makes use of the .endswith function, but every time I try to mock it using patch I get an error. 我有一个要尝试使用.endswith函数的函数,但是每次尝试使用补丁模拟它时,都会出现错误。

with patch("killme.endswith",MagicMock()) as mock_endswith

I've tried replacing killme.endswith with the following: 我尝试用以下命令替换killme.endswith

  • killme.UserString.endswith
  • killme.__builtin__.endswith
  • killme.__builtin__.str.endswith
  • killme.str.endswith

killme.py killme.py

def foo(in_str):
 if in_str.endswith("bob"):
     return True
 return False`

killme_test.py killme_test.py

import killme
import unittest
from mock import MagicMock, patch


class tests(unittest.TestCase):
    def test_foo(self):
        with patch("killme.endswith", MagicMock()) as mock_endswith:
            mock_endswith.return_value = True
            result = killme.foo("xxx")
            self.assertTrue(result)

Error: 错误:

Traceback (most recent call last):
  File "C:\Python27\lib\unittest\case.py", line 329, in run
    testMethod()
  File "C:\Users\bisaacs\Desktop\gen2\tools\python\killme_test.py", line 8, in test_foo
    with patch("killme.endswith", MagicMock()) as mock_endswith:
  File "C:\Python27\lib\site-packages\mock\mock.py", line 1369, in __enter__
    original, local = self.get_original()
  File "C:\Python27\lib\site-packages\mock\mock.py", line 1343, in get_original
    "%s does not have the attribute %r" % (target, name)
AttributeError: <module 'killme' from 'C:\Users\bisaacs\Desktop\gen2\tools\python\killme.py'> does not have the attribute 'endswith'

endswith is a builtin str method so you cant simply override it by killme.endswith . endswith是内置的str方法,因此您不能简单地通过killme.endswith覆盖它。 Instead of this you can pass mock object into foo function. 取而代之的是,您可以将模拟对象传递给foo函数。 This object would have the same interface like str but mocked startswith method 该对象将具有与str相同的接口,但模拟了startswith方法

mocked_str = Mock()
mocked_str.endswith.return_value = True # or something else you want
mocked_str.endswith('something') # True or something else

killme.foo(mocked_str)

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

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