我是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异常?

最佳答案

您在修补Draft4Validator错误。基本上,您要做的是创建一个没有必需参数的新Draft4Validator对象,并将其每次分配给myproject.common.helper.jsonschema调用(是否已使用必需参数创建了该对象)。

在此处了解更多信息:https://docs.python.org/3/library/unittest.mock-examples.html#patch-decorators

要检查有关预期异常的断言,请检查:http://doc.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions

我想根据您的问题和要求,您需要一些类似的东西:

@patch('sys.exit')
@patch('myproject.common.helper.jsonschema.Draft4Validator')
@patch('builtins.open')
def test_validate_json_specifications(mock_file_open, draft_4_validator_mock, exit_mock):
    with pytest.raises(ValidationError):
        mock_file_open.return_value = {}
        draft_4_validator_mock = Mock()
        draft_4_validator_mock.side_effect = ValidationError

        validate_json_specifications('foo_path_to_data', 'foo_json_file_path', {})

        assert draft_4_validator_mock.call_count == 1
        assert draft_4_validator_mock.validate.assert_called_with({})
        assert exit_mock.call_count == 1

关于python - 模拟文件打开并引发异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42704292/

10-12 22:57