Python:模拟上下文管理器

时间:2015-03-04 08:50:07

标签: python mocking

我不明白为什么我不能在这个例子中模拟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'

5 个答案:

答案 0 :(得分:76)

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

mock_tmp.return_value.__enter__.return_value.name = mytmpname

您的测试将有效。

答案 1 :(得分:1)

这里是pytestmocker 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

答案 2 :(得分:1)

我将 hmobrienv 的回答扩展到一个小型工作程序

import tempfile
import pytest


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"


if __name__ == "__main__":
    pytest.main(args=[__file__])

答案 3 :(得分:0)

使用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'

答案 4 :(得分: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