python - 正确测试记录错误消息并在不满足条件时引发 SystemExit 的函数
问题描述
背景
我想测试一个函数的以下行为:
- 如果满足条件,则函数引发
None
- 如果条件不满足功能:
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
解决方案
在我看来,您的错误实际上是 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')
推荐阅读
- django - django 模型创建连接到 mssql
- jasper-reports - 如何将子数据集中的变量添加到报告中?[碧玉]
- three.js - 任何获取边界框面的方法
- javascript - 在反应日期上使用 moment.locale('de') 来显示德语翻译,但收到低于意外的输出
- autodesk-forge - 如何将模型从伪造场景导入地图(Google、arcGis 等)?
- python-3.x - 无法使用 os.system 执行查找
- reactjs - 使 React 组件在商店中更改状态时重新渲染
- json - 根据另一个键特定值获取特定键的所有值
- expo - 世博会:背景和封闭应用
- laravel - 使用 Laravel5 模块进行 Codeception api 测试:在单个 JsonResource 上应用 withoutWrapping() 会影响其他测试