如何为这个场景编写单元测试用例

How to write unit test case for this scenario

我正尝试在 main.py

中为以下方法编写单元测试用例
def create_tmp_dir(tmp_dir): 
    logger.info('{app} Creating directory: {arg}'.format(
       app=app_log, arg=tmp_dir))
    mkdir_cmd = 'mkdir -p ' + tmp_dir
    try:
       utility.simple_cmd(mkdir_cmd)
    except Exception, exc:
       logger.critical('{app} Unable to create dir: {arg}'.format(app=app_log, arg=exc))
       exit(1)

utility.py 中的 simple_cmd 方法可以:

def simple_cmd(cmd):
    subprocess.call(cmd, shell=True, stdout=subprocess.PIPE)

这是我的测试_main.py

def test_create_tmp_dir_raises_exception_on_blank_dir():
    with patch('utility.simple_cmd'):
        with pytest.raises(Exception):
            main.create_tmp_dir('')

当我 运行 pytest 时,它说没有引发异常

        with patch('utility.simple_cmd'):
            with pytest.raises(Exception):
>               main.create_tmp_dir('')
E               Failed: DID NOT RAISE <type 'exceptions.Exception'>

create_tmp_dir 不会引发 Exception — 它捕获它并转换为 SystemExit,它是 BaseException 的子类,而不是 Exception,因此你的 pytest.raises(Exception) 没听懂。

重新引发异常而不是退出:

except Exception, exc:
   logger.critical('{app} Unable to create dir: {arg}'.format(app=app_log, arg=exc))
   raise

@phd 感谢您的回复,实际上我无法更改源代码。所以我找到的解决方案是,我应该将 side_effect 设置为 Exception 并引发 SystemExit.

def test_create_tmp_dir_exits_on_exception():
    with patch('utility.simple_cmd') as SimpleCmdMock:
        SimpleCmdMock.side_effect = Exception
        with pytest.raises(SystemExit):
            assert main.create_tmp_dir('Some_Directory') is None