2017-03-09 30 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