1. 程式人生 > 實用技巧 >單元測試之寫用例(全域性變數,異常處理,斷言)

單元測試之寫用例(全域性變數,異常處理,斷言)

時間久了,都快忘記了,寫著練練。
1
from Excel.excel_1 import HttpRequests 2 import unittest 3 COOKIE=None#全域性變數用法 4 #全域性變數先None值賦予全域性變數COOKIE 5 class TestHttp(unittest.TestCase): 6 def setUp(self): 7 print('開始執行用例') 8 9 def tearDown(self): 10 print('用例執行結束') 11 12 def test_correct_login(self):#
正常登陸 13 global COOKIE 14 url='http://api.nnzhp.cn/api/user/login' 15 data = {'username': 'niuhanyang', 'passwd': 'aA123456'} 16 res=HttpRequests().http_requests(url,data,'post') 17 if res.cookies:#如果返回的res有cookie 18 COOKIE=res.cookies#就賦值給COOKIE,COOKIE是全域性變數
19 try: 20 self.assertEqual(0,res.json()['error_code'],'登入錯誤')#為什麼帶有self,不可以直接assertEqual嗎 21 #因為self 是unittest 得內建assert 必須繼承unittest 得例項測試類 才可以用 22 except AssertionError as e: 23 print('用例test_correct_login執行出現{}錯誤'.format(e)) 24 raise
e 25 #如果是錯誤用例就不會執行下一句了,如果沒報錯就會在通過的用例顯示返回的響應正文 26 print('此條用例返回的響應正文是:', res.json())#可以再測試報告中顯示返回的響應正文 27 28 def test_erroe_login(self):#錯誤登入 29 global COOKIE#宣告是全域性變數 30 url = 'http://api.nnzhp.cn/api/user/login' 31 data = {'username': 'niuhanyang', 'passwd': 'aA123456789'} 32 res = HttpRequests().http_requests(url, data, 'post') 33 try: 34 #json()['error_code']代表介面內res的json返回值中的error_code返回的值,然後和預期結果作對比 35 self.assertEqual(0,res.json()['error_code'],'登入錯誤')#預期結果,實際結果,報錯資訊 36 except AssertionError as e: 37 print('用例test_erroe_login執行出現{}錯誤'.format(e)) 38 raise e 39 #如果是錯誤用例就不會執行下一句了,如果沒報錯就會在通過的用例顯示返回的響應正文 40 print('此條用例返回的響應正文是:', res.json())#可以再測試報告中顯示返回的響應正文 41 42 def test_correct_recharge(self): 43 global COOKIE#宣告是全域性變數 44 url='http://api.nnzhp.cn/api/user/gold_add' 45 data={'stu_id':'1432','gold':'10000'} 46 res=HttpRequests().http_requests(url,data,'post',COOKIE)#全域性變數 47 try: 48 self.assertEqual(0,res.json()['error_code'],'充值失敗') 49 except AssertionError as e: 50 print('用例test_correct_recharge執行出現{}錯誤'.format(e)) 51 raise e 52 #如果是錯誤用例就不會執行下一句了,如果沒報錯就會在通過的用例顯示返回的響應正文 53 print('此條用例返回的響應正文是:', res.json())#可以再測試報告中顯示返回的響應正文 54 55 def test_error_recharge(self): 56 global COOKIE#宣告是全域性變數 57 url = 'http://api.nnzhp.cn/api/user/gold_add' 58 data = {'stu_id': '1432', 'gold': '-1'} 59 res=HttpRequests().http_requests(url,data,'post',COOKIE) 60 try: 61 self.assertEqual(0,res.json()['error_code'],'充值失敗')#為什麼帶有self,不可以直接assertEqual嗎 62 except AssertionError as e: 63 print('用例test_error_recharge執行出現{}錯誤'.format(e)) 64 raise e 65 #如果是錯誤用例就不會執行下一句了,如果沒報錯就會在通過的用例顯示返回的響應正文 66 print('此條用例返回的響應正文是:', res.json())#可以再測試報告中顯示返回的響應正文