我不明白为什么无法在此示例中模拟NamedTemporaryFile.name:
from mock import Mock, patch
import unittest
import tempfile
def myfunc():
with tempfile.NamedTemporaryFile() as mytmp:
return mytmp.name
class TestMock(unittest.TestCase):
@patch('tempfile.NamedTemporaryFile')
def test_cm(self, mock_tmp):
mytmpname = 'abcde'
mock_tmp.__enter__.return_value.name = mytmpname
self.assertEqual(myfunc(), mytmpname)
测试结果在:
AssertionError: <MagicMock name='NamedTemporaryFile().__enter__().name' id='140275675011280'> != 'abcde'