1. 程式人生 > >python nose測試框架全面介紹八---接口測試中非法參數的斷言

python nose測試框架全面介紹八---接口測試中非法參數的斷言

mod get 自己的 strong div com 很多 with python 2

在測接口時,會有這樣的場景,輸入非法的參數,校驗返回的錯誤碼及錯誤內容

通常做法為發請求,將錯誤的返回結果拿出,再進行對比匹配;但存在一個問題,需要再寫錯誤返回分析函數,不能與之前正常發請求的函數共用。

這時,我們可以用上assertRaises、assertRaisesRegexp;python 2.7中unittest中叫assertRaises,nose.tools中叫assert_raises、assert_raises_regexp

一、unittest中的assertRaises


看看官方說明吧:

技術分享圖片

可以對異常和告警使用上面兩個方法進行斷言。

看個例子吧:

import unittest

def mode(dividend,divisor): remainder = dividend % divisor quotient = (dividend - remainder) / dividend return quotient,remainder class RaiseTest(): def test_raise(self): self.assertRaise(ZeroDivisionError, mode,7,0) def test_raise_regexp(self): self.assertRaiseRegexp(ZeroDivisionError, r
.*?Zero, mode,7,0) if __name__ == __main__: unittest.main()

註意:裏面的引用函數是不帶()的,直接是mode

異常名的也是不帶引號的,如果使用自定義的異常是要先引入的

二、nose中的assertRaises

還是上面那斷代碼,改用nose方式

#coding:utf-8
‘‘‘
Created on 2018年1月4日
@author: hu
‘‘‘
from nose.tools import assert_raises,assert_raises_regexp

def mode(dividend,divisor):
    remainder 
= dividend % divisor quotient = (dividend - remainder) / dividend return quotient,remainder class RaiseTest(): def test_raise(self): assert_raises(ZeroDivisionError, mode,7,0) def test_raise_regexp(self): assert_raises_regexp(ZeroDivisionError, r.*?Zero, mode,7,0)

執行結果也是一致的

三:接口測試中常見的用法

根據上面的斷言特證,我們在接口測試中底層的請求封裝中可以直接類似這樣寫:

def show_xxxxx(self, id):
        """查看xxxx,id為參數"""
        url = "xxxx/%s" % str(volume_id)
        resp, body = self.get(url)
        body = json.loads(body)
        self.expected_success(200, resp.status)
        return body

其中expected_success是自己的封裝,裏面封裝了拋錯,這裏就不舉例了

然後在實際測異常參數時,就可以這麽寫

def test_get_invalid_xxxxx_id(self):
        # Negative: Should not be able to get xxxxx with invalid id
        self.assertRaises(你自己定義的錯誤類型,
                          self.show_xxxxxx, #$%%&^&^)

或者用assertRaiseRegexp判斷錯誤內容

這樣一來,可以少寫很多代碼

python nose測試框架全面介紹八---接口測試中非法參數的斷言