python—unittest—数据驱动详细讲解(ddt)
生活随笔
收集整理的這篇文章主要介紹了
python—unittest—数据驱动详细讲解(ddt)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數據驅動ddt
數據驅動ddt可以實現測試數據與測試腳本的分離,通過ddt來將測試數據加載到腳本中。采用數據驅動設計模式使一組數據對應一個測試用例,用例自動加載生成
ddt基礎
pip install ddt測試數據為嵌套字典的列表
測試類前加修飾@ddt
測試用例前加修飾@data()
運行后用例會自動加載成多個單獨的用例
代碼案例
import unittest from ddt import ddt, data#測試用例 cases = [{'title': '登錄成功', 'expected': {'code': 200, 'msg': '登錄成功'}, 'data': ('kobe', '666')},{'title': '登錄失敗', 'expected': {'code': 201, 'msg': '用戶名或者密碼不正確'}, 'data': ('kobe', '888')},{'title': '用戶名不能為空', 'expected': {'code': 201, 'msg': '用戶名不能為空'}, 'data': ('', '666')},{'title': '密碼不能為空', 'expected': {'code': 201, 'msg': '密碼不能為空'}, 'data': ('kobe', '')},{'title': '用戶名和密碼不能為空', 'expected': {'code': 201, 'msg': '用戶名和密碼不能為空'}, 'data': ('', '')},]@ddt class LoginTestCase(unittest.TestCase):@classmethoddef setUpClass(cls) -> None:print('開始')def setUp(self) -> None:print('開始執行用例')@data(*cases)def test_login(self, case):print(case)self.assertEqual(case['expected'], self.login(case['data'][0], case['data'][1]))def login(self, username, password):if username == 'kobe' and password == '666':return {'code': 200, 'msg': '登錄成功'}if username == 'kobe' and username != '' and password != '666' and password != '':return {'code': 201, 'msg': '用戶名或者密碼不正確'}if username == 'kobe' and password == '':return {'code': 201, 'msg': '密碼不能為空'}if username == '' and password == '666':return {'code': 201, 'msg': '用戶名不能為空'}if username == '' and password == '':return {'code': 201, 'msg': '用戶名和密碼不能為空'}def tearDown(self) -> None:print('用例執行完畢')@classmethoddef tearDownClass(cls) -> None:print('結束')if __name__ == '__main__':unittest.main()case依次為,每一條case表示一條用例
{'title': '登錄成功', 'expected': {'code': 200, 'msg': '登錄成功'}, 'data': ('kobe', '666')}, {'title': '登錄失敗', 'expected': {'code': 201, 'msg': '用戶名或者密碼不正確'}, 'data': ('kobe', '888')}, {'title': '用戶名不能為空', 'expected': {'code': 201, 'msg': '用戶名不能為空'}, 'data': ('', '666')}, {'title': '密碼不能為空', 'expected': {'code': 201, 'msg': '密碼不能為空'}, 'data': ('kobe', '')}, {'title': '用戶名和密碼不能為空', 'expected': {'code': 201, 'msg': '用戶名和密碼不能為空'}, 'data': ('', '')},測試結果
繼承了unittest.TestCase的類下每個test開頭的方法(就是用例)時,每次執行用例都會執行setUp和tearDown
setUpClass和tearDownClass只會執行一次
總結
以上是生活随笔為你收集整理的python—unittest—数据驱动详细讲解(ddt)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: unittest单元测试框架—基本实例
- 下一篇: 【Flask项目2】定制统一的JSON返