Python:模拟上下文管理器


76

我不明白为什么无法在此示例中模拟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'

Answers:


128

您设置的模拟错误:mock_tmp不是上下文管理器,而是返回了一个上下文管理器。将您的设置行替换为:

mock_tmp.return_value.__enter__.return_value.name = mytmpname

这样您的测试就可以了。


4

使用pytest和嘲讽夹具扩展Peter K的答案。

def myfunc():
    with tempfile.NamedTemporaryFile(prefix='fileprefix') as fh:
        return fh.name


def test_myfunc(mocker):
    mocker.patch('tempfile.NamedTemporaryFile').return_value.__enter__.return_value.name = 'tempfilename'
    assert myfunc() == 'tempfilename'

3

这是pytest嘲笑的fixture的替代方法,也是一种常见的做法:

def test_myfunc(mocker):
    mock_tempfile = mocker.MagicMock(name='tempfile')
    mocker.patch(__name__ + '.tempfile', new=mock_tempfile)
    mytmpname = 'abcde'
    mock_tempfile.NamedTemporaryFile.return_value.__enter__.return_value.name = mytmpname
    assert myfunc() == mytmpname

0

为了扩展Nathaniel的答案,此代码块

with tempfile.NamedTemporaryFile() as mytmp:
    return mytmp.name

有效地做三件事

# Firstly, it calls NamedTemporaryFile, to create a new instance of the class.
context_manager = tempfile.NamedTemporaryFile()  

# Secondly, it calls __enter__ on the context manager instance.
mytmp = context_manager.__enter__()  

# Thirdly, we are now "inside" the context and can do some work. 
return mytmp.name

当您替换为或tempfile.NamedTemporaryFile实例MockMagicMock

# This first line, below, will call mock_tmp().
# Therefore we need to set the return_value with
# mock_tmp.return_value
context_manager = mock_tmp()

# This will call mock_tmp.return_value.__enter__() so we need to set 
# mock_tmp.return_value.__enter__.return_value
mytmp = context_manager.__enter__()

# This will access mock_tmp.return_value.__enter__.return_value.name
return mytmp.name
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.