【发布时间】:2017-03-09 19:54:43
【问题描述】:
我是 python 测试的新手。我正在使用 pytest 并开始学习模拟和补丁。我正在尝试为我的一种方法编写一个测试用例。
helper.py
def validate_json_specifications(path_to_data_folder, json_file_path, json_data) -> None:
""" Validates the json data with a schema file.
:param path_to_data_folder: Path to the root folder where all the JSON & schema files are located.
:param json_file_path: Path to the json file
:param json_data: Contents of the json file
:return: None
"""
schema_file_path = os.path.join(path_to_data_folder, "schema", os.path.basename(json_file_path))
resolver = RefResolver('file://' + schema_file_path, None)
with open(schema_file_path) as schema_data:
try:
Draft4Validator(json.load(schema_data), resolver=resolver).validate(json_data)
except ValidationError as e:
print('ValidationError: Failed to validate {}: {}'.format(os.path.basename(json_file_path), str(e)))
exit()
我想测试的是:
- 是否已实例化 Draft4Validator 类并使用
json_data调用 validate 方法? - 是否抛出
ValidationError并调用exit?
到目前为止,这是我编写测试用例的尝试。我决定修补open 方法和Draft4Validator 类。
@patch('builtins.open', mock_open(read_data={}))
@patch('myproject.common.helper.jsonschema', Draft4Validator())
def test_validate_json_specifications(mock_file_open, draft_4_validator_mock):
validate_json_specifications('foo_path_to_data', 'foo_json_file_path', {})
mock_file_open.assert_called_with('foo_path_to_data/schema/foo_json_file_path')
draft_4_validator_mock.assert_called()
我想向我的方法传递一些虚假数据和路径,而不是尝试传递真实数据。我收到此错误消息
更新:
@patch('myproject.common.helper.jsonschema', Draft4Validator())
E TypeError: __init__() missing 1 required positional argument: 'schema'
如何为 2 种方法创建补丁,特别是 Draft4Validator 以及如何模拟 ValidationError 异常?
【问题讨论】:
标签: python python-3.x python-mock