httprunner 3.x--variables變量和聲明(變量和值一一對應)


 

在 HttpRunner 中,支持變量聲明(variables)和引用($var)的機制。調用函數(${func($var)})

在 config 和 test 中均可以通過 variables 關鍵字定義變量,然后在測試步驟中可以通過 $ + 變量名稱 的方式引用變量。


區別在於:

在 config 中定義的變量為全局的,整個測試用例(testcase)的所有地方均可以引用;

在 test 中定義的變量作用域僅局限於當前測試步驟(teststep)

 

一般寫用例的時候,最好把可能會變的參數單獨寫個變量。做到測試數據和代碼的分離,以便后續維護。

如果step和config中variables聲明的參數名相同,在運行測試用例的時候會取step里面的參數值

全局變量

如果要設置一個全局變量,需把變量聲明(variables)放到config下

pytest格式

config = (
        Config("test /lotter*****st.php")
        .base_url("https://lotter****.com")
        .verify(False)
        .variables(
            **{"uid": "14**7",
               "choujiang_id": "*9",
               "username": "**"}
        )
    )

yml格式

config:
    name: "hz測試"
    base_url: "https://lottery.hz.z****in.com"
    variables:
        uid: "14***7"
        choujiang_id: "***"
        username: "**"

    verify: False

teststeps:
-
    name: "接口test /lotteryTest.php"
    request:
        method: GET
        url: /lotteryTest.php
        params:
          uid: $uid
          choujiang_id: $choujiang_id
          username: $username
    validate:
        - eq : ["status_code", 200]
        - eq : ["body.status", 1]

 

引用uid和choujiang_id/username變量用$uid,$pchoujiang_id,$username 完整的腳本如下:

 

 

 

局部變量

如果在steps下聲明的變量,作用域只在當前steps下有效。聲明變量用with_variables,變量和對應值用鍵值對,如

Step(
            RunRequest("get with params")
            .with_variables(
                **{"uid": "14**7",
                   "choujiang_id": "**",
                   "username": "**"}
            )
            .get("/lotteryTest.php")
            .with_params(**{"uid": "$uid", "choujiang_id": "$choujiang_id", "username": "$username"})
            .validate()
            .assert_equal("status_code", 200)
        ),

完整代碼如下:

 

 運行結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM