unittestの5例(すべての技術は、データはまた、試験された場合でも、テストデータをフェイル実装するコードを使用して)テスト弱いパスワード

背景

私たちは、これらのデータは時間以下でテストするとき、私たちはケースを使用することは問題です。

[
  {"name":"jack","password":"Iloverose"},
  {"name":"rose","password":"Ilovejack"},
  {"name":"tom","password":"password123"},
  {"name":"jerry","password":"password"}
]

私たちのユースケースは、トムはこのユーザが処罰される、ジェリーの弱いユーザーのパスワードを見つけることです。

何故

ユニットテストでは、これは、試験方法アサーションの失敗後、後続のアサーションが実行されません。

ループが終了するため、アサーション障害時例トムで使用され、試験方法を完了すると、上記の例における減少は、このデータの背後にあるジェリーはアサートされません。

どのように行います

私たちは、アサーションが弱いパスワードをプリントアウトするようにユーザーを置くために失敗した後の試験方法は、一度だけアサートさそうという、当社の試験方法について再構築することができます。

コード

いくつかのテストデータを追加し、user_data.jsonファイルを変更し、user_data.json変更されたファイルはする必要があります

[
  {"name":"jack","password":"Iloverose"},
  {"name":"rose","password":"Ilovejack"},
  {"name":"tom","password":"password123"},
  {"name":"jerry","password":"password"},
  {"name":"fred","password":"123456"},
  {"name":"elma","password":"654321"}
]

新しいtest_password_4.pyファイルには、次のように


import unittest
import json

class WeakPasswordTestCase1(unittest.TestCase):

    @classmethod
    def setUpClass(kls):
        data_file_path = './user_data.json'
        print('before all test methods')
        with open(data_file_path) as f:
            kls.test_data = json.loads(f.read())

    def test_weak_password(self):
        res = True
        msg = []
        for data in self.test_data:
            passwd = data['password']
            tmp_res = True

            tmp_res = tmp_res and (len(passwd) >= 6)
            tmp_res = tmp_res and (passwd != 'password')
            tmp_res = tmp_res and (passwd != 'password123')
            if not tmp_res:
                msg.append("user %s has a weak password %s" %(data['name'], data['password']))
            res = res and tmp_res

        self.assertTrue(res, "\n".join(msg))

    def test_dummy(self):
        pass

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

操作と結果

コマンドラインを実行しpython test_password_4.py、以下の結果とし

$ python test_password_4.py
before all test methods
.F
======================================================================
FAIL: test_weak_password (__main__.WeakPasswordTestCase1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_password_4.py", line 27, in test_week_password
    self.assertTrue(res, "\n".join(msg))
AssertionError: user tom has a weak password password123
user jerry has a weak password password

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

私たちが学ぶことができます

  • 失敗したら、アサーション後、試験方法の実行は、終了しますので、一般的に試験方法が一つだけアサーションをお勧めします
  • より多くのアサーションでなければならない試験方法は、前のアサーションの失敗の後に確認している場合、後者の主張が実行されていない場合でも、それはテストの範囲と結果には影響しません
  • ループアサーションの失敗のために一度、それがループの外にあるため
  • 実際には、テストケースの上のプレゼンテーションの文言は、データ駆動型テストの特定のアイデアを持っています

プログラムは、この方法が唯一の主張され、その結果、特定のスキル、操作で複数のデータの結果の性質の判定を有するように設計されます。

参照

http://www.testclass.net/pyunit/test_example_3

おすすめ

転載: www.cnblogs.com/candyYang/p/12290300.html
おすすめ