简体   繁体   English

正确测试记录错误消息并在不满足条件时引发SystemExit的功能

[英]Properly testing for a function that logs an error message and raises SystemExit if condition not met

Background 背景

I would like to test for the following behaviours of a function: 我想测试函数的以下行为:

  1. If condition is met function raises None 如果条件满足,则函数将引发None
  2. If condition is not met function: 如果条件不满足功能:
    • Outputs log message of ERROR level 输出ERROR级别的日志消息
    • Raises SystemExit 提高系统SystemExit

Example

The following trivial function checks if directory is accessible. 以下简单功能检查目录是否可访问。 The logging configuration logging.getLogger('__main__.' + __name__) is defined in __main__.py as the function is part of a package. 日志配置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

Testing 测试

 #########
 # 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()

Problem 问题

The last test errors: 最后的测试错误:

======================================================================
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

It seems to me that your error is actually on test_outputting_log_message , which you're not adding the with self.assertRaises context. 在我看来,您的错误实际上是在test_outputting_log_message ,您没有在with self.assertRaises添加with self.assertRaises上下文。 Since /wrong_path doesn't exist, the exception is raised just like in the previous test, but this time it's not expected in the test, so it breaks. 由于/wrong_path不存在,因此就像在先前的测试中一样引发了异常,但是这次在测试中不是预期的,因此它中断了。


Working solution 工作方案

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

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

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