2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでopenメソッドをモック化したときにAttributeErrorになった

Posted at

pythonで

open(file_path, 'r')

みたいなのをモック化するとき、テストスクリプトに

if __name__ == '__main__':
    unittest.main()

って書いて直接実行するときは

__builtins__.open = MagicMock()

みたいにしていた。

でもコマンドラインから
$ python -m unittest2 -v test_module
みたいに実行すると
AttributeError: 'dict' object has no attribute 'open'
っておこられる。
このとき

__builtins__['open']

のようにすれば参照できるので、テストコード内で

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

こんなメソッドを作った。。。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?