简体   繁体   English

Python 模拟:模拟 Class 的 function 引发错误

[英]Python Mock: Raising Error for function of Mocked Class

I'm trying to test some code that create or changes directories and files based on some inputs.我正在尝试测试一些根据某些输入创建或更改目录和文件的代码。 My issue is raising exceptions when a method of a mocked object is called.我的问题是在调用模拟 object 的方法时引发异常。 For example, say I have some code:例如,假设我有一些代码:

def create_if_not_exists(dest):
    dir = os.path.dirname(dest)
    if not dir:
        # create if it doesn't exist
        try:
           os.makedirs(os.path.dirname(dest))
        except OSError:
           pass # Nevermind what goes here, it's unimportant to the question

and a unit test:和单元测试:

@patch('my.package.os')
def test_create_dir_if_not_exists(self, mock_os):
    mock_os.path.dirname.return_value = None
    mock_os.makedirs.raiseError.side_effect = OSError()

    with self.assertRaises(OSError)
        create_if_not_exists('test')

This setup returns AssertionError: OSError not raised but my understanding is it should raise the error when the makedirs call is made in the actual (non-test) method.此设置返回AssertionError: OSError not raised但我的理解是当在实际(非测试)方法中进行makedirs调用时它应该引发错误。 Is my understanding incorrect?我的理解不正确吗?

Try with the following patch in the test file:尝试在测试文件中使用以下补丁:

@patch('my.package.os.path.dirname')
@patch('my.package.os.makedirs')
def test_create_dir_if_not_exists(self, mock_os_makedirs, mock_os_path_dirname):
    mock_os_path_dirname.return_value = None
    mock_os_makedirs.raiseError.side_effect = OSError()

    with self.assertRaises(OSError)
        create_if_not_exists('test')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM