Фон
Я хотел бы проверить следующие функции функции:
- Если условие выполнено, функция повышается
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