提供一个适配器,用于模拟用于单元测试的http请求。
requests-testadapter的Python项目详细描述
当前是一个非常基本的模块,它为模拟单元网络活动的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。
测试会话
在requests1.2.0和更低版本中,装入适配器的顺序是 不可预知的。以确保可以用它们自己的路径装载任意路径 各自的适配器,使用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/'
如何运行测试?
最简单的方法是提取源tarball并运行:
$ 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
- 修复了与requests1.2.1+的兼容性问题
0.2.0
- 引入了TestSession以使适配器顺序在^{tt3}中可预测$ 1.2及以上
- TestAdapter不再预取response.content如果 stream=True被传递给请求。这允许用户读取 response.raw她自己。
0.1.0
- 初始发布版本