天天看点

httprunner3.x--setup_hooks的使用

我们正在推动功能测试进行自动化用例的编写,所以我们沿用httprunner中yaml格式进行用例编写。

在用例编写中,我们遇到了需要设置前置条件的情况,而2.x的实现方式已经不能沿用到3.x里面,yml转化为.py时直接给忽略了,譬如这样的代码:

config:
    name: testcase description
    base_url: "http://192.152.104.111:8080"
    variables:
        username: "admin"
        password: "[email protected]"
    export: ["token"]
    setup_hooks:
      - ${hook_up()}
    teardown_hooks:
      - ${hook_down()} 
           

转化成的.py文件中没有对应的代码内容:

class TestCaseLogin(HttpRunner):

    config = (
        Config("testcase description")
        .variables(**{"username": "admin", "password": "[email protected]"})
        .base_url("http://192.152.104.111:8080")
        .export(*["token"])
    )

    teststeps = [
        Step(
            RunRequest("public-key")
            .get("/secret/public-key")
           

​ 研究了很久也没有搞出针对用例进行setup,teardown的实现方式。但是通过对测试步骤进行setup的操作时OK的,所以我就想到了曲线救国的思路。

在测试步骤第一步设置setup,在测试步骤最后一步设置teardown,也能达到用例级别的hook机制

yml代码如下:

config:
    name: "batch user order sync interface"
    base_url: "http://192.152.113.23:8080"
    verify: False
    variables:
        phone: "13500001|13500002"
        localpath: "D:\\xx.txt"
        remotepath: "/cmiot/ccmp/srv_file/xx.txt"
teststeps:
-
    name:  sync interface
    setup_hooks:
      - ${update_file_content($phone,$localpath)}
      - ${load_file_to_service($localpath,$remotepath)}
    teardown_hooks:
      - ${hook_down()}
    request:
        method: POST
        url: /ccmp/interface
        headers:
            Content-Type: "txt/xml"
           

转换后的python代码如下:

from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase


class TestCaseCrmBatchchangeofferingbyfile(HttpRunner):

    config = (
        Config("batch user order sync interface")
        .variables(
            **{
                "phone": "13500001|13500002",
                "localpath": "D:\\xx.txt",
                "remotepath": "/cmiot/ccmp/srv_file/xx.txt",
            }
        )
        .base_url("http://192.152.113.23:8080")
        .verify(False)
    )

    teststeps = [
        Step(
            RunRequest("sync interface")
            .setup_hook("${update_file_content($phone,$localpath)}")
            .setup_hook("${load_file_to_service($localpath,$remotepath)}")
            .post("/ccmp/interface")
            .with_headers(**{"Content-Type": "txt/xml"})
           

说明格式OK,能够正常转换。

并且在setup_hook下可以设置多个方法调用,亲测有效。暂时分享到这里,后面如果能实现用例级别的hook机制,也会进行文章内容更新。