###前提・実現したいこと
PythonのUnitテストを作成しております。
urlopen()を使用している部分の異常時ケースのテストを作成したく思います。
mock.patchを使ってurlopen()をダミー関数に置き換えるようにしました。
しかし、import文の書き方によって、うまくmockに置き換わらない場合がありました。
これはmockの仕様なのでしょうか?それとも自分の記述方法が良くないためでしょうか?
お詳しい方、ご教示いただけますでしょうか?
###テスト失敗時
テスト対象
python
1# terateil_q/my_urlopen.py 2from urllib.request import urlopen # this is test NG 3 4def my_urlopen_1(): 5 6 url = "https://www.google.co.jp/" 7 response = urlopen(url) 8 9 if response.getcode() == 200: 10 return True 11 else: 12 return False
テストケース
python
1#terateil_q/test_my_urlopen.py 2from unittest import mock 3from unittest import TestCase 4from terateil_q.my_urlopen import * 5 6class MyUrlopenTests(TestCase): 7 def test_my_urlopen_normal(self): 8 retval = my_urlopen_1() 9 self.assertTrue(retval) # test pass 10 11 def test_my_urlopen_codeerror2(self): 12 def dummy_urlopen(*args, **kwargs): 13 """ urlopen mock 14 :return HTTPRespnse duck typing 15 """ 16 class Dummy_response(): 17 def __init__(self): 18 self.code = 404 19 20 def getcode(self): 21 return self.code 22 23 return Dummy_response() 24 25 with mock.patch("urllib.request.urlopen", side_effect=dummy_urlopen) as m: 26 retval = my_urlopen_1() 27 self.assertFalse(retval) # test NG / AssertionError: True is not false
pdbでトレースした所、urlopenがmockに置き換わっておりませんでした。
そのため普通にurlopenが動いて、retvalがTrueとなり、結果として、テストがNGとなりました。
###うまくいったパターン1
インポートタイミングを変えるとtest passしました。動的インポートなので実行速度的に気分悪いです。
python
1# terateil_q/my_urlopen.py 2def my_urlopen_1(): 3 from urllib.request import urlopen # change import timeng / this is test OK 4 5 url = "https://www.google.co.jp/" 6 response = urlopen(url) 7 8 if response.getcode() == 200: 9 return True 10 else: 11 return False
###うまくいったパターン2
import宣言を変えてもtest passしました。importにトップレベルパッケージを指定しました。
関数呼び出し部分が非常に残念になってしまいました・・・。
python
1# terateil_q/my_urlopen.py 2import urllib # change this 3 4def my_urlopen_1(): 5 6 url = "https://www.google.co.jp/" 7 response = urllib.request.urlopen(url) # kanasii call 8 9 if response.getcode() == 200: 10 return True 11 else: 12 return False
この方法を毎回使わないといけないでしょうか?
テスト対象をテスト用に変更しなければならないというのは、なんか残念な感じがしております。
###補足情報(言語/FW/ツール等のバージョンなど)
Python3
PyCharm
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/11/24 07:09