2016-08-10 6 views
-1

私はTDDを初めて使い、テストを書くときに状況に遭遇しました。文字列が有効なintであるかどうかをアサート

マイFUNC:

def nonce(): 
    return str(int(1000 * time.time())) 

私はそれのためにテストを書いた - そしてそれは私が何をしたいんしながら、これを処理するunittestモジュールの中で何か?:

があるべきように、それはそう
def test_nonce_returns_an_int_as_string(self): 
    n = 'abc' # I want it to deliberately fail 
    self.assertIsInstance(n, str) 
    try: 
     int(n) 
    except ValueError: 
     self.fail("%s is not a stringified integer!" % n) 

これをアサートする方法はありますか?try/except

この回答はSO postですが、回答ではassert afaictの使用はありません。

特に気になるのは、私のfailed testメッセージは、純粋なunittest.TestCaseメソッドを使用するのとは対照的に、あまりにもかわいくてクラッタではないということです。

Failure 
Traceback (most recent call last): 
    File "/git/bitex/tests/client_tests.py", line 39, in test_restapi_nonce 
    int(n) 
ValueError: invalid literal for int() with base 10: 'a' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "//git/bitex/tests/client_tests.py", line 41, in test_restapi_nonce 
    self.fail("%s is not a stringified integer!" % n) 
AssertionError: a is not a stringified integer! 
+0

テストをデバッグするためのメッセージがあります。ある例外が別の例外を処理するコンテキストで発生した場合、通常はこれについて知りたいと思う*。 –

+0

* "答えは' assert' afaict "の使用法を提供していません" * - あなたは何を言っているのですか?それらの全ては、例えば、 'self.assertTrue(n.isdigit())'のようなテストに簡単に適応させることができます。 – jonrsharpe

+0

答えに何が書いてあるのか考えるのを止めずに、私はそれを言います。あなたが正しい。シャック。 – nlsdfnbch

答えて

1

あなたはアサーション例外ハンドラ外を作ることができます。その方法は、Pythonが処理されているValueErrorAssertionError例外を接続しません:それは唯一なし整数の文字列のために働くだろうと

self.assertTrue(n.strip().isdigit()) 

注:代わりにため

try: 
    intvalue = int(n) 
except ValueError: 
    intvalue = None 

self.assertIsNotNone(intvalue) 

またはテスト符号。先頭の+または-は、int()には許容されますが、str.isdigit()には受け入れられません。しかし、あなたの特定の例では、str.isdigit()を使用すれば十分でしょう。

関連する問題