0
0

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 unittest】mockでリストを返してもらうときの注意

Posted at

##概要
Pythonでmock使ってテスト書いてたら、リスト返してもらうところでちょっとはまったのでメモ

##mock.return_valueは参照を返す

Mockにreturn_valueとしてリストを設定

#from unittest.mock import Mock を省略しています
>>> mc = Mock()
>>> mc.return_value = [0,1,2]
>>> mc()
[0, 1, 2]

Mockを呼び出して、返り値を編集する

>>> test = mc()
>>> test
[0, 1, 2]
>>> test[0]=9
>>> test
[9, 1, 2]

もう一回モックを呼び出すと

>>> test = mc()
>>> test
[9, 1, 2]
#[0,1,2]がほしかった

うーん
ちなみにこういうことをしてもだめ

>>> import copy
>>> mc.return_value = copy.deepcopy([0,1,2]) #ついでにlambda:[0,1,2]もだめ
>>> test = mc()
>>> test
[0, 1, 2]
>>> test[0] = 99
>>> test
[99, 1, 2]
>>> test=mc()
>>> test
[99, 1, 2]

##side_effectに関数を設定しましょう

>>> mc = Mock()
>>> mc.side_effect = lambda:[0,1,2]
>>> test = mc()
>>> test
[0, 1, 2]
>>> test[0]=9
>>> test
[9, 1, 2]
>>> test = mc()
>>> test
[0, 1, 2]

とりあえずよかった。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?