跳转到主要内容

为单元测试提供HTTP请求模拟适配器。

项目描述

https://secure.travis-ci.org/ambv/requests-testadapter.png

目前是一个非常基础的模块,为requests提供适配器,用于模拟网络活动进行单元测试。

如何使用

此代码假定您的HTTP客户端以允许传递自定义Session对象的方式编写。在这种情况下,您只需要将适配器挂载以响应特定前缀即可。

>>> import requests
>>> from requests_testadapter import TestAdapter
>>> s = requests.Session()
>>> s.mount('http://', TestAdapter(b'Mock!', status=404))
>>> r = s.get('http://mocked.com')
>>> r.status_code
404
>>> r.text
'Mock!'

您还可以将headers字典作为关键字参数传递给TestAdapter

TestSession

在1.2.0及更早版本的requests中,挂载适配器的顺序是不可预测的。为了确保您可以使用各自的适配器挂载任意路径,请使用TestSession,它始终匹配最长前缀。

>>> from requests_testadapter import TestAdapter, TestSession
>>> s = TestSession()
>>> s.mount('http://git', TestAdapter(b'git'))
>>> s.mount('http://github', TestAdapter(b'github'))
>>> s.mount('http://github.com', TestAdapter(b'github.com'))
>>> s.mount('http://github.com/about/', TestAdapter(b'github.com/about'))
>>> r = s.get('http://github.com/about/')
>>> r.text
u'github.com/about'
>>> r = s.get('http://github.com')
>>> r.text
u'github.com'
>>> r = s.get('http://gittip.com')
>>> r.text
u'git'

TestSession不连接默认的HTTP和HTTPS处理器,因此如果您的请求在单元测试中无意中尝试连接外部网站,您将收到通知。

>>> r = s.get('http://bitbucket.org')
Traceback (most recent call last):
...
requests.exceptions.InvalidSchema: No connection adapters were found for
'http://bitbucket.org/'

如何运行测试?

最简单的方法是解压源tar包并运行

$ python test/test_testadapter.py

如果您系统上有所有兼容的Python实现,您可以使用tox在它们上面运行测试

$ pip install tox
$ tox
GLOB sdist-make: setup.py
py26 inst-nodeps: .tox/dist/requests-testadapter-0.1.0.zip
py26 runtests: commands[0]
..
----------------------------------------------------------------------
Ran 2 tests in 0.014s

OK
py27 inst-nodeps: .tox/dist/requests-testadapter-0.1.0.zip
py27 runtests: commands[0]
..
----------------------------------------------------------------------
Ran 2 tests in 0.014s

OK
py32 inst-nodeps: .tox/dist/requests-testadapter-0.1.0.zip
py32 runtests: commands[0]
..
----------------------------------------------------------------------
Ran 2 tests in 0.024s

OK
py33 inst-nodeps: .tox/dist/requests-testadapter-0.1.0.zip
py33 runtests: commands[0]
..
----------------------------------------------------------------------
Ran 2 tests in 0.017s

OK
_______________________________ summary ______________________________
  py26: commands succeeded
  py27: commands succeeded
  py32: commands succeeded
  py33: commands succeeded
  congratulations :)

变更日志

0.3.0

  • 修复了与requests 1.2.1+的兼容性问题

0.2.0

  • 引入了TestSession,以使在requests 1.2和旧版本中适配器的顺序可预测

  • 如果将stream=True传递给请求,TestAdapter不再预取response.content。这使得用户可以自行读取response.raw

0.1.0

  • 初始发布版本

作者

Łukasz Langa整合。由Luke Sneeringer提供额外修正。

项目详情


下载文件

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

源代码发行版

requests-testadapter-0.3.0.tar.gz (5.4 kB 查看哈希值)

上传时间 源代码

支持者