Python - unittestã®assertRaisesã®ä½¿ãæ¹
æ°æ¥åããPython2.7ãåå¼·ãå§ãã¦ãã¾ãã
WEBãã¥ã¼ããªã¢ã«ãå°ããã¤ãã£ã¦ãããã§ãããå
å®åº¦ããããã
ãããªè¨³ã§Pythonã«æ¨æºã§å
¥ã£ã¦ããunittestã使ãã
assertRaisesã«ã¦ä¾å¤ã®ãã¹ããæ¸ããã¨ãã¾ããã
(noseã¨ãpy.testã¨ãã®æ¹ã便å©ãããã§ããã
ã¾ãã¯æ¨æºã®ç¶æ
ã§ã¢ã¬ã³ã¬ãããã£ãã®ã§unittestã«ãã¦ã¾ã)
ãããªãµãã«ã
import unittest class MyException(Exception): pass class Target: def something(self): raise MyException class Test(unittest.TestCase): def setUp(self): self.target = Target() def test_exception(self): self.assertRaises(MyException, self.target.something()) if __name__ == '__main__': unittest.main()
ããããã¹ããå®è¡ããã¨å¤±æãã¾ããã
E
======================================================================
ERROR: test_exception (__main__.Test)
- -
Traceback (most recent call last):
File "/Users/kanno/.vim_sandbox/2013-05-01-2014.py", line 15, in test_exception
self.assertRaises(MyException, self.target.something())
File "/Users/kanno/.vim_sandbox/2013-05-01-2014.py", line 8, in something
raise MyException
MyException
- -
Ran 1 test in 0.000s
FAILED (errors=1)
ããã¼ã¨æã£ã¦ã°ã°ã£ããè¦ã¤ãã£ããã¡ãã®ãµã¤ãã
Python/Unittest : assertRaises raises Error | loup2fu
To avoid this error, simply run the function using lambda in the test call :
lambda使ã£ã¡ãããªããã¨ãããã¨ãªã®ã§æ¸ãæãããã¨ã«ã
def test_exception(self): self.assertRaises(MyException, lambda: self.target.something())
ããããéãã¾ããã
.
- -
Ran 1 test in 0.000s
OK
ã§ããªããéããªã¨æãã¤ã¤Twitterã«åããã¨ãã
unittestã®assertRaisesã§æå¾ éãã«ä¾å¤æãã¦ãã®ã«ãã¹ãè½ã¡ã¡ãã£ã¦ä½ã§ã ã£ã¦ãªã£ãã®ã ãã©ãã¨ãããµã¤ãã«lambdaã§ã©ããããã£ã¦ãã£ã¦ç¢ºãã«åãããã©ãããããã®ãªã®ã
@methaneããã«æãã¦é ãã¾ããããããã¨ããããã¾ã!
@kanno_kanno Python ã§ããï¼ assertRaises(Error, spam(a, b)) ã 㨠assertRaises ãå¼ã°ããåã«ãã§ã«ä¾å¤é£ãã§ãã¾ã£ã¦ãã®ã§ã assertRaises(Error, spam, (a, b)) ã¿ããã«ãããã
@kanno_kanno with self.assertRaises(): spam(a, b) ããå¿ è¦ãããã¾ããURL
ããæ¸ããã
def test_exception(self): # NG: self.target.something() # OK: self.target.something self.assertRaises(MyException, self.target.something)
ããæ¸ãã¦ããããª!
def test_exception(self): with self.assertRaises(MyException): self.target.something()
ã¾ã¨ã
ããã¥ã¡ã³ãã¡ããã¨èªã