跳转到主要内容

模拟Web服务器以测试Web客户端

项目描述

webmock
=======

此工具提供在临时端口上的进程内WSGI服务器。
它旨在用于单元测试,当待测试的系统进行无法轻松模拟的外出HTTP连接时。

用法
-----

首先,创建一个表示您要创建的伪造Web服务器的WSGI应用程序。
这比看起来要简单;例如:

def simple_app(environ, start_response)
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return ['Hello, world!\n']

接下来,激活测试服务器。
有几种方法可以做到这一点,但它们都会产生一个端口号。

作为上下文管理器:

from mockweb import mock_server
def test_web_request()
with mock_server(simple_app) as port
my_client.get_greeting('http://127.0.0.1:{}'.format(port))

作为装饰器:

from mockweb import mock_server
@mock_server(simple_app)
def test_web_request(port)
my_client.get_greeting('http://127.0.0.1:{}'.format(port))

或者手动启动和停止:

from mockweb import mock_server
@mock_server
def test_web_request()
server = mock_server(simple_app)
# ...
server.start()
my_client.get_greeting('http://127.0.0.1:{}'.format(port))
server.stop()

在后一种情况下,请务必停止服务器。

模拟应用程序
--------

``webmock``软件包包括一个简单的WSGI应用程序,其行为类似于Python的``Mock``:它接受并记录任何请求,允许测试在操作完成后进行断言。

它的用法很简单

from mockweb import mock_server, MockApp

app = MockApp()
with mock_server(app)
# ..
app.assert_called_with('GET /foo/bar')

可用的断言方法有

** ``assert_called_with(call)`` -- 断言最近请求与 ``call`` 匹配
** ``assert_called_once_with(call)`` -- 断言只有一个请求被发出且与 ``call`` 匹配
** ``assert_any_call(call)`` -- 断言任何请求与 ``call`` 匹配
** ``assert_has_call([call, call, ..], any_order=False)`` -- 断言给定的所有调用都已发生。
如果 ``any_order`` 为 false,调用必须是顺序的。

调用可以用包含方法和路径的字符串来描述。

可以以一些小的方式调整模拟应用程序的行为。
对于更复杂的事情,构建自定义 WSGI 应用程序。

** ``MockApp(response='403 Forbidden')`` -- 自定义 HTTP 响应(默认为 "200 OK")
** ``MockApp(body='hello world\n')`` -- 自定义响应体(默认为空)
** ``MockApp(headers=[('X-Auth', 'abc123')])`` -- 自定义响应头

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源代码分发

本发布没有可用的源代码分发文件。请参阅 生成分发存档的教程

构建分发

webmock-1.1.0-py2.py3-none-any.whl (6.3 kB 查看哈希值)

上传时间 Python 2 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面