日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

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

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