質問

どのような書unittestに失敗した場合のみ機能しない捨てると予想される例外?

役に立ちましたか?

解決

使用 TestCase.assertRaisesTestCase.failUnlessRaises からunittestモジュール、例えば:

import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)

他のヒント

Python2.7利用できる文脈管にaholdの実際の例外オブジェクトを投:

import unittest

def broken_function():
    raise Exception('This is broken')

class MyTestCase(unittest.TestCase):
    def test(self):
        with self.assertRaises(Exception) as context:
            broken_function()

        self.assertTrue('This is broken' in context.exception)

if __name__ == '__main__':
    unittest.main()

http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises


Python3.5, いラップ context.exceptionstr, れんく TypeError

self.assertTrue('This is broken' in str(context.exception))

このコード私の前の答えは単純にすることが求められている:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction)

場afunctionかの引数で渡しassertRaisesようになります:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction, arg1, arg2)

どうでしょうPython関数が例外をスローし?

にはどうすればよい書き試験に失敗した場合のみ機能しない投げ 予想される例外?

答え:

をご利用 self.assertRaises 方法としてのコンテキストマネージャー:

    def test_1_cannot_add_int_and_str(self):
        with self.assertRaises(TypeError):
            1 + '1'

実証

最良の実践アプローチはかなり簡単になるこのPythonしています。

unittest 図書館

Python2.7 3:

import unittest

Python2.6インストールすることができるbackport27の unittest 図書館と呼ばれる unittest2, には、エイリアスとして、 unittest:

import unittest2 as unittest

試験例

現在、ペーストへのPythonのシェルに以下の試験はPythonのタイプの安全:

class MyTestCase(unittest.TestCase):
    def test_1_cannot_add_int_and_str(self):
        with self.assertRaises(TypeError):
            1 + '1'
    def test_2_cannot_add_int_and_str(self):
        import operator
        self.assertRaises(TypeError, operator.add, 1, '1')

試験用 assertRaises コンテクストとして長することを確保するためにエラーが適切に挟まれ-巻き込まれ清掃が記録されます。

私のように記述することもできますので なし コマは、試験ます。最初の引数のエラータイプのご期待を上げ、第二引数の機能をお試験に用い、残りの引数とキーワード引数が渡される機能です。

いかに簡単に読みや、維持するだけでコンテキストを使用した。

走行試験

の試験:

unittest.main(exit=False)

Python2.6ましょう 必要以下の:

unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))

お端子は出力の

..
----------------------------------------------------------------------
Ran 2 tests in 0.007s

OK
<unittest2.runner.TextTestResult run=2 errors=0 failures=0>

とをすることが見込まれることを追加 1'1'TypeError.


より詳細な出力してみてください:

unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(MyTestCase))

コードはこのパターン(これはunittestモジュールのスタイル試験):

def test_afunction_throws_exception(self):
    try:
        afunction()
    except ExpectedException:
        pass
    except Exception as e:
       self.fail('Unexpected exception raised:', e)
    else:
       self.fail('ExpectedException not raised')

Python < 2.7この構築に有用なチェックのための特定の値を期待します。のunittest機能 assertRaises みかどうかをチェックします例外を向上させました。

http://www.lengrand.fr/2011/12/pythonunittest-assertraises-raises-error/

最初に、ここに対応する(利用するものdum:p)関数ファイルdum_function.py :

def square_value(a):
   """
   Returns the square value of a.
   """
   try:
       out = a*a
   except TypeError:
       raise TypeError("Input should be a string:")

   return out

ここでは、試験を行うのみこの試験は挿入):

import dum_function as df # import function module
import unittest
class Test(unittest.TestCase):
   """
      The class inherits from unittest
      """
   def setUp(self):
       """
       This method is called before each test
       """
       self.false_int = "A"

   def tearDown(self):
       """
       This method is called after each test
       """
       pass
      #---
         ## TESTS
   def test_square_value(self):
       # assertRaises(excClass, callableObj) prototype
       self.assertRaises(TypeError, df.square_value(self.false_int))

   if __name__ == "__main__":
       unittest.main()

このス機能!ここでは何が起きるように試験:

======================================================================
ERROR: test_square_value (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_dum_function.py", line 22, in test_square_value
    self.assertRaises(TypeError, df.square_value(self.false_int))
  File "/home/jlengrand/Desktop/function.py", line 8, in square_value
    raise TypeError("Input should be a string:")
TypeError: Input should be a string:

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

にTypeErrorがactullay達成テストの失敗。問題はこれが正確に行動した。

このエラーを簡単に機能をラムダ仕様のテストコール:

self.assertRaises(TypeError, lambda: df.square_value(self.false_int))

最終出力:

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

完璧です!

...とくに最適!!

ThanskくさんサンジュリアンLengrand-ランベール

することで作ることができる独自の contextmanager チェックの場合は例外を向上させました。

import contextlib

@contextlib.contextmanager
def raises(exception):
    try:
        yield 
    except exception as e:
        assert True
    else:
        assert False

とを利用することができ raises このように:

with raises(Exception):
    print "Hola"  # Calls assert False

with raises(Exception):
    raise Exception  # Calls assert True

ご利用の場合 pytest, このことは実施しています。できない pytest.raises(Exception):

例:

def test_div_zero():
    with pytest.raises(ZeroDivisionError):
        1/0

その結果:

pigueiras@pigueiras$ py.test
================= test session starts =================
platform linux2 -- Python 2.6.6 -- py-1.4.20 -- pytest-2.5.2 -- /usr/bin/python
collected 1 items 

tests/test_div_zero.py:6: test_div_zero PASSED

使ってい doctest[1]ほとんどどこでも好きだから、その文書は、試験は私の機能も同時に行います。

このコード:

def throw_up(something, gowrong=False):
    """
    >>> throw_up('Fish n Chips')
    Traceback (most recent call last):
    ...
    Exception: Fish n Chips

    >>> throw_up('Fish n Chips', gowrong=True)
    'I feel fine!'
    """
    if gowrong:
        return "I feel fine!"
    raise Exception(something)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

を入れればこの例では、モジュールを実行し、コマンドラインからの両方のテストケース評価を実施します。

[1] Pythonドキュメンテーション23.2doctest-試験対話モードにおける例題

というものが assertRaises の方法 unittest モジュールです。

うることを発見し、 模擬図書館 を提供assertRaisesWithMessage()メソッド(そのunittest.テストケースクラスのサブクラスは、チェックな期待される例外は、それだけではなく上げるのメッセージ:

from testcase import TestCase

import mymod

class MyTestCase(TestCase):
    def test1(self):
        self.assertRaisesWithMessage(SomeCoolException,
                                     'expected message',
                                     mymod.myfunc)

利用できるassertRaisesからunittestモジュール

import unittest

class TestClass():
  def raises_exception(self):
    raise Exception("test")

class MyTestCase(unittest.TestCase):
  def test_if_method_raises_correct_exception(self):
    test_class = TestClass()
    # note that you dont use () when passing the method to assertRaises
    self.assertRaises(Exception, test_class.raises_exception)

多くの回答をこちらです。のコードを作成できます例外利用法などについて、また、どこの例外に当社の手法は、最後にいかを確認することができ、unittestの修正の例外を除いています。

import unittest

class DeviceException(Exception):
    def __init__(self, msg, code):
        self.msg = msg
        self.code = code
    def __str__(self):
        return repr("Error {}: {}".format(self.code, self.msg))

class MyDevice(object):
    def __init__(self):
        self.name = 'DefaultName'

    def setParameter(self, param, value):
        if isinstance(value, str):
            setattr(self, param , value)
        else:
            raise DeviceException('Incorrect type of argument passed. Name expects a string', 100001)

    def getParameter(self, param):
        return getattr(self, param)

class TestMyDevice(unittest.TestCase):

    def setUp(self):
        self.dev1 = MyDevice()

    def tearDown(self):
        del self.dev1

    def test_name(self):
        """ Test for valid input for name parameter """

        self.dev1.setParameter('name', 'MyDevice')
        name = self.dev1.getParameter('name')
        self.assertEqual(name, 'MyDevice')

    def test_invalid_name(self):
        """ Test to check if error is raised if invalid type of input is provided """

        self.assertRaises(DeviceException, self.dev1.setParameter, 'name', 1234)

    def test_exception_message(self):
        """ Test to check if correct exception message and code is raised when incorrect value is passed """

        with self.assertRaises(DeviceException) as cm:
            self.dev1.setParameter('name', 1234)
        self.assertEqual(cm.exception.msg, 'Incorrect type of argument passed. Name expects a string', 'mismatch in expected error message')
        self.assertEqual(cm.exception.code, 100001, 'mismatch in expected error code')


if __name__ == '__main__':
    unittest.main()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top