httpretty,一个Mock Http请求的库

介绍:

HTTPretty是一个用于在测试环境中模拟HTTP请求和响应。允许开发者在不实际进行网络调用的情况下,完全控制HTTP交互。通过拦截网络请求并提供预定义的响应。使用HTTPretty,开发者可以模拟各种网络条件,如延迟、错误和超时。

安装

pip install httpretty

  

使用HTTPretty 模拟一个HTTP GET 请求的响应

import httpretty
import requests

httpretty.enable()  # 开启HTTPretty

httpretty.register_uri(httpretty.GET, "https://www.wen.com/index",
                       body='{"result": "success", "code": "1", "data": [1, 2, 3]}',
                       adding_headers={'Content-Type': 'application/json'})

response = requests.get("https://www.wen.com/index")
print(response.json())

httpretty.disable()  # 关闭HTTPretty
httpretty.reset()    # 重置HTTPretty状态

 

使用 HTTPretty 模拟一个HTTP POST请求的响应

import httpretty
import requests

httpretty.enable()

httpretty.register_uri(httpretty.POST, "https://www.wenx.com/index",
                       body='{"status": "received", "msg": "ok"}',
                       adding_headers={'Content-Type': 'application/json'})

response = requests.post("https://www.wenx.com/index", data={"name": "Miko"})
print(response.json())

httpretty.disable()
httpretty.reset()

  

错误处理模拟

模拟错误响应是测试中一个重要的部分,HTTPretty 可以模拟不同的HTTP状态代码和错误信息。通过设置status参数,模拟了一个返回404状态码的HTTP请求。

import httpretty
import requests

httpretty.enable()

httpretty.register_uri(httpretty.GET, "https://api.example.com/notfound",
                       status=404)

response = requests.get("https://api.example.com/notfound")
print(response.status_code)

httpretty.disable()
httpretty.reset()

  

动态响应内容

HTTPretty 允许使用回调函数来动态生成响应内容,这在需要根据请求内容自定义响应时非常有用。

这个示例展示了如何根据请求头中的Content-Type动态调整响应内容。

import httpretty
import requests

httpretty.enable()


def request_callback(request, uri, response_headers):
    content_type = request.headers.get('Content-Type')
    if content_type == 'application/json':
        return [200, response_headers, '{"message": "JSON received"}']
    else:
        return [200, response_headers, "Received"]


httpretty.register_uri(httpretty.POST, "https://api.example.com/submit",
                       body=request_callback)


response1 = requests.post("https://api.example.com/submit", json={"key": "value"})
print(response1.text)

response2 = requests.post("https://api.example.com/submit", data={"key": "value"})
print(response2.text)

httpretty.disable()
httpretty.reset()

  

延迟响应

模拟网络延迟可以帮助测试应用在慢速网络环境下。这个示例演示了如何模拟网络延迟,通过在响应函数中加入sleep来实现。

import httpretty
import requests
import time

httpretty.enable()


def delayed_response(request, uri, response_headers):
    time.sleep(2)  # 延迟2秒
    return [200, response_headers, '{"message": "Delayed response"}']


httpretty.register_uri(httpretty.GET, "https://api.example.com/delay",
                       body=delayed_response)

response = requests.get("https://api.example.com/delay")
print(response.json())

httpretty.disable()
httpretty.reset()

  

流式响应

HTTPretty还支持模拟流式响应,这对于测试处理如视频流或大数据下载的应用非常有用。通过生成器streaming_body来模拟一个流式响应。

import httpretty
import requests

httpretty.enable()


def streaming_body():
    yield "Hello"
    yield " "
    yield "world!"


# 生成器转换成列表
body_list = list(streaming_body())

httpretty.register_uri(httpretty.GET, "https://api.example.com/stream",
                       body=''.join(body_list))

response = requests.get("https://api.example.com/stream", stream=True)
print(''.join(response.iter_content(decode_unicode=True)))  # 输出流式响应内容

httpretty.disable()
httpretty.reset()

  

 

实际应用场景

单元测试

HTTPretty 常用于单元测试,尤其是在测试涉及外部API调用的功能时。通过模拟API响应,开发者可以确保他们的代码在各种网络条件下都能正常工作。测试一个依赖外部API的功能,确保在API响应延迟时,应用能正确处理。

import time
import httpretty
import requests

httpretty.enable()


# 模拟API响应延迟
def delayed_weather_api(request, uri, response_headers):
    time.sleep(2)
    return [200, response_headers, '{"temperature": "test"}']


httpretty.register_uri(httpretty.GET, "https://weatherapi.example.com/today",
                       body=delayed_weather_api)


# 测试应用如何处理延迟
def test_weather():
    response = requests.get("https://weatherapi.example.com/today")
    if response.status_code == 200:
        return response.json()['temperature']
    else:
        return "Error"


print(test_weather())
httpretty.disable()
httpretty.reset()

  

集成测试

在集成测试中,HTTPretty可以用来模拟服务间的交互,特别是在微服务架构中。在微服务架构中,模拟一个服务失败的情况,测试系统的容错能力。

import httpretty
import requests

httpretty.enable()

# 模拟服务失败
httpretty.register_uri(httpretty.GET, "https://paymentservice.example.com/charge",
                       status=500)


# 测试系统如何响应服务失败
def process_payment():
    response = requests.get("https://paymentservice.example.com/charge")
    if response.status_code == 500:
        return "Service Error"
    else:
        return "OK"


print(process_payment())

httpretty.disable()
httpretty.reset()

  

性能测试

使用HTTPretty模拟不同网络条件,测试应用的性能。模拟网络拥堵和高延迟,测试应用的响应时间和用户体验。

import time
import httpretty
import requests

httpretty.enable()


# 模拟高延迟网络
def high_latency_simulation(request, uri, response_headers):
    time.sleep(5)  # 5秒高延迟
    return [200, response_headers, '{"status": "ok"}']


httpretty.register_uri(httpretty.GET, "https://api.example.com/data",
                       body=high_latency_simulation)

response = requests.get("https://api.example.com/data")
print("Response time:", response.elapsed.total_seconds(), "seconds")  # 输出响应时间

httpretty.disable()
httpretty.reset()

  

posted @ 2024-05-24 15:04  北京测试菜鸟  阅读(49)  评论(0编辑  收藏  举报