I don\'t understand why I can\'t mock NamedTemporaryFile.name in this example:
from mock import Mock, patch
import unittest
import tempfile
def myfunc():
Here is an alternative with pytest and mocker fixture, which is a common practice as well:
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