自动化工具 在每一个自动化测试用例里建立代理规则

黑水 · October 10, 2019 · Last by 黑水 replied at June 11, 2020 · 1871 hits

之前写了在移动端测试自动化中利用 AnyProxy Mock 数据,测试埋点功能
以前的方案里,所有用例需要的代理规则都写在 AnyProxy 的 rule 文件里,有个变量做开关,默认关闭,在每个 Mocha 用例里通过修改共享的变量打开需要的规则
写了一阵后发现 rule 文件越来越长,阅读调试的时候脑力负担非常重,所以换了个写法,新代码在 master 分支

还是 rule.js 和 Mocha 的用例共享一个 JSON 对象 rewriteRules,这个 JSON 的 key 是一个 url,value 是一个函数,这个函数的入参是 AnyProxy 截获的 Request 或者 Response

在用例里,如果有个操作触发的请求需要被修改,就在这个操作前把 url 和 value 加到 rewriteRules 里

const { rewriteRules } = require('../rules') // 和 AnyProxy 共享的 JSON
...
    it('case', function () {
        const title = Date.now()
        rewriteRules.responses = {}
        rewriteRules.responses['testerhome.com/api/v3/topics.json'] = (response) => {
            response.topics[index].title = title

            return response
        }
...

        assert.equal(element.getText(), title)
    })

在 AnyProxy 里,每次将 Response 发给 App 之前,都会检查一下这次的 url 在不在 rewriteRules 里,如果在的话,就用对应的函数处理 Response,处理完再发给 App

const rewriteRules = { 'responses' : {} }

module.exports = {
    rewriteRules: rewriteRules,
    *beforeSendResponse(requestDetail, responseDetail) {
        const hostAndPath = requestDetail.requestOptions.hostname + requestDetail.requestOptions.path.split('?')[0]

        if (rewriteRules.responses.hasOwnProperty(hostAndPath)) {
            const newResponse = responseDetail.response
            const jsonResponse = JSON.parse(newResponse.body.toString())
            const rewrite = rewriteRules.responses[hostAndPath]  // 这是从用例里拿到的处理函数
            newResponse.body = JSON.stringify(rewrite(jsonResponse))

            return {
                response: newResponse
            }
        }
    }
}
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 2 条回复 时间 点赞
Author only
黑水 #3 · June 11, 2020 Author
SimpsonH 回复

为什么不在回帖里说呢?

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up