mock file open in python

前端 未结 2 1866
天命终不由人
天命终不由人 2021-02-19 06:34

I\'m trying to mock file open, and all of the examples show that I need to

@patch(\'open\', create=True) 

but I keep getting

         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 07:37

    You need to include a module name; if you are testing in a script, the name of the module is __main__:

    @patch('__main__.open')
    

    otherwise use the name of the module that contains the code you are testing:

    @patch('module_under_test.open')
    

    so that any code that uses the open() built-in will find the patched global instead.

    Note that the mock module comes with a mock_open() utility that'll let you build a suitable open() call with file data:

    @patch('__main__.open', mock_open(read_data='foo\nbar\nbaz\n'))
    

提交回复
热议问题