未提供项目描述
项目描述
spymock
此库提供类似于 MagicMock
的 SpyMock
,但记录了函数返回值和异常在 call_values_or_exceptions
属性上。
安装
pip install python-spymock
用法
使用 spymock.spy
函数,就像 patch.object
一样,来监视和模拟目标属性,如下所示:
import urllib.request
from spymock import spy
def request():
url = "http://httpbin.org/json"
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as res:
return json.loads(res.read())
def test_request_with_spy():
with spy(urllib.request, "urlopen") as s:
assert request() == {
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
"slides": [
{"title": "Wake up to WonderWidgets!", "type": "all"},
{
"items": [
"Why <em>WonderWidgets</em> are great",
"Who <em>buys</em> WonderWidgets",
],
"title": "Overview",
"type": "all",
},
],
"title": "Sample Slide Show",
}
}
# 's' is like MagicMock but it has 'call_values_or_exceptions' attribute
assert len(s.call_values_or_exceptions) == 1
r = s.call_values_or_exceptions[0]
assert isinstance(r, HTTPResponse)
assert r.status == 200
assert r.reason == "OK"
或者直接创建类似于 MagicMock
的 spymock.SpyMock
实例,如下所示:
import urllib.request
from spymock import SpyMock
def request():
url = "http://httpbin.org/json"
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as res:
return json.loads(res.read())
def test_request_with_spymock():
s = SpyMock(request)
assert s() == {
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
"slides": [
{"title": "Wake up to WonderWidgets!", "type": "all"},
{
"items": [
"Why <em>WonderWidgets</em> are great",
"Who <em>buys</em> WonderWidgets",
],
"title": "Overview",
"type": "all",
},
],
"title": "Sample Slide Show",
}
}
# 's' is like MagicMock but it has 'call_values_or_exceptions' attribute
assert len(s.call_values_or_exceptions) == 1
r = s.call_values_or_exceptions[0]
assert r == {
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
"slides": [
{"title": "Wake up to WonderWidgets!", "type": "all"},
{
"items": [
"Why <em>WonderWidgets</em> are great",
"Who <em>buys</em> WonderWidgets",
],
"title": "Overview",
"type": "all",
},
],
"title": "Sample Slide Show",
}
}
许可证
根据 MIT许可证 分布。
项目详情
关闭
python-spymock-0.3.0.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | adad41ff7d67ca7256bc9d07137e3669846b95c0d0abe052dde9fbfa332406f5 |
|
MD5 | 14fb236aa2c2cb25843c80e8850a5602 |
|
BLAKE2b-256 | 4a70404a0606d834b002f2e6f4fdacb968e9a17ab70535c64e341c524b3ecfcb |
关闭
python_spymock-0.3.0-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 17e316354dd7be54edc69ebcfd2384be0764792f507f8591ccfb6c1c2d3b4305 |
|
MD5 | f4506ca57dfe40d597c623710c97e832 |
|
BLAKE2b-256 | cc1a58860a03801bebf0e45b95148e9472d30aad6cb1a74e3b1a954ff3135fd2 |