httprunner3.x詳細(xì)教程六(httprunner的setup和teardown及hook)
httprunner的setup和teardown可以在yml或者json文件中定義,按照3.x版本的推薦,建議大家在py文件中進(jìn)行定義放案,unittest和pytest都可以定義setup和teardown秒啦,那么httprunner如何定義呢坦报,下面我會(huì)介紹一下設(shè)置setup和teardown的兩種方式当犯。
**歡迎加入測(cè)試交流群:自動(dòng)化測(cè)試-夜行者(816489363)進(jìn)行交流學(xué)習(xí)QAQ**--成都-阿木木
httprunner有兩種setup和teardown的定義方式征椒,一個(gè)是測(cè)試類級(jí)別,一個(gè)是測(cè)試步驟級(jí)別的定義末荐。
測(cè)試類級(jí)別的setup和teardown
第一種寫法setup和teardown:
#!/user/bin/env?python??
#?-*-?coding:?utf-8?-*-??
"""??
------------------------------------??
@Project?:?interfaceDemo??
@Time????:?2020/8/20?13:47??
@Auth????:?chineseluo??
@Email???:?848257135@qq.com??
@File????:?demo_baidu_request_test.py??
@IDE?????:?PyCharm??
------------------------------------??
"""??
from?httprunner?import?HttpRunner,?Config,?Step,?RunRequest,?RunTestCase??
class?TestBaiduRequestTestCase(HttpRunner):??
????def?setup(self):??
????????print("運(yùn)行于測(cè)試用例之前")??
????def?teardown(self):??
????????print("運(yùn)行于測(cè)試用例之后")??
????config?=?(??
????????Config("get?user?list")??
????????.base_url("https://www.baidu.com")??
????????.verify(False)??
????)??
????teststeps?=?[??
????????Step(??
????????????RunRequest("get?info")??
????????????.get("/")??
????????????.validate()??
????????????.assert_equal("status_code",?200)??
????????)??
????]??
if?__name__?==?"__main__":??
????TestBaiduRequestTestCase().test_start()??
結(jié)果為:
Process?finished?with?exit?code?0??
運(yùn)行于測(cè)試用例之前??
PASSED?[100%]2020-08-20?13:50:53.306?|?INFO?????|?httprunner.loader:load_dot_env_file:127?-?Loading?environment?variables?from?D:\TestScriptDir\httprunner\interfaceDemo\.env??
.??
.??
.??
?D:\TestScriptDir\httprunner\interfaceDemo\logs\a3872c1b-dedf-4485-bd95-3f31947bfae0.run.log??
運(yùn)行于測(cè)試用例之后??
第二種寫法setup_class和teardown_class:
#!/user/bin/env?python??
#?-*-?coding:?utf-8?-*-??
"""?
------------------------------------?
@Project?:?interfaceDemo?
@Time????:?2020/8/20?13:47?
@Auth????:?chineseluo?
@Email???:?848257135@qq.com?
@File????:?demo_baidu_request_test.py?
@IDE?????:?PyCharm?
------------------------------------?
"""??
from?httprunner?import?HttpRunner,?Config,?Step,?RunRequest,?RunTestCase??
class?TestBaiduRequestTestCase(HttpRunner):??
????@classmethod??
????def?setup_class(cls):??
????????print("運(yùn)行于測(cè)試用例之前")??
????@classmethod??
????def?teardown_class(cls):??
????????print("運(yùn)行于測(cè)試用例之后")??
????config?=?(??
????????Config("get?user?list")??
????????.base_url("https://www.baidu.com")??
????????.verify(False)??
????)??
????teststeps?=?[??
????????Step(??
????????????RunRequest("get?info")??
????????????.get("/")??
????????????.validate()??
????????????.assert_equal("status_code",?200)??
????????)??
????]??
if?__name__?==?"__main__":??
????TestBaiduRequestTestCase().test_start()??
上面兩種寫法在unittest和pytest中是不一樣的侧纯,setup_class是運(yùn)行于測(cè)試類的前面,setup是運(yùn)行與每個(gè)測(cè)試方法的前面甲脏,在httprunner好像不區(qū)分這兩個(gè)方法眶熬。
測(cè)試步驟前后的setup和teardown設(shè)置
我在debugtalk.py中寫了兩個(gè)hook_up和hook_teardown方法
def?hook_up():??
????print("前置操作:setup!")??
def?hook_down(response=None):??
????print("后置操作:teardown!")??
????if?response:??
????????print(response)??
????????response.status_code?=?300??
在demo_baidu_request_test.py中調(diào)用debugtalk的兩個(gè)hook方法,使用setup_hook()和teardown_hook()來加載我們自定義的hook:
#!/user/bin/env?python??
#?-*-?coding:?utf-8?-*-??
"""?
------------------------------------?
@Project?:?interfaceDemo?
@Time????:?2020/8/20?13:47?
@Auth????:?chineseluo?
@Email???:?848257135@qq.com?
@File????:?demo_baidu_request_test.py?
@IDE?????:?PyCharm?
------------------------------------?
"""??
from?httprunner?import?HttpRunner,?Config,?Step,?RunRequest,?RunTestCase??
class?TestBaiduRequestTestCase(HttpRunner):??
????@classmethod??
????def?setup_class(cls):??
????????print("運(yùn)行于測(cè)試用例之前")??
????@classmethod??
????def?teardown_class(cls):??
????????print("運(yùn)行于測(cè)試用例之后")??
????config?=?(??
????????Config("get?user?list")??
????????.base_url("https://www.baidu.com")??
????????.verify(False)??
????)??
????teststeps?=?[??
????????Step(??
????????????RunRequest("get?info")??
????????????.setup_hook("${hook_up()}")??
????????????.get("/")??
????????????.teardown_hook("${hook_down()}")??
????????????.validate()??
????????????.assert_equal("status_code",?200)??
????????)??
????]??
if?__name__?==?"__main__":??
????TestBaiduRequestTestCase().test_start()??
運(yùn)行結(jié)果:
Process?finished?with?exit?code?0??
運(yùn)行于測(cè)試用例之前??
PASSED?[100%]前置操作:setup!??
后置操作:teardown!??
2020-08-20?14:07:08.534?|?INFO?????|?httprunner.runner:test_start:460?-?generate?testcase?log:?D:\TestScriptDir\httprunner\interfaceDemo\logs\983886ea-36c1-4677-9966-4929f4006004.run.log??
運(yùn)行于測(cè)試用例之后??
既然是hook方法块请,那么肯定是會(huì)集成一些內(nèi)置的鉤子娜氏,滿足特殊的要求所使用的。
setup_hooks:在測(cè)試步驟前執(zhí)行负乡,先調(diào)用setup_hooks()內(nèi)的函數(shù)牍白。可以傳入 $request 參數(shù)抖棘,可以對(duì)請(qǐng)求進(jìn)行預(yù)處理或者修改茂腥,修改請(qǐng)求參數(shù)
teardown_hooks:在測(cè)試步驟執(zhí)行后,先調(diào)用teardown()內(nèi)的函數(shù)切省,可以傳入$response參數(shù)最岗,可以對(duì)返回值進(jìn)行處理
我先在debugtalk.py中定義兩個(gè)方法,輸出一下后面獲取的request和response.
def?hook_up(request=None):??
????print("輸出request:{}".format(request))??
????print("前置操作:setup!")??
def?hook_down(response=None):??
????print("輸出response:{}".format('\n'.join(['%s:%s'?%?item?for?item?in?response.__dict__.items()])))??
????print("后置操作:teardown!")??
然后在demo_baidu_request_test.py文件中調(diào)用這兩個(gè)hook朝捆,然后傳遞參數(shù)$request和$response般渡。
#!/user/bin/env?python??
#?-*-?coding:?utf-8?-*-??
"""?
------------------------------------?
@Project?:?interfaceDemo?
@Time????:?2020/8/20?13:47?
@Auth????:?chineseluo?
@Email???:?848257135@qq.com?
@File????:?demo_baidu_request_test.py?
@IDE?????:?PyCharm?
------------------------------------?
"""??
from?httprunner?import?HttpRunner,?Config,?Step,?RunRequest,?RunTestCase??
class?TestBaiduRequestTestCase(HttpRunner):??
????@classmethod??
????def?setup_class(cls):??
????????print("運(yùn)行于測(cè)試用例之前")??
????@classmethod??
????def?teardown_class(cls):??
????????print("運(yùn)行于測(cè)試用例之后")??
????config?=?(??
????????Config("get?user?list")??
????????.base_url("https://www.baidu.com")??
????????.verify(False)??
????)??
????teststeps?=?[??
????????Step(??
????????????RunRequest("get?info")??
????????????.setup_hook("${hook_up($request)}")??
????????????.get("/")??
????????????.teardown_hook("${hook_down($response)}")??
????????????.validate()??
????????????.assert_equal("status_code",?200)??
????????)??
????]??
if?__name__?==?"__main__":??
????TestBaiduRequestTestCase().test_start()??
結(jié)果如下:
Process?finished?with?exit?code?0??
運(yùn)行于測(cè)試用例之前??
PASSED?[100%]輸出request:{'method':?'GET',?'url':?'/',?'params':?{},?'headers':?{'HRUN-Request-ID':?'HRUN-656566cb-5369-43b1-af19-47ce6ef1c7ba-081374'},?'req_json':?None,?'data':?None,?'cookies':?{},?'timeout':?120,?'allow_redirects':?True,?'verify':?False}??
前置操作:setup!??
resp_obj:<Response?[200]>??
validation_results:{}??
后置操作:teardown!??
傳入的是一個(gè)request和response對(duì)象,我們可以對(duì)于傳入的request和response對(duì)象進(jìn)行操作
我們可以修改resquest和response傳入和返回的值芙盘,來完成復(fù)雜的業(yè)務(wù)要求驯用。
現(xiàn)在debugtalk.py改變了一下:
def?hook_up(request=None):??
????print("輸出request:{}".format(request))??
????print("前置操作:setup!")??
????if?request:??
????????request["params"]["username"]?=?"888888"??
def?hook_down(response=None):??
????print("輸出response:{}".format('\n'.join(['%s:%s'?%?item?for?item?in?response.__dict__.items()])))??
????print("后置操作:teardown!")??
????if?response:??
????????response.status_code?=?404??
我修改了傳入的setp的密碼為“888888”,修改了step返回的狀態(tài)碼為404儒老,看一下我在demo_baidu_request_test.py中的調(diào)用:
#!/user/bin/env?python??
#?-*-?coding:?utf-8?-*-??
"""?
------------------------------------?
@Project?:?interfaceDemo?
@Time????:?2020/8/20?13:47?
@Auth????:?chineseluo?
@Email???:?848257135@qq.com?
@File????:?demo_baidu_request_test.py?
@IDE?????:?PyCharm?
------------------------------------?
"""??
from?httprunner?import?HttpRunner,?Config,?Step,?RunRequest,?RunTestCase??
class?TestBaiduRequestTestCase(HttpRunner):??
????@classmethod??
????def?setup_class(cls):??
????????print("運(yùn)行于測(cè)試用例之前")??
????@classmethod??
????def?teardown_class(cls):??
????????print("運(yùn)行于測(cè)試用例之后")??
????config?=?(??
????????Config("get?user?list")??
????????.variables(??
????????????**{??
????????????????"username":?"123456"??
????????????}??
????????)??
????????.base_url("https://www.baidu.com")??
????????.verify(False)??
????)??
????teststeps?=?[??
????????Step(??
????????????RunRequest("get?info")??
????????????.setup_hook("${hook_up($request)}")??
????????????.get("/")??
????????????.with_params(**{"username":?"${username}"})??
????????????.teardown_hook("${hook_down($response)}")??
????????????.validate()??
????????????.assert_equal("status_code",?200)??
????????)??
????]??
if?__name__?==?"__main__":??
????TestBaiduRequestTestCase().test_start()??
下面是執(zhí)行結(jié)果:
demo_baidu_request_test.py::TestBaiduRequestTestCase::test_start?<-?C:\Users\luozhongwen\AppData\Local\Programs\Python\Python38\lib\site-packages\httprunner\runner.py?運(yùn)行于測(cè)試用例之前??
FAILED?[100%]輸出request:{'method':?'GET',?'url':?'/',?'params':?{'username':?'123456'},?'headers':?{'HRUN-Request-ID':?'HRUN-bbeea383-94b1-43c4-8092-4f35debfdacc-782331'},?'req_json':?None,?'data':?None,?'cookies':?{},?'timeout':?120,?'allow_redirects':?True,?'verify':?False}??
前置操作:setup!??
輸出response:resp_obj:<Response?[200]>??
validation_results:{}??
后置操作:teardown??
method???:?GET??
url??????:?https://www.baidu.com/?username=888888??
httprunner.exceptions.ValidationFailure:?assert?status_code?equal?200(int)??==>?fail??
check_item:?status_code??
check_value:?404(int)??
assert_method:?equal??
expect_value:?200(int)??
可以看到斷言是失敗的蝴乔,我設(shè)置的成功斷言狀態(tài)碼是200,傳入的request中的username開始是123456驮樊,被我們截獲請(qǐng)求參數(shù)后更改為了888888薇正。在實(shí)際應(yīng)用中,我們可以對(duì)于傳入賬號(hào)密碼等進(jìn)行加密囚衔,或者對(duì)于返回值的格式等進(jìn)行解碼操作