Python Mock:模拟类函数引发错误

问题描述 投票:0回答:1

我正在尝试测试一些根据某些输入创建或更改目录和文件的代码。我的问题是在调用模拟对象的方法时引发异常。例如,假设我有一些代码:

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

和单元测试:

@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')

此设置返回

AssertionError: OSError not raised
但我的理解是,当在实际(非测试)方法中进行
makedirs
调用时,它应该会引发错误。难道我的理解有误?

python unit-testing mocking magicmock
1个回答
0
投票

尝试在测试文件中使用以下补丁:

@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() <--- REMOVE raiseError
    mock_os_makedirs.side_effect = OSError()

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

此外,您的函数

create_if_not_exists()
不得捕获
OSError
异常;所以你的
create_if_not_exists()
函数必须修改如下:

import os

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

否则测试失败。

你的测试也很好

在您的测试中,唯一的问题是指令:

mock_os.makedirs.raiseError.side_effect = OSError()

因此,您测试的另一个解决方案是:

  • 删除生产代码中的
    try-except OSError
  • 更改您的测试代码如下:
@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() <--- REMOVE raiseError
    mock_os.makedirs.side_effect = OSError()

    with self.assertRaises(OSError):
        create_if_not_exists('test')
© www.soinside.com 2019 - 2024. All rights reserved.