Python: Mocking a context manager

前端 未结 3 617
广开言路
广开言路 2020-11-30 01:30

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():
           


        
3条回答
  •  执念已碎
    2020-11-30 02:24

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

    mock_tmp.return_value.__enter__.return_value.name = mytmpname
    

    and your test will work.

提交回复
热议问题