Python: Mocking a context manager

I don't understand why I can't mock in this example:

    from mock import Mock, patch
    import unittest
    import tempfile

    def myfunc():
        with tempfile.NamedTemporaryFile() as mytmp:

    class TestMock(unittest.TestCase):
        def test_cm(self, mock_tmp):
            mytmpname = 'abcde'
   = mytmpname
            self.assertEqual(myfunc(), mytmpname)

Test results in:

    AssertionError: <MagicMock name='NamedTemporaryFile().__enter__().name' id='140275675011280'> != 'abcde'

You are setting the wrong mock: mock_tmp is not the context manager, but instead returns a context manager. Replace your setup line with: = mytmpname

and your test will work.