我是新來的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
異常?