引言
前面的章节介绍了,如何去抽离base_url
做一个全局变量,那么我们在实际应用中,不仅只有url
是变动不频繁,还有一些不需要改动的变量。比如:当只有一个用户场景操作的业务,此时只需要一个用户即可,那么我们就可以选择将账号以及密码抽离出来放在config
属性里面作为一个全局变量,或者声明变量名之后存储在.env
文件中。
1. py
测试用例抽离变量参数
首先在Step
中需要引用变量的地方使用${变量名}
进行引用,然后在config >> .variables(**{})
声明变量名以及它的值:
config = Config("testcase description")\
.variables(
**{
"pn": "1",
"ps": "20"
}
)\
...
teststeps = [
Step(
...
.with_params(**{"PN": "${pn}", "PS": "${ps}"})
...
2. yml
测试用例抽离变量参数
config:
name: testcase description
variables:
pn: '1'
ps: '20'
verify: false
teststeps:
...
request:
...
params:
PN: ${pn}
PS: ${ps}
...
3. 完整代码
# NOTE: Generated By HttpRunner v3.1.4
# FROM: har\woshipm_get_author.yml
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase
class TestCaseWoshipmGetAuthor(HttpRunner):
config = Config("testcase description").base_url("${ENV(base_url)}").verify(False)
teststeps = [
Step(
RunRequest("/api2/user/followings/status")
.get("/api2/user/followings/status")
.with_params(**{"authorIds": "801994"})
.with_headers(
**{
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
"COMMON_ACCESS_TOKEN": "",
"COMMON_ACCESS_TOKEN_SECRET": "",
"Connection": "keep-alive",
"Cookie": "",
"Host": "www.woshipm.com",
"Referer": "http://www.woshipm.com/u/801994",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"X-WP-Nonce": "452000896a",
}
)
.with_cookies(
**{
"Hm_lpvt_b85cbcc76e92e3fd79be8f2fed0f504f": "1628342649",
"Hm_lvt_b85cbcc76e92e3fd79be8f2fed0f504f": "1628163442,1628172667,1628334320",
"_DAU": "done%21",
"article_detail_normal": "article_user_profile@article_items",
"article_index": "",
"article_user_profile": "article_recom_users@author_items",
"dts_device_info": "",
"firstVisitTime": "1628342605147",
"isOverlayShowx": "VVVV",
"new_device_id": "device_0ca45ac5-91b5-48f1-989f-09d72908c13f",
"post_view_4751263": "2",
"s": "",
"t": "",
"wordpress_logged_in_41071e66c7856d347ba575b5339c5a86": "",
}
)
.validate()
.assert_equal("status_code", 200)
.assert_equal('headers."Content-Type"', "application/json;charset=UTF-8")
.assert_equal("body.CODE", 200)
.assert_equal("body.MESSAGE", "请求成功")
.assert_equal("body.HOST_ID", "localhost")
),
]
if __name__ == "__main__":
TestCaseWoshipmGetAuthor().test_start()