简体   繁体   中英

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.

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

I've tried replacing killme.endswith with the following:

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

killme.py

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

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 . Instead of this you can pass mock object into foo function. This object would have the same interface like str but mocked startswith method

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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