虽然你可以使用 assert json.loads(expected) == json.loads(actual)
在一个故事步骤中匹配两个 JSON,但如果你使用 json_match(expected, actual)
,那么当它失败时
- 它会警告你是否失败是因为它不是有效的 JSON。
- 它将显示清晰格式化的实际 JSON、预期 JSON 和差异。
- 它将引发 Failure 异常,并避免在错误消息中包含完整的堆栈跟踪。
代码示例
example.story
Failing story:
steps:
- Pass because json matches
- Fail because strings don't match
from hitchstory import BaseEngine, json_match
class Engine(BaseEngine):
def pass_because_json_matches(self):
json_match(
"""{"a": 1, "b": 2}""",
"""{"b": 2, "a": 1}"""
)
def fail_because_strings_dont_match(self):
json_match(
"""{"a": 1, "b": 2}""",
"""{"b": 2, "a": 1, "d": 3}"""
)
带有代码
from hitchstory import StoryCollection
from engine import Engine
from pathlib import Path
story_collection = StoryCollection(Path(".").glob("*.story"), Engine())
story_collection.one().play()
将输出
RUNNING Failing story in /path/to/working/example.story ... FAILED in 0.1 seconds.
steps:
- Pass because json matches
- Fail because strings don't match
hitchstory.exceptions.Failure
Test failed.
ACTUAL:
{
"a": 1,
"b": 2,
"d": 3
}
EXPECTED:
{
"a": 1,
"b": 2
}
DIFF:
{
"a": 1,
- "b": 2
+ "b": 2,
? +
+ "d": 3
}
可执行规范
从 matching-json.story storytests 自动生成的文档。