時々、グローバル設定に依存する機能のテストを実行する、またはネットワークアクセスを伴うような簡単にテストできないコードを実行する必要があります。 monkeypatch という関数の引数を使うことで、属性、ディクショナリの項目、環境変数、インポートのための sys.path の変更を安全に追加/削除するのを支援します。入門記事とその動機付けの議論は monkeypatch のブログ記事 を参照してください。
os.expanduser が特定のディレクトリを返すようにさせたい場合、関数内で os.expanduser が呼ばれる前にこの関数へパッチを当てるために monkeypatch.setattr() メソッドが使えます:
# test_module.py の内容
import os.path
def getssh(): # 疑似アプリケーションコード
return os.path.join(os.path.expanduser("~admin"), '.ssh')
def test_mytest(monkeypatch):
def mockreturn(path):
return '/abc'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
x = getssh()
assert x == '/abc/.ssh'
このテスト関数は os.path.expanduser にモンキーパッチを当てた後で、ある関数内からその関数が呼ばれます。このテスト関数が終了した後で os.path.expanduser に対する変更は元に戻ります。
object keeping a record of setattr/item/env/syspath changes.
change the current working directory to the specified path path can be a string or a py.path.local object
delete attribute name from target, by default raise AttributeError it the attribute did not previously exist.
If no name is specified and target is a string it will be interpreted as a dotted import path with the last part being the attribute name.
If raising is set to false, the attribute is allowed to not pre-exist.
set attribute value on target, memorizing the old value. By default raise AttributeError if the attribute did not exist.
For convenience you can specify a string as target which will be interpreted as a dotted import path, with the last part being the attribute name. Example: monkeypatch.setattr("os.getcwd", lambda x: "/") would set the getcwd function of the os module.
The raising value determines if the setattr should fail if the attribute is not already present (defaults to True which means it will raise).
monkeypatch.setattr/delattr/delitem/delenv() の全ての関数において、変更対象が存在しない場合にデフォルトで例外を発生させます。このチェック処理をスキップしたいなら raising=False を渡してください。