httprunner 3.x学习14 - 上传文件(upload)

前言

requests 库里面上传文件会用到 requests_toolbelt, 可以很方便的解决 multipart/form-data 类型的文件上传相关接口。
HttpRunner3.x 集成了 requests_toolbelt,可以使用内置 upload 关键字来上传文件相关操作。
相关环境:

  • httprunner 3.1.4
  • requests_toolbelt
  • filetype

使用示例

使用 upload 关键字,上传文件(2.4.1以上版本)

teststeps:
- 
    name: upload file
    request:
        url: http://httpbin.org/upload
        method: POST
        headers:
            Cookie: session=AAA-BBB-CCC
        upload:
            file: "data/file_to_upload"
            field1: "value1"
            field2: "value2"
    validate:
        - eq: ["status_code", 200]

参考案例:文件上传multipart/form-data

用fiddler抓包,查看抓到的接口,以下这种接口就是multipart/form-data

  • Content-Type: multipart/form-data
  • body参数是这种格式:

-----------------------------22165374713946
Content-Disposition: form-data; name="localUrl"

yoyoketang.png
-----------------------------22165374713946
Content-Disposition: form-data; name="imgFile"; filename="yoyoketang.png"
Content-Type: image/png

httprunner3.x 脚本文件上传使用 upload 关键字,文件放 data 目录下

yaml脚本示例

# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

config:
    name: file
    base_url: ${ENV(base_url)}
    variables:
        filename: data/hrun.png
        titlename: 上海-悠悠
teststeps:
-
    name: upload file
    request:
        url: /api/v1/upfile/
        method: POST
        upload:
            file: $filename
            title: $titlename

pytest脚本示例

# NOTE: Generated By HttpRunner v3.1.4
# FROM: testcases\upfile.yml
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

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


class TestCaseUpfile(HttpRunner):

    config = (
        Config("file")
        .variables(**{"filename": "data/hrun.png", "titlename": "上海-悠悠"})
        .base_url("${ENV(base_url)}")
    )

    teststeps = [
        Step(
            RunRequest("upload file")
            .post("/api/v1/upfile/")
            .upload(**{"file": "$filename", "title": "$titlename"})
        ),
    ]


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

网易云课程地址



点我 ->立即报名

posted @ 2021-06-22 10:23  上海-悠悠  阅读(1273)  评论(2编辑  收藏  举报