""" Unit tests related to install_log """ import unittest from unittest.mock import patch import install_log import datetime class InitLoggingTestCase(unittest.TestCase): """ Class to test init_logging method """ @patch("os.makedirs") @patch("os.path.exists", return_value=False) @patch("os.symlink") @patch("os.unlink") @patch("logging.FileHandler") @patch("logging.StreamHandler") def test_init_logging(self, mock_stream_handler, mock_file_handler, mock_unlink, mock_symlink, mock_exists, mock_makedirs): """ Test init_logging method """ # Setup lab_name = "lab1" log_path = "/some/log/path" current_time = datetime.datetime(2023, 6, 6, 10, 20, 30) expected_log_dir = f"{log_path}/{lab_name}/{current_time.year}_{current_time.month}_{current_time.day}_" \ f"{current_time.hour}_{current_time.minute}_{current_time.second}" with patch('install_log.datetime') as mock_date: mock_date.datetime.now.return_value = current_time # Run install_log.init_logging(lab_name, log_path) # Assert mock_exists.assert_called_once_with(expected_log_dir) mock_makedirs.assert_called_once_with(expected_log_dir) mock_file_handler.assert_called_once_with(f"{expected_log_dir}/install.log") mock_stream_handler.assert_called_once_with() mock_unlink.assert_called_once_with(f"{log_path}/{lab_name}/latest") mock_symlink.assert_called_once_with(expected_log_dir, f"{log_path}/{lab_name}/latest") @patch("os.makedirs") @patch("os.path.exists", return_value=False) @patch("os.symlink") @patch("os.unlink", side_effect=FileNotFoundError) @patch("logging.FileHandler") @patch("logging.StreamHandler") def test_init_logging_no_latest_link(self, mock_stream_handler, mock_file_handler, mock_unlink, mock_symlink, mock_exists, mock_makedirs): """ Test init_logging method when there's no latest link """ # Setup lab_name = "lab1" log_path = "/some/log/path" current_time = datetime.datetime(2023, 6, 6, 10, 20, 30) expected_log_dir = f"{log_path}/{lab_name}/{current_time.year}_{current_time.month}_{current_time.day}_" \ f"{current_time.hour}_{current_time.minute}_{current_time.second}" with patch('install_log.datetime') as mock_date: mock_date.datetime.now.return_value = current_time # Run install_log.init_logging(lab_name, log_path) # Assert mock_exists.assert_called_once_with(expected_log_dir) mock_makedirs.assert_called_once_with(expected_log_dir) mock_file_handler.assert_called_once_with(f"{expected_log_dir}/install.log") mock_stream_handler.assert_called_once_with() mock_unlink.assert_called_once_with(f"{log_path}/{lab_name}/latest") mock_symlink.assert_called_once_with(expected_log_dir, f"{log_path}/{lab_name}/latest") if __name__ == '__main__': unittest.main()