還是以本地搭建的接口測試平台的登錄接口為例,發送請求,生成報告,查看結果等一系列操作,代碼都是經過本地調試,運行通過的:
1、api目錄下的demo_api.yml代碼:
name: 登錄接口 base_url: ${ENV(BASE_URL)} variables: username: $username password: $password status: $status request: url: /user/login/ method: POST headers: Content-Type: "application/json" json: username: $username password: $password validate: - eq: ["status_code", 200]
2、testcases/demo_testcase.yml代碼:
config: variables: title: $title status: $status contains_msg: $contains_msg teststeps: - name: $title api: api/demo_api.yml validate: - eq: ["status_code", $status] - {check: "content", comparator: "contains", expect: $contains_msg}
3、testsuites/demo_testsuite.yml代碼:
testcases: - name: $title testcase: testcases/demo_testcase.yml parameters: - title-username-password-status-contains_msg: ${get_login_datas()} # - ["正常登錄", "benben", "123456", 200, "token"] # - ["用戶名錯誤", "bb", "123456", 400, "non_field_errors"] # - ["密碼錯誤", "benben", "111111", 400, "non_field_errors"]
說明:
demo_testsuite中的parameters參數化實現:
1、可以直接寫測試數據,如上邊注釋掉的代碼
2、使用CSV文件來保存測試數據:- title-username-password-status-contains_msg: ${P(datas/accounts.csv)}
3、使用函數動態生成參數,將測試數據寫到debugtalk.py中,函數返回嵌套字典的列表即可,例如:
def get_login_datas(): user_info = [ {"title": "正常登錄", "username": "benben", "password": "123456", "status": 200, "contains_msg": "token"}, {"title": "用戶名錯誤", "username": "bb", "password": "123456", "status": 400, "contains_msg": "non_field_errors"}, {"title": "密碼錯誤", "username": "benben", "password": "111111", "status": 400, "contains_msg": "non_field_errors"}, ] return user_info
4、將BASE_URL變量存放到.env文件中:
BASE_URL=http://127.0.0.1:8000
5、運行,使用擴展模板:
hrun testsuites/demo_testsuite.yml --report-template templates/ext_reports_template.html
6、查看運行結果:

