import os import sys import unittest from unittest.mock import patch, MagicMock sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))) from o11ydiagnosis.subtasks.slowlogcompactor.task import Task class TestSlowlogCompactorTask(unittest.TestCase): def test_task_initialization(self): """Test that Task can be initialized with mock S3""" mock_s3 = MagicMock() task = Task( mock_s3, cluster="test-cluster", drhouse_bucket="test-bucket", drhouse_prefix="test/prefix/", drhouse_local_path="/tmp/test/", ) self.assertEqual(task.cluster, "test-cluster") self.assertEqual(task.drhouse_bucket, "test-bucket") # Task.__init__ calls rstrip("/") on drhouse_prefix, so trailing slash is removed self.assertEqual(task.drhouse_prefix, "test/prefix") self.assertEqual(task.drhouse_local_path, "/tmp/test") @patch('o11ydiagnosis.subtasks.slowlogcompactor.task.os.path.exists') @patch('o11ydiagnosis.subtasks.slowlogcompactor.task.os.makedirs') def test_task_prepare(self, mock_makedirs, mock_exists): """Test task prepare method""" mock_s3 = MagicMock() mock_s3.download.return_value = True # os.path.exists should return False for all paths (files don't exist) mock_exists.return_value = False task = Task( mock_s3, cluster="test-cluster", drhouse_bucket="test-bucket", drhouse_prefix="test/prefix/", drhouse_local_path="/tmp/test/", ) # Test prepare with mock # begin_hour_ts must be divisible by n_hours * 3600 # For n_hours=3, begin_hour_ts must be divisible by 10800 (3 * 3600) # Use a timestamp that is divisible by 10800 begin_hour_ts = 1712761200 # This is divisible by 10800 task.prepare(begin_hour_ts=begin_hour_ts, n_hours=3) # Verify prepare was called (if it has side effects we can check) self.assertIsNotNone(task) self.assertIsInstance(task.existed_statsdb_paths, dict) # Should have attempted to download 3 files (one for each hour) # Since os.path.exists returns False for all files, all 3 should be downloaded self.assertEqual(mock_s3.download.call_count, 3) # Verify that existed_statsdb_paths has 3 entries self.assertEqual(len(task.existed_statsdb_paths), 3) def test_task_attributes(self): """Test task has required attributes""" mock_s3 = MagicMock() task = Task( mock_s3, cluster="test-cluster", drhouse_bucket="test-bucket", drhouse_prefix="test/prefix/", drhouse_local_path="/tmp/test/", ) # Verify task has expected attributes self.assertTrue(hasattr(task, 'cluster')) self.assertTrue(hasattr(task, 'drhouse_bucket')) self.assertTrue(hasattr(task, 'drhouse_prefix')) self.assertTrue(hasattr(task, 'drhouse_local_path')) self.assertTrue(hasattr(task, 'existed_statsdb_paths')) self.assertTrue(hasattr(task, 'dirty_merged_statsdb_paths')) if __name__ == "__main__": unittest.main()