簡體   English   中英

如何模擬/修補.endswith()?

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

我有一個要嘗試使用.endswith函數的函數,但是每次嘗試使用補丁模擬它時,都會出現錯誤。

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

我嘗試用以下命令替換killme.endswith

  • 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)

錯誤:

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是內置的str方法,因此您不能簡單地通過killme.endswith覆蓋它。 取而代之的是,您可以將模擬對象傳遞給foo函數。 該對象將具有與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