我是新来的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类和validate方法被调用,有
json_data
? - 是
ValidationError
抛出并被调用?
这是我在编写测试用例时的尝试。我决定修补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()
我想将一些假数据和路径传递给我的方法,而不是尝试传递实际数据。我得到这个错误消息
UPDATE:
@patch('myproject.common.helper.jsonschema', Draft4Validator())
E TypeError: __init__() missing 1 required positional argument: 'schema'
如何去创造的2种方法特别Draft4Validator
以及如何补丁我模拟ValidationError
异常?