前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >HTTPretty - Python的HTTP客户端模拟

HTTPretty - Python的HTTP客户端模拟

作者头像
wangmcn
发布2024-11-25 13:34:49
发布2024-11-25 13:34:49
10500
代码可运行
举报
文章被收录于专栏:AllTests软件测试AllTests软件测试
运行总次数:0
代码可运行

1、前言

曾几何时,一个Python开发或测开人员想要使用RESTful API,一切都很好,但直到有一天他需要测试访问RESTful API的代码,如果API服务器坏了怎么办?如果它的内容发生了变化怎么办?

本篇将介绍一款Python的HTTP客户端模拟工具 - HTTPretty,由Gabriel Falcão创建,可以完整地伪造TCP socket模块。

2、简介

HTTPretty是一个Python库,它将模块socket和ssl与在TCP连接级别拦截HTTP请求的虚假实现进行交换,也就是它提供了一个完整的伪造TCP socket模块,它的灵感来自Ruby的FakeWeb。

功能特点:

  • API集成的测试驱动开发
  • 外部API的虚假响应
  • 记录和回放HTTP请求

安装:

pip install httpretty

GitHub地址:

https://github.com/gabrielfalcao/HTTPretty

3、快速上手

1、响应返回

代码语言:javascript
代码运行次数:0
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

import requests
import httpretty

def test_one():
    httpretty.enable(verbose=True, allow_net_connect=False) # 启用HTTPretty,以便它对socket模块进行猴子补丁
    httpretty.register_uri(httpretty.GET, "https://www.httpbin.org/get",
                           body='[{"username": "admin"}]',
                           content_type="application/json")

    response = requests.get('https://www.httpbin.org/get')

    assert response.text == '[{"username": "admin"}]'

    httpretty.disable() # 之后禁用,这样使用该socket模块的代码就不会出现问题
    httpretty.reset() # 重置HTTPretty状态(清理已注册的URL和请求历史记录)

2、在生成响应体的回调中进行断言

代码语言:javascript
代码运行次数:0
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

import requests
import json
import httpretty

@httpretty.activate
def test_with_callback_response():
    def request_callback(request, uri, response_headers):
        content_type = request.headers.get('Content-Type')
        assert request.body == '{"nothing": "here"}', 'unexpected body: {}'.format(request.body)
        assert content_type == 'application/json', 'expected application/json but received Content-Type: {}'.format(content_type)
        return [200, response_headers, json.dumps({"hello": "world"})]

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

    response = requests.post('https://httpretty.example.com/api', headers={'Content-Type': 'application/json'}, data='{"nothing": "here"}')

    expect(response.json()).to.equal({"hello": "world"})

3、通过正则表达式匹配URL

通过re.compile()传递一个编译后的正则表达式,用于拦截对特定主机的所有请求。

代码语言:javascript
代码运行次数:0
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公众号:AllTests软件测试

import re
import requests
import httpretty

@httpretty.activate(allow_net_connect=False, verbose=True)
def test_regex():
    httpretty.register_uri(httpretty.GET, re.compile(r'.*'), status=418)

    response1 = requests.get('http://foo.com')
    assert response1.status_code == 418

    response2 = requests.get('http://test.com')
    assert response2.status_code == 418
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-11-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AllTests软件测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档