2017-03-09 36 views
1

我是新来的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() 

事情我想测试是:

  1. 被实例化的Draft4Validator类和validate方法被调用,有json_data
  2. 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异常?

回答

2

您正在修补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