首页 > 解决方案 > 正确测试记录错误消息并在不满足条件时引发 SystemExit 的函数

问题描述

背景

我想测试一个函数的以下行为:

  1. 如果满足条件,则函数引发None
  2. 如果条件不满足功能:
    • ERROR输出级别的日志消息
    • 加注SystemExit

例子

下面的简单函数检查目录是否可访问。日志记录配置logging.getLogger('__main__.' + __name__)定义__main__.py为函数是包的一部分。

###########
# Modules #
###########
import os


###########
# Logging #
###########
import logging
logger = logging.getLogger('__main__.' + __name__)


#############
# Functions #
#############

def check_directory_access(folder_path):
    """Test if directory is readable"""
    if os.access(folder_path, os.R_OK) is not True:
        logger.error("Provided folder %s is invalid", folder_path)
        raise SystemExit

测试

 #########
 # Tests #
 #########

 class TestDirectoryChecking(unittest.TestCase):
     """Unit test checking utility functions"""

     def test_return_none_correct_path(self):
         """Test if function checking for valid directory works"""
         # Should return None
         self.assertIsNone(utilities.check_directory_access(folder_path="/"))

     def test_raise_exception_wrong_path(self):
         """Raises sception for wrong path"""
         # Should raise a system exception
         with self.assertRaises(SystemExit):
             utilities.check_directory_access(folder_path="/wrong_path")

     def test_outputting_log_message(self):
         """Function returns log message in case of wrong directory"""
         with self.assertLogs(level='ERROR'):
             utilities.check_directory_access(folder_path="/wrong_path")


 if __name__ == '__main__':
     unittest.main()

问题

最后的测试错误:

======================================================================
ERROR: test_outputting_log_message (test_utility_functions.TestDirectoryChecking)
Function returns log message in case of wrong directory
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/module_path/tests/test_utility_functions.py", line 38, in test_outputting_log_message
    utilities.check_directory_access(folder_path="/wrong_path")
  File "/module_path/sample_module/utilities.py", line 30, in check_directory_access
    raise SystemExit
SystemExit

----------------------------------------------------------------------
Ran 4 tests in 0.001s

标签: pythonpython-3.xunit-testing

解决方案


在我看来,您的错误实际上是 on test_outputting_log_message,您没有添加with self.assertRaises上下文。因为/wrong_path不存在,所以就像在之前的测试中一样引发了异常,但是这次在测试中没有预料到,所以它会中断。


工作解决方案

 def test_outputting_log_message(self):
     """Function returns log message in case of wrong directory"""
     with self.assertRaises(SystemExit), self.assertLogs(level='ERROR') as log:
         utilities.check_directory_access(folder_path="/wrong_path")
     self.assertRegex(str(log), '.*Provided folder /wrong_path is invalid')

推荐阅读