日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python—unittest—数据驱动详细讲解(ddt)

發布時間:2025/3/21 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。