我是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()
我想测试的是:
json_data
调用了validate方法?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()
我想将一些假数据和路径传递给我的方法,而不是尝试传递真实数据。我收到此错误消息
更新
@patch('myproject.common.helper.jsonschema', Draft4Validator())
E TypeError: __init__() missing 1 required positional argument: 'schema'
如何专门针对2种方法Draft4Validator
创建补丁,以及如何模拟ValidationError
异常?
答案 0 :(得分:2)
您正在修补//Get users information
$sql = "SELECT user.uid, user.first, user.last, user.email, user.rating
FROM user
INNER JOIN team_members ON user.uid=team_members.uid
WHERE tid = '$tid'
ORDER BY user.last ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
//name as button(displayed on page load)
echo "<button class='player' type='button' data-uid='".$row["uid"]."'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none' data-uid='".$row["uid"]."'>
".$row["email"]." ".$row["rating"]."
</div>";
}
$(document).ready(function(){
$('button.player').click(function(){
$('div.player_info[data-uid='+$(this).attr('data-uid')+']').toggle();
});
});
错误。基本上你正在做的是创建一个没有所需参数的新Draft4Validator对象,并且每次都将它分配给Draft4Validator
调用(如果你使用所需的参数创建它)。
在此处详细了解:https://docs.python.org/3/library/unittest.mock-examples.html#patch-decorators
检查有关预期异常的断言检查:http://doc.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions
我想根据你的问题和要求你想要的东西是这样的:
myproject.common.helper.jsonschema