In python
open(file_path, 'r')
When mocking something like, in a test script
if __name__ == '__main__':
    unittest.main()
When you write and execute it directly
__builtins__.open = MagicMock()
I was like.
But from the command line
$ python -m unittest2 -v test_module
When you run like
AttributeError: 'dict' object has no attribute 'open'
Get angry.
At this time
__builtins__['open']
You can refer to it by doing like, so in the test code
def get_builtins_open(self):
    if __name__ == '__main__':
        return __builtins__.open
    else:
        return __builtins__['open']
def set_builtins_open(self, input):
    if __name__ == '__main__':
        __builtins__.open = input
    else:
        __builtins__['open'] = input
I made a method like this. .. ..
Recommended Posts