私は強くassertRaises
とunittest.TestCase
からassertRaisesRegexp
の動作を複製nose.tools
からassert_raises
とassert_raises_regexp
を、使用することをお勧めだから
鼻には固有のドキュメントはありません。これにより、実際にunittest.TestCase
クラスを使用しないテストスイートでは、unittest.TestCase
と同じ機能を使用できます。
私は、@raises
が非常に鈍い器械であることがわかりました。 foo
は、我々が期待していた例外を調達しているので、しかしfoo
が使用するデータを設定したコードは、同じ例外で失敗するので
from nose.tools import *
something = ["aaa", "bbb"]
def foo(x, source=None):
if source is None:
source = something
return source[x]
# This is fine
@raises(IndexError)
def test1():
foo(3)
# This is fine. The expected error does not happen because we made
# a mistake in the test or in the code. The failure indicates we made
# a mistake.
@raises(IndexError)
def test2():
foo(1)
# This passes for the wrong reasons.
@raises(IndexError)
def test3():
source = something[2] # This is the line that raises the exception.
foo(10, source) # This is not tested.
# When we use assert_raises, we can isolate the line where we expect
# the failure. This causes an error due to the exception raised in
# the first line of the function.
def test4():
source = something[2]
with assert_raises(IndexError):
foo(10, source)
test3
パスではなく:ここでは、問題を示すコードです。test4
は、実際にテストすることを意味するものを実際にテストするために、を使用してテストを書き込む方法を示しています。最初の行の問題は、Noseにエラーを報告させ、次にテストを書き直して、その行をテストして、最終的にテストしたことをテストできるようにします。
@raises
は、例外に関連するメッセージのテストを許可しません。私がValueError
を上げるとき、ちょうど1つの例を取るために、私は通常有益なメッセージでそれを上げたいと思う。ここでは例です:渡します@raises
使用
def bar(arg):
if arg: # This is incorrect code.
raise ValueError("arg should be higher than 3")
if arg >= 10:
raise ValueError("arg should be less than 10")
# We don't know which of the possible `raise` statements was reached.
@raises(ValueError)
def test5():
bar(10)
# Yes, we're getting an exception but with the wrong value: bug found!
def test6():
with assert_raises_regexp(ValueError, "arg should be less than 10"):
bar(10)
test5
が、それは間違った理由のために渡します。 test6
は、より細かいテストを実行して、ValueError
が欲しいものではないことがわかりました。
ほとんどのdupのhttp://stackoverflow.com/questions/11767938/how-to-use-noses-assert-raises – Stefano