2016-12-27 9 views
2

は、次のことを考えてみましょう:Unittest - オブジェクトによるデータ駆動型エッジケーステスト?

import unittest 

class MyClass: 
    def __init__(self, dict: {}): 
     try: 
      if self.validate_dict(dict): 
       self.data = dict 
     except Exception as e: 
      raise Exception('Unable to create MyClass: {}'.format(str(e))) 

    def validate_dict(self, dict: {}): 
     if 'special_key' not in dict: 
      raise Exception('Missing Key: special_key') 

     # ... perhaps more complicated validation code... 
     return True 

class MyTests(unittest.TestCase): 
    def test_bad_validation(self): 
     with self.assertRaises(Exception) as context: 
      test_dict = {} 
      test_class = MyClass(test_dict) 

     self.assertTrue('Unable to create' in str(context.exception)) 

...私は離れてちょうど{}からunittestのに多くのテストケースを追加する方法を、これはユニットテストのこの機能をためひどいなアプローチではないと仮定すると?

特定のテストのすべてのテストケースを素早く確認し、新しいテストケースをすばやく追加すると便利です。

この非常に問題に取り組むために作られたライブラリDDTが見つかりましたが、dictのようなオブジェクト全体をアンパックすることなくテスト引数として渡す方法はないようです。この場合、私は鍵の存在をテストしたい(そして多くの人がいるかもしれない)ので、DDTのような個々の議論にそれらを解くことは貧弱な解決策のように思えます。

unittestは次のような機能をサポートしていますか?私はpytestは知っているが、私はunittestで可能なことを最初に見たかった。

このコードをユニットテストするための他のアプローチも認められます。

答えて

1

私はあなたがsubTestメソッド(3.4で追加)を探していると思います。検証チェックを渡すことによって、失敗した場合の3.6に

import unittest 

class MyClass: 
    def __init__(self, dic: {}): 
     try: 
      if self.validate_dict(dic): 
       self.data = dic 
     except KeyError as e: 
      raise ValueError('Unable to create MyClass: {}'.format(e)) 

    def validate_dict(self, dic): 
     if 'special_key' not in dic: 
      raise KeyError('Missing Key: special_key') 

     # ... perhaps more complicated validation code... 
     return True 

class MyTests(unittest.TestCase): 
    def test_bad_validation(self): 
     for test_dict in (
       {}, 
       {'a':1}, 
       {'b':2, 'else':3}, 
       {'special_key':4}, 
       ): 
      with self.subTest(test_dict=test_dict): 
       with self.assertRaises(Exception) as context: 
        MyClass(test_dict) 
       self.assertTrue('Unable to create' in str(context.exception)) 

unittest.main() 

、この版画、:素晴らしく

====================================================================== 
FAIL: test_bad_validation (__main__.MyTests) (test_dict={'special_key': 4}) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "F:\Python\mypy\tem2.py", line 23, in test_bad_validation 
    MyClass(test_dict) 
AssertionError: Exception not raised 

---------------------------------------------------------------------- 
Ran 1 test in 0.014s 

FAILED (failures=1) 
+0

作品。ありがとうございました。 – moogooloo

関連する問題