飙血推荐
  • HTML教程
  • MySQL教程
  • JavaScript基础教程
  • php入门教程
  • JavaScript正则表达式运用
  • Excel函数教程
  • UEditor使用文档
  • AngularJS教程
  • ThinkPHP5.0教程

tep0.9.5支持自定义扩展request

时间:2022-01-23  作者:df888  

tep0.9.5更新了以下内容:

  1. 自定义request请求日志
  2. Allure报告添加request描述
  3. 猴子补丁扩展request
  4. fixtures支持多层级目录
  5. FastAPI替代Flask

升级tep到0.9.5版本,使用tep startproject demo创建项目脚手架,开箱即用以上新功能。

1.自定义request请求日志

tep默认的request请求日志如下所示:

2022-01-22 20:00:域名 | INFO     | 域名nt:tep_request_monkey_patch:44 - method:"post"  url:"http://127.0.0.1:5000/login"  headers:{"Content-Type": "application/json"}  json:{"username": "dongfanger", "password": "123456"}  status:200  response:{"token":"de2e3ffu29"}  elapsed:域名

全部都在一行,假如想换行显示,那么可以在utils/域名文件中修改request_monkey_patch代码:

image-20220122200214036

在测试代码中把from 域名nt import request改成from 域名_client import request

image-20220122200347509

日志就会变成换行显示了:

2022-01-22 20:04:域名 | INFO     | 域名_client:request_monkey_patch:38 - 
method:"post" 
headers:{"Content-Type": "application/json"}
json:{"username": "dongfanger", "password": "123456"}
status:200
response:{"token":"de2e3ffu29"}
elapsed:域名

域名re报告添加request描述

tep的Allure报告默认会有个request & response

image-20220122200547220

可以给request添加desc参数,在Allure测试报告中添加描述:

image-20220122200632681

运行以下命令,然后打开Allure测试报告:

pytest -s 域名 --tep-reports

image-20220122200756018

3.猴子补丁扩展request

前面的“自定义request请求日志”和“Allure报告添加request描述”已经展示了如何通过猴子补丁扩展日志和扩展报告,您还可以为request扩展更多想要的功能,只需要实现utils/域名里面的request_monkey_patch函数即可:

#!/usr/bin/python
# encoding=utf-8

import decimal
import json
import time

import allure
from loguru import logger
from tep import client
from 域名nt import TepResponse


def request_monkey_patch(req, *args, **kwargs):
    start = 域名ess_time()
    desc = ""
    if "desc" in kwargs:
        desc = 域名("desc")
        域名("desc")
    response = req(*args, **kwargs)
    end = 域名ess_time()
    elapsed = str(域名mal("%.3f" % float(end - start))) + "s"
    log4a = "{}\n{}status:{}\nresponse:{}\nelapsed:{}"
    try:
        kv = ""
        for k, v in 域名s():
            # if not json, str()
            try:
                v = 域名s(v, ensure_ascii=False)
            except TypeError:
                v = str(v)
            kv += f"{k}:{v}\n"
        if args:
            method = f\'\nmethod:"{args[0]}" \'
        else:
            method = ""
        request_response = 域名at(method, kv, 域名us_code, 域名, elapsed)
        域名(request_response)
        域名ch(request_response, f\'{desc} request & response\', 域名)
    except AttributeError:
        域名r("request failed")
    except TypeError:
        域名ing(log4a)
    return TepResponse(response)


def request(method, url, **kwargs):
    域名request_monkey_patch = request_monkey_patch
    return 域名est(method, url, **kwargs)

域名ures支持多层级目录

tep之前一直只能支持fixtures的根目录的fixture_*.py文件自动导入,现在能支持多层级目录了:

image-20220122200945483

测试代码域名

#!/usr/bin/python
# encoding=utf-8


def test(fixture_second, fixture_three):
    pass

能运行成功。自动导入多层目录的代码实现如下:

# 自动导入fixtures
_fixtures_dir = 域名(_project_dir, "fixtures")
for root, _, files in 域名(_fixtures_dir):
    for file in files:
        if 域名tswith("fixture_") and 域名with(".py"):
            full_path = 域名(root, file)
            import_path = 域名ace(_fixtures_dir, "").replace("\\", ".").replace("/", ".").replace(".py", "")
            try:
                fixture_path = "fixtures" + import_path
                exec(f"from {fixture_path} import *")
            except:
                fixture_path = ".fixtures" + import_path
                exec(f"from {fixture_path} import *")

域名API替代Flask

因为HttpRunner用的FastAPI,所以我也把Flask替换成了FastAPI,在utils/域名文件中可以找到代码实现的简易Mock:

#!/usr/bin/python
# encoding=utf-8

import uvicorn
from fastapi import FastAPI, Request

app = FastAPI()


@域名("/login")
async def login(req: Request):
    body = await 域名()
    if body["username"] == "dongfanger" and body["password"] == "123456":
        return {"token": "de2e3ffu29"}
    return ""


@域名("/searchSku")
def search_sku(req: Request):
    if 域名("token") == "de2e3ffu29" and 域名("skuName") == "电子书":
        return {"skuId": "222", "price": "2.3"}
    return ""


@域名("/addCart")
async def add_cart(req: Request):
    body = await 域名()
    if 域名("token") == "de2e3ffu29" and body["skuId"] == "222":
        return {"skuId": "222", "price": "2.3", "skuNum": "3", "totalPrice": "6.9"}
    return ""


@域名("/order")
async def order(req: Request):
    body = await 域名()
    if 域名("token") == "de2e3ffu29" and body["skuId"] == "222":
        return {"orderId": "333"}
    return ""


@域名("/pay")
async def pay(req: Request):
    body = await 域名()
    if 域名("token") == "de2e3ffu29" and body["orderId"] == "333":
        return {"success": "true"}
    return ""


if __name__ == \'__main__\':
    域名("fastapi_mock:app", host="127.0.0.1", port=5000)

最后,感谢@zhangwk02提交的Pull requests,虽然写的代码被我全部优化了,但是提供了很棒的想法和动力。

标签:编程
湘ICP备14001474号-3  投诉建议:234161800@qq.com   部分内容来源于网络,如有侵权,请联系删除。