2013-02-21 17 views
13

私はpytestに新しく、いくつかの機能テストスクリプトをpytestでうまく動作するスクリプトに変換しようとしています。私のモジュールにはカスタムエラーの型があり、 "excinfoとしてpytest.raises()を使用する"メソッドを使用しようとしています。これは科学的/数値的なパッケージなので、呼び出されたときに特定のメソッドが一貫しているかどうかをテストする必要があるため、下位のものまで掘り下げることはできません。ありがとうpytest.raisesを使用して予想されるカスタムエラーをキャッチする

答えて

27

特定の例外をインポートすることを停止し、withpytest.raisesステートメントでそれを使用していますか?なぜこれは機能しないのですか?あなたが直面している問題の詳細をもっと詳しく説明できるなら、もっと役に立つでしょう。

# your code 

class CustomError(Exception): 
    pass 


def foo(): 
    raise ValueError('everything is broken') 

def bar(): 
    raise CustomError('still broken')  

#############  
# your test 

import pytest 
# import your module, or functions from it, incl. exception class  

def test_fooErrorHandling(): 
    with pytest.raises(ValueError) as excinfo: 
     foo() 
    assert excinfo.value.message == 'everything is broken' 

def test_barSimpleErrorHandling(): 
    # don't care about the specific message 
    with pytest.raises(CustomError): 
     bar() 

def test_barSpecificErrorHandling(): 
    # check the specific error message 
    with pytest.raises(MyErr) as excinfo: 
     bar() 
    assert excinfo.value.message == 'oh no!' 

def test_barWithoutImportingExceptionClass(): 
    # if for some reason you can't import the specific exception class, 
    # catch it as generic and verify it's in the str(excinfo) 
    with pytest.raises(Exception) as excinfo: 
     bar() 
    assert 'MyErr:' in str(excinfo) 
+2

はpy.test.raises'と 'あなたの最後のように見える'今更新pytest.raises' –

+0

@IanHunterで、おかげで(私はまだ「py.test」バージョンを使用してい伝えることができますする必要があります。 )) – pfctdayelise

+0

python3の場合: 'assert str(excinfo.value)== 'すべてが壊れています' – incognick

関連する問題