python中unittest框架應用詳解

1、Unittest為Python內嵌的測試框架,不需要特殊配置

2、編寫規范

需要導入 import unittest

測試類必須繼承unittest.TestCase

測試方法以 test_開頭

模塊和類名沒有要求

TestCase 理解為寫測試用例

TestSuite 理解為測試用例的集合

TestLoader 理解為的測試用例加載

TestRunner 執行測試用例,並輸出報告

import unittest
from class_api_login_topup.demo import http_request
from class_api_login_topup.http_attr import Get_Attr  # 反射的值 獲取 cookies
# 這是文件http_attr中的Get_Attr類
class Get_Attr:
    cookies = None

class Login_Http(unittest.TestCase):
    def __init__(self, methodName, url, data, method, expected):
        super(Login_Http, self).__init__(methodName)  # 超繼承
        self.url = url
        self.data = data
        self.expected = expected
        self.method = method
    def test_api(self):  # 正常登錄
        res = http_request().request(self.url, self.data, self.method, getattr(Get_Attr, 'cookies'))
        if res.cookies:
            setattr(Get_Attr, 'cookies', res.cookies)
        try:
            self.assertEqual(self.expected, res.json()['code'])
        except AssertionError as e:
            print("test_api's, error is {0}", format(e))
            raise e
        print(res.json())

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

執行一:

import unittest
from class_demo_login_topup.http_tools import Login_Http
suite = unittest.TestSuite()
loader = unittest.TestLoader()
test_data = [{'url': 'http://test.lemonban.com/futureloan/mvc/api/member/login',
              'data': {'mobilephone': 'xxxx', 'pwd': '123456'}, 'expected': '10001', 'method': 'get'},
             {'url': 'http://test.lemonban.com/futureloan/mvc/api/member/login',
              'data': {'mobilephone': 'xxxx', 'pwd': '12345678'}, 'expected': '20111', 'method': 'get'},
             {'url': 'http://test.lemonban.com/futureloan/mvc/api/member/recharge',
              'data': {'mobilephone': 'xxxx', 'amount': '1000'}, 'expected': '10001', 'method': 'post'},
             {'url': 'http://test.lemonban.com/futureloan/mvc/api/member/recharge',
              'data': {'mobilephone': 'xxxx', 'amount': '-100'}, 'expected': '20117', 'method': 'post'}]
# 遍歷數據,執行腳本 addTest 單個執行
for item in test_data:
    suite.addTest(Login_Http('test_api', item['url'], item['data'], item['method'], item['expected']))
#  執行
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
    runner = unittest.TextTestRunner(stream=file, verbosity=2)
    runner.run(suite)
# 運行結果
{'status': 1, 'code': '10001', 'data': None, 'msg': '登錄成功'}
{'status': 0, 'code': '20111', 'data': None, 'msg': '用戶名或密碼錯誤'}
{'status': 1, 'code': '10001', 'data': {'id': 10011655, 'regname': '小蜜蜂', 'pwd': 'E10ADC3949BA59ABBE56E057F20F883E', 'mobilephone': 'xxxx', 'leaveamount': '150000.00', 'type': '1', 'regtime': '2021-07-14 14:54:08.0'}, 'msg': '充值成功'}
{'status': 0, 'code': '20117', 'data': None, 'msg': '請輸入范圍在0到50萬之間的正數金額'}

執行二:把test_data的數據放在EXCEL中運行。

import unittest
from class_demo_login_topup.http_tools import Login_Http
suite = unittest.TestSuite()
loader = unittest.TestLoader()
test_data = HttpExcel('test_api.xlsx', 'python').real_excel()
for item in test_data:
    suite.addTest(Login_Http('test_api', item['url'], eval(item['data']), item['method'], str(item['expected'])))
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
    runner = unittest.TextTestRunner(stream=file, verbosity=2)
    runner.run(suite)   

執行三、直接用裝飾器ddt

import unittest
from class_api_login_topup.demo import http_request
from class_api_login_topup.http_attr import Get_Attr  # 反射的值
from ddt import ddt, data, unpack
from class_demo_login_topup.http_excel import HttpExcel

test_data = HttpExcel('test_api.xlsx', 'python').real_excel()
@ddt
class Login_Http(unittest.TestCase):
    @data(*test_data)
    def test_api(self, item):  # 正常登錄
        res = http_request().request(item['url'], eval(item['data']), item['method'], getattr(Get_Attr, 'cookies'))
        if res.cookies:
            setattr(Get_Attr, 'cookies', res.cookies)
        try:
            self.assertEqual(str(item['expected']), res.json()['code'])
        except AssertionError as e:
            print("test_api's, error is {0}", format(e))
            raise e
        print(res.json())

執行ddt方式一

import unittest
from class_demo_login_topup.http_tools import Login_Http
from class_demo_login_topup.http_excel import HttpExcel
suite = unittest.TestSuite()
loader = unittest.TestLoader()
from class_demo_login_topup import http_tools_1
suite.addTest(loader.loadTestsFromModule(http_tools_1))  # 執行整個文件
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
    runner = unittest.TextTestRunner(stream=file, verbosity=2)
    runner.run(suite)

執行ddt方式二

import unittest
from class_demo_login_topup.http_tools import Login_Http  # 不用ddt的方法
from class_demo_login_topup.http_excel import HttpExcel
suite = unittest.TestSuite()
loader = unittest.TestLoader()
from class_demo_login_topup.http_tools_1 import * # http_tools_1文件是用ddt的方法
suite.addTest(loader.loadTestsFromTestCase(Login_Http))  # 執行http_tools_1 文件下的Login_Http類,按照類執行
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
    runner = unittest.TextTestRunner(stream=file, verbosity=2)
    runner.run(suite)

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: