HttpRunner3.x 源码解析(5)-runner.py

这篇具有很好参考价值的文章主要介绍了HttpRunner3.x 源码解析(5)-runner.py。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

首先看下生成的pytest文件

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


class TestCaseLogin(HttpRunner):

    config = (
        Config("登录成功").variables(**{"password": "tester", "expect_foo2": "config_bar2"}).base_url("https://api.pity.fun")
        .verify(False)
        .export(*["token"])
    )

    teststeps = [
        Step(
            RunRequest("登录成功")
            .with_variables(**{"foo1": "bar1"})
            .setup_hook("${get_request($request)}")
            .post("/auth/login")
            .with_headers(**{"Content-Type": "application/json"})
            .with_json({"username": "${ENV(username)}", "password": "${ENV(password)}"})
            .teardown_hook("${get_reponse($response)}")
            .extract()
            .with_jmespath("body.msg", "token")
            .validate()
            .assert_equal("status_code", 200)
            .assert_equal("body.code", 0)
            .assert_equal("body.msg", "哈哈哈")
        ),
    ]


if __name__ == "__main__":
    TestCaseLogin().test_start()

首先类继承了HttpRunner类

主要包括config和teststeps两部分

函数的入库是test_start()方法

test_start

  def test_start(self, param: Dict = None) -> "HttpRunner":
        """main entrance, discovered by pytest"""
        self.__init_tests__()
        self.__project_meta = self.__project_meta or load_project_meta(
            self.__config.path
        )
        self.__case_id = self.__case_id or str(uuid.uuid4())
        self.__log_path = self.__log_path or os.path.join(
            self.__project_meta.RootDir, "logs", f"{self.__case_id}.run.log"
        )
        log_handler = logger.add(self.__log_path, level="DEBUG")

        # parse config name
        config_variables = self.__config.variables
        if param:
            config_variables.update(param)
        config_variables.update(self.__session_variables)
        self.__config.name = parse_data(
            self.__config.name, config_variables, self.__project_meta.functions
        )

        if USE_ALLURE:
            # update allure report meta
            allure.dynamic.title(self.__config.name)
            allure.dynamic.description(f"TestCase ID: {self.__case_id}")

        logger.info(
            f"Start to run testcase: {self.__config.name}, TestCase ID: {self.__case_id}"
        )

        try:
            return self.run_testcase(
                TestCase(config=self.__config, teststeps=self.__teststeps)
            )
        finally:
            logger.remove(log_handler)
            logger.info(f"generate testcase log: {self.__log_path}")

首先调用了__init_tests__()方法

HttpRunner3.x 源码解析(5)-runner.py

 teststeps是pytest文件中的Step列表,示例只有1个步骤。

HttpRunner3.x 源码解析(5)-runner.py

 文章来源地址https://www.toymoban.com/news/detail-414617.html

config.perform方法返回了一个Tconfig对象,这个对象定义了testcase的config中的关键字和内容

HttpRunner3.x 源码解析(5)-runner.py

 HttpRunner3.x 源码解析(5)-runner.py

teststeps是py文件中的Step列表,

调用的step.perform()方法,返回__step_context,而__step_context来自step_context调用perfoem方法。

在Step类的初始化函数可以看到,step_context可以是如下几种

 

当step_contxt时RunTestCase时,调用它的perfom方法如下,可以看到返回的是一个TStep对象。

HttpRunner3.x 源码解析(5)-runner.py HttpRunner3.x 源码解析(5)-runner.py

 接着看test_start()

self.__project_meta = self.__project_meta or load_project_meta(
    self.__config.path
)

 返回项目的资源文件

self.__case_id为caseid或者是一个uuid
self.__log_path为日志目录
config_variables = self.__config.variables为config部分的变量
self.__config.name = parse_data(
    self.__config.name, config_variables, self.__project_meta.functions
)获取config中的name
if USE_ALLURE:
    # update allure report meta
    allure.dynamic.title(self.__config.name)
    allure.dynamic.description(f"TestCase ID: {self.__case_id}")

logger.info(
    f"Start to run testcase: {self.__config.name}, TestCase ID: {self.__case_id}"
)

如果用了allure报告,则定义title和描述

 

return self.run_testcase(
    TestCase(config=self.__config, teststeps=self.__teststeps)
)

将config和teststeps列表传给TestCase并调用HttpRunner类的run_testcase方法执行用例

run_testcase

这个方法最后返回的也是HttpRunner实例

主要的是下面这一句,执行了用例的步骤。

extract_mapping = self.__run_step(step)

 __run_step方法

如果步骤中存在request,则调用__run_step_request来执行步骤,并返回返回testdata

如果存在testcase,则调用__run_step_testcase(step)来执行,最后返回test_data

    def __run_step(self, step: TStep):
        """run teststep, teststep maybe a request or referenced testcase"""
        logger.info(f"run step begin: {step.name} >>>>>>")

        if step.request:
            step_data = self.__run_step_request(step)
        elif step.testcase:
            step_data = self.__run_step_testcase(step)
        else:
            raise ParamsError(
                f"teststep is neither a request nor a referenced testcase: {step.dict()}"
            )

        self.__step_datas.append(step_data)
        logger.info(f"run step end: {step.name} <<<<<<\n")
        return step_data.export_vars

__run_step_request

这个方法解析request并调用request方法来执行

resp = self.__session.request(method, url, **parsed_request_dict)

HttpRunner3.x 源码解析(5)-runner.py

 

parsed_request_dict解析请求字典

parsed_request_dict

{'method': 'POST', 'url': '/auth/login', 'params': {}, 'headers': {'Content-Type': 'application/json'}, 'req_json': {'username': 'tester', 'password': 'tester'}, 'data': None, 'cookies': {}, 'timeout': 120, 'allow_redirects': True, 'verify': False}

if step.setup_hooks:
    self.__call_hooks(step.setup_hooks, step.variables, "setup request")

如果存在setup_hooks就调用hook

 

 

# teardown hooks
if step.teardown_hooks:
    self.__call_hooks(step.teardown_hooks, step.variables, "teardown request")

如果存在teardown就调用hook

 最后返回step_dataHttpRunner3.x 源码解析(5)-runner.py

 HttpRunner3.x 源码解析(5)-runner.py

 

到了这里,关于HttpRunner3.x 源码解析(5)-runner.py的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • HttpRunner4.x 安装与使用

    以下只介绍Windows下 python 方式安装和使用 HttpRunner ,Linux下安装方式官方文档也写得很明确,只需执行一条 shell 命令,即可完成 hrp 的下载和安装操作。 安装 HttpRunner 存储于 PyPI, 支持通过pip命令安装,推荐安装到虚拟环境下,这样的话不同的虚拟环境可以使用不同版本的 H

    2023年04月08日
    浏览(20)
  • 使用这个插件,fiddler抓包直接生成httprunner脚本

    har2case可以将.har文件转化成yaml格式或者json格式的httprunner的脚本文件,生成.har格式文件可以借助 fiddler 或 Charles 抓包工具 友情提示: 录制脚本,只是一个过渡,从0到1的一个过渡,如果让你直接写脚本,你会无从下手,可以将录制的脚本快速转化成httprunner脚本文件,但是如

    2024年02月10日
    浏览(26)
  • HttpRunner v4 一条用例是怎么被执行的

    HttpRunner 4.0版本,支持多种用例的编写格式:YAML/JSON/go test/pytest,其中后面两种格式我们都知道通过调用测试函数执行,那YAML/JSON这两种用例格式到底是怎样被运行的呢?下面我们一起分析一下 注意:以下代码被缩略过,只保留核心代码,框架版本:4.3.0 hrp run case1 case2 在执

    2024年02月10日
    浏览(25)
  • python django vue httprunner 实现接口自动化平台(最终版)

    后端地址: GitHub - 18713341733/test_platform_service: django vue 实现接口自动化平台 前端地址: GitHub - 18713341733/test_platform_front: Django vue实现接口自动化平台 1.2.1 环境准备 Python = 3.8.0 (推荐3.9+版本) nodejs = 14.0 (推荐最新) 或者 16,千万不要使用18(会报错) Mysql = 5.7.0 (可选,默认数据库

    2024年02月10日
    浏览(25)
  • 以效率为导向:用ChatGPT和HttpRunner实现敏捷自动化测试(二)

    在上一篇文章: 利用ChatGPT提升测试工作效率——测试工程师的新利器(一)中,我们提到了如何通过chatGPT生成单接口测试用例,然后再让chatGPT去根据测试用例去生成接口自动化脚本。本篇文章将详细讲解一下我们团队内部在遇到业务痛点时如何利用Httprunner框架进行接口自动化

    2024年02月08日
    浏览(36)
  • 基于 HttpRunner + Django + Vue + Element UI 的接口自动化测试平台

    https://github.com/tahitimoon/LunarLink https://lunar-link-docs.fun 基于HttpRunner + Django + Vue + Element UI 的接口自动化测试平台,生产可用。 此外,非常感谢 花菜。没有 AnotherFasterRunner 就不会有 LunarLink 😃 🎨 Django 🎶 Django Rest framework 🎉 Vue.js 🎃 Element UI 🏐 django-celery-beat(定时任务) 🎲

    2024年04月11日
    浏览(32)
  • HttpRunner自动化测试工具之获取响应数据&extract提取值到变量

    获取响应数据 extract: 提取 注: extract 应与request保持同一层级 1、响应行,响应头;通过 extract 提取响应的数据并存储到变量中,如下图: 注:变量名的前面要有 -  # 获取响应数据: 响应行(200,ok)响应头 - config:     name: 测试百度网站     base_url: https://www.baidu.com - test:

    2024年02月02日
    浏览(49)
  • gitlab runner

    # install ``` # Download the binary for your system sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64 # Give it permission to execute sudo chmod +x /usr/local/bin/gitlab-runner # Create a GitLab Runner user sudo useradd --comment \\\'GitLab Runner\\\' --create-home gitlab-r

    2024年02月07日
    浏览(30)
  • gitlab-Runner搭建

    root wget https://packages.gitlab.com/runner/gitlab-runner/packages/fedora/29/gitlab-runner-12.6.0-1.x86_64.rpm/download.rpm rpm -ivh download.rpm ---- 安装 rpm -Uvh download.rpm -----更新升级 然后运行: gitlab-runner register --url https://gitlab.com --token glrt-Upn7mu 基于权限: root sudo chmod +x /usr/lib/gitlab-runner/gitlab-runner 直接运

    2024年02月14日
    浏览(41)
  • Junit执行器Runner探索之旅

    单元测试是每个程序员必备的技能,而Runner是每个单元测试类必有属性。本文通过解读Junit源码,介绍junit中每个执行器的使用方法,让读者在单元测试时,可以灵活的使用Runner执行器。 在今年的敏捷团队建设中,京东物流通过Suite执行器实现了一键自动化单元测试。Juint除了

    2024年02月08日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包