Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/modules/test_logrotate.py

raw
1 # Copyright (c) 2026 Aleksandr Gabidullin <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 import os
8 import shutil
9 import sys
10 import tempfile
11 import unittest
12 from unittest.mock import Mock, mock_open, patch
13
14
15 class TestLogrotateConfig(unittest.TestCase):
16 """Unit tests for the logrotate_config module."""
17
18 @classmethod
19 def setUpClass(cls):
20 """Set up test environment."""
21 cls.test_dir = tempfile.mkdtemp()
22 cls.mock_ansible_basic = Mock()
23 cls.mock_ansible_basic.AnsibleModule = Mock()
24 cls.mock_converters = Mock()
25 cls.mock_converters.to_native = str
26 cls.patcher_basic = patch.dict(
27 "sys.modules",
28 {
29 "ansible.module_utils.basic": cls.mock_ansible_basic,
30 "ansible.module_utils.common.text.converters": cls.mock_converters,
31 },
32 )
33 cls.patcher_basic.start()
34
35 @classmethod
36 def tearDownClass(cls):
37 """Clean up after all tests."""
38 cls.patcher_basic.stop()
39 if os.path.exists(cls.test_dir):
40 shutil.rmtree(cls.test_dir)
41
42 def setUp(self):
43 """Set up test fixtures."""
44 self.mock_ansible_basic.AnsibleModule.reset_mock()
45 self.mock_module = Mock()
46 self.mock_module.params = {}
47 self.mock_module.fail_json = Mock(side_effect=Exception("fail_json called"))
48 self.mock_module.exit_json = Mock()
49 self.mock_module.check_mode = False
50 self.mock_module.get_bin_path = Mock(return_value="/usr/sbin/logrotate")
51 self.mock_module.atomic_move = Mock()
52 self.mock_module.warn = Mock()
53 self.mock_module.run_command = Mock(return_value=(0, "", ""))
54 self.mock_module.backup_local = Mock(return_value=None)
55 self.mock_module.tmpdir = self.test_dir
56 self.mock_ansible_basic.AnsibleModule.return_value = self.mock_module
57 self.config_dir = os.path.join(self.test_dir, "logrotate.d")
58 os.makedirs(self.config_dir, exist_ok=True)
59 for module_name in list(sys.modules.keys()):
60 if "logrotate" in module_name or "ansible_collections.community.general.plugins.modules" in module_name:
61 del sys.modules[module_name]
62
63 def tearDown(self):
64 """Clean up after test."""
65 pass
66
67 def _setup_module_params(self, **params):
68 """Helper to set up module parameters."""
69 default_params = {
70 "name": "test",
71 "state": "present",
72 "config_dir": self.config_dir,
73 "paths": ["/var/log/test/*.log"],
74 "rotate_count": 7,
75 "compress": True,
76 "compression_method": "gzip",
77 "delay_compress": False,
78 "missing_ok": True,
79 "not_if_empty": True,
80 "copy_truncate": False,
81 "date_ext": False,
82 "date_format": "-%Y%m%d",
83 "shared_scripts": False,
84 "enabled": True,
85 "backup": True,
86 }
87 default_params.update(params)
88 self.mock_module.params = default_params
89
90 def test_create_new_configuration(self):
91 """Test creating a new logrotate configuration."""
92 from ansible_collections.community.general.plugins.modules import logrotate
93
94 self._setup_module_params()
95 config_path = os.path.join(self.config_dir, "test")
96
97 def exists_side_effect(path):
98 if path == self.config_dir:
99 return True
100 elif path == config_path:
101 return False
102 return False
103
104 with patch("os.path.exists", side_effect=exists_side_effect):
105 with patch("os.chmod") as mock_chmod:
106 logrotate_bin = self.mock_module.get_bin_path.return_value
107 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
108 result = config.apply()
109 self.assertTrue(result["changed"])
110 self.assertIn("config_file", result)
111 self.assertIn("config_content", result)
112 self.assertEqual(result["enabled_state"], True)
113 mock_chmod.assert_called_once()
114
115 def test_update_existing_configuration(self):
116 """Test updating an existing logrotate configuration."""
117 from ansible_collections.community.general.plugins.modules import logrotate
118
119 self._setup_module_params(rotate_count=14)
120 config_path = os.path.join(self.config_dir, "test")
121 existing_content = """/var/log/test/*.log {
122 daily
123 rotate 7
124 compress
125 delaycompress
126 missingok
127 notifempty
128 }"""
129
130 def exists_side_effect(path):
131 if path == self.config_dir:
132 return True
133 elif path == config_path:
134 return True
135 return False
136
137 with patch("os.path.exists", side_effect=exists_side_effect):
138 with patch("builtins.open", mock_open(read_data=existing_content)):
139 with patch("os.remove") as mock_remove:
140 with patch("os.chmod") as mock_chmod:
141 logrotate_bin = self.mock_module.get_bin_path.return_value
142 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
143 result = config.apply()
144 self.assertTrue(result["changed"])
145 self.assertIn("14", result["config_content"])
146 mock_remove.assert_not_called()
147 mock_chmod.assert_called_once()
148
149 def test_remove_configuration(self):
150 """Test removing a logrotate configuration."""
151 from ansible_collections.community.general.plugins.modules import logrotate
152
153 self._setup_module_params(state="absent")
154 config_path = os.path.join(self.config_dir, "test")
155
156 def exists_side_effect(path):
157 if path == self.config_dir:
158 return True
159 return path in (config_path, config_path + ".disabled")
160
161 with patch("os.path.exists", side_effect=exists_side_effect):
162 with patch("os.remove") as mock_remove:
163 logrotate_bin = self.mock_module.get_bin_path.return_value
164 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
165 result = config.apply()
166 self.assertTrue(result["changed"])
167 self.assertTrue(mock_remove.called)
168
169 def test_disable_configuration(self):
170 """Test disabling a logrotate configuration."""
171 from ansible_collections.community.general.plugins.modules import logrotate
172
173 self._setup_module_params(enabled=False)
174 config_path = os.path.join(self.config_dir, "test")
175 existing_content = """/var/log/test/*.log {
176 daily
177 rotate 7
178 }"""
179
180 def exists_side_effect(path):
181 if path == self.config_dir:
182 return True
183 elif path == config_path:
184 return True
185 return False
186
187 with patch("os.path.exists", side_effect=exists_side_effect):
188 with patch("builtins.open", mock_open(read_data=existing_content)):
189 with patch("os.remove"):
190 with patch("os.chmod"):
191 mock_file_write = mock_open()
192 with patch("builtins.open", mock_file_write):
193 logrotate_bin = self.mock_module.get_bin_path.return_value
194 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
195 result = config.apply()
196 self.assertTrue(result["changed"])
197 self.assertEqual(result["enabled_state"], False)
198 self.assertTrue(result["config_file"].endswith(".disabled"))
199
200 def test_enable_configuration(self):
201 """Test enabling a disabled logrotate configuration."""
202 from ansible_collections.community.general.plugins.modules import logrotate
203
204 self._setup_module_params(enabled=True)
205 config_path = os.path.join(self.config_dir, "test")
206 existing_content = """/var/log/test/*.log {
207 daily
208 rotate 7
209 }"""
210
211 def exists_side_effect(path):
212 if path == self.config_dir:
213 return True
214 elif path == config_path + ".disabled":
215 return True
216 return False
217
218 with patch("os.path.exists", side_effect=exists_side_effect):
219 with patch("builtins.open", mock_open(read_data=existing_content)):
220 with patch("os.remove"):
221 with patch("os.chmod"):
222 self.mock_module.atomic_move = Mock()
223 logrotate_bin = self.mock_module.get_bin_path.return_value
224 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
225 result = config.apply()
226 self.assertTrue(result["changed"])
227 self.assertEqual(result["enabled_state"], True)
228 self.assertFalse(result["config_file"].endswith(".disabled"))
229
230 def test_validation_missing_paths(self):
231 """Test validation when paths are missing for new configuration."""
232 from ansible_collections.community.general.plugins.modules import logrotate
233
234 self._setup_module_params(paths=None)
235 config_path = os.path.join(self.config_dir, "test")
236
237 def exists_side_effect(path):
238 if path == self.config_dir:
239 return True
240 elif path == config_path:
241 return False
242 return False
243
244 with patch("os.path.exists", side_effect=exists_side_effect):
245 logrotate_bin = self.mock_module.get_bin_path.return_value
246 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
247 with self.assertRaises(Exception) as context:
248 config.apply()
249 self.assertIn("fail_json called", str(context.exception))
250
251 def test_check_mode(self):
252 """Test that no changes are made in check mode."""
253 from ansible_collections.community.general.plugins.modules import logrotate
254
255 self._setup_module_params()
256 self.mock_module.check_mode = True
257 config_path = os.path.join(self.config_dir, "test")
258
259 def exists_side_effect(path):
260 if path == self.config_dir:
261 return True
262 elif path == config_path:
263 return False
264 return False
265
266 with patch("os.path.exists", side_effect=exists_side_effect):
267 with patch("builtins.open", mock_open()):
268 logrotate_bin = self.mock_module.get_bin_path.return_value
269 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
270 result = config.apply()
271 self.assertTrue(result["changed"])
272
273 def test_generate_config_with_scripts(self):
274 """Test generating configuration with pre/post scripts."""
275 from ansible_collections.community.general.plugins.modules import logrotate
276
277 self._setup_module_params(
278 pre_rotate=["echo 'Pre-rotation'"],
279 post_rotate=["systemctl reload test", "logger 'Rotation done'"],
280 first_action=["echo 'First action'"],
281 last_action=["echo 'Last action'"],
282 )
283 config_path = os.path.join(self.config_dir, "test")
284
285 def exists_side_effect(path):
286 if path == self.config_dir:
287 return True
288 elif path == config_path:
289 return False
290 return False
291
292 with patch("os.path.exists", side_effect=exists_side_effect):
293 with patch("builtins.open", mock_open()):
294 with patch("os.chmod"):
295 logrotate_bin = self.mock_module.get_bin_path.return_value
296 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
297 result = config.apply()
298 content = result["config_content"]
299 self.assertIn("prerotate", content)
300 self.assertIn("postrotate", content)
301 self.assertIn("firstaction", content)
302 self.assertIn("lastaction", content)
303 self.assertIn("systemctl reload test", content)
304 self.assertIn("echo 'Pre-rotation'", content)
305
306 def test_compression_methods(self):
307 """Test different compression methods."""
308 from ansible_collections.community.general.plugins.modules import logrotate
309
310 compression_methods = ["gzip", "bzip2", "xz", "zstd", "lzma", "lz4"]
311 for method in compression_methods:
312 with self.subTest(method=method):
313 self._setup_module_params(compression_method=method)
314 config_path = os.path.join(self.config_dir, "test")
315
316 def exists_side_effect(path, current_config_path=config_path):
317 if path == self.config_dir:
318 return True
319 elif path == current_config_path:
320 return False
321 return False
322
323 with patch("os.path.exists", side_effect=exists_side_effect):
324 with patch("builtins.open", mock_open()):
325 with patch("os.chmod"):
326 logrotate_bin = self.mock_module.get_bin_path.return_value
327 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
328 result = config.apply()
329 content = result["config_content"]
330 if method != "gzip":
331 self.assertIn(f"compresscmd /usr/bin/{method}", content)
332 if method == "zstd" or method == "lz4":
333 self.assertIn(f"uncompresscmd /usr/bin/{method} -d", content)
334 else:
335 uncompress_cmd = f"{method}un{method}"
336 self.assertIn(f"uncompresscmd /usr/bin/{uncompress_cmd}", content)
337
338 def test_size_based_rotation(self):
339 """Test size-based rotation configuration."""
340 from ansible_collections.community.general.plugins.modules import logrotate
341
342 self._setup_module_params(size="100M", rotation_period="daily")
343 config_path = os.path.join(self.config_dir, "test")
344
345 def exists_side_effect(path):
346 if path == self.config_dir:
347 return True
348 elif path == config_path:
349 return False
350 return False
351
352 with patch("os.path.exists", side_effect=exists_side_effect):
353 with patch("builtins.open", mock_open()):
354 with patch("os.chmod"):
355 logrotate_bin = self.mock_module.get_bin_path.return_value
356 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
357 result = config.apply()
358 content = result["config_content"]
359 self.assertIn("size 100M", content)
360 self.assertNotIn("daily", content)
361
362 def test_logrotate_not_installed(self):
363 """Test error when logrotate is not installed."""
364 from ansible_collections.community.general.plugins.modules import logrotate
365
366 mock_module_for_test = Mock()
367 mock_module_for_test.params = {
368 "name": "test",
369 "state": "present",
370 "config_dir": self.config_dir,
371 "paths": ["/var/log/test/*.log"],
372 "rotate_count": 7,
373 "compress": True,
374 "compression_method": "gzip",
375 "delay_compress": False,
376 "missing_ok": True,
377 "not_if_empty": True,
378 "copy_truncate": False,
379 "date_ext": False,
380 "date_format": "-%Y%m%d",
381 "shared_scripts": False,
382 "enabled": True,
383 }
384 mock_module_for_test.fail_json = Mock(side_effect=Exception("fail_json called"))
385 mock_module_for_test.exit_json = Mock()
386 mock_module_for_test.check_mode = False
387
388 def get_bin_path_side_effect(name, required=False):
389 if name == "logrotate" and required:
390 mock_module_for_test.fail_json(msg=f"Failed to find required executable '{name}' in PATH")
391 return None
392
393 mock_module_for_test.get_bin_path = Mock(side_effect=get_bin_path_side_effect)
394 mock_module_for_test.atomic_move = Mock()
395 mock_module_for_test.warn = Mock()
396 mock_module_for_test.run_command = Mock(return_value=(0, "", ""))
397
398 with patch(
399 "ansible_collections.community.general.plugins.modules.logrotate.AnsibleModule",
400 return_value=mock_module_for_test,
401 ):
402 with self.assertRaises(Exception) as context:
403 logrotate.main()
404
405 self.assertIn("fail_json called", str(context.exception))
406
407 mock_module_for_test.get_bin_path.assert_called_once_with("logrotate", required=True)
408 mock_module_for_test.fail_json.assert_called_once()
409
410 def test_parse_existing_config_paths(self):
411 """Test parsing paths from existing configuration."""
412 from ansible_collections.community.general.plugins.modules import logrotate
413
414 self._setup_module_params(paths=None)
415 config_path = os.path.join(self.config_dir, "test")
416 existing_content = """/var/log/app1/*.log
417 {
418 daily
419 rotate 7
420 compress
421 }"""
422
423 def exists_side_effect(path):
424 if path == self.config_dir:
425 return True
426 elif path == config_path:
427 return True
428 return False
429
430 with patch("os.path.exists", side_effect=exists_side_effect):
431 mock_file_read = mock_open(read_data=existing_content)
432 with patch("builtins.open", mock_file_read):
433 with patch("os.remove"):
434 with patch("os.chmod"):
435 logrotate_bin = self.mock_module.get_bin_path.return_value
436 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
437 result = config.apply()
438 self.assertTrue(result["changed"])
439 self.assertIn("/var/log/app1/*.log", result["config_content"])
440
441 def test_no_delay_compress_parameter(self):
442 """Test no_delay_compress parameter."""
443 from ansible_collections.community.general.plugins.modules import logrotate
444
445 self._setup_module_params(no_delay_compress=True)
446 config_path = os.path.join(self.config_dir, "test")
447
448 def exists_side_effect(path):
449 if path == self.config_dir:
450 return True
451 elif path == config_path:
452 return False
453 return False
454
455 with patch("os.path.exists", side_effect=exists_side_effect):
456 with patch("builtins.open", mock_open()):
457 with patch("os.chmod"):
458 logrotate_bin = self.mock_module.get_bin_path.return_value
459 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
460 result = config.apply()
461 content = result["config_content"]
462 self.assertIn("nodelaycompress", content)
463 self.assertTrue(result["changed"])
464
465 def test_shred_and_shred_cycles_parameters(self):
466 """Test shred and shred_cycles parameters."""
467 from ansible_collections.community.general.plugins.modules import logrotate
468
469 self._setup_module_params(shred=True, shred_cycles=3)
470 config_path = os.path.join(self.config_dir, "test")
471
472 def exists_side_effect(path):
473 if path == self.config_dir:
474 return True
475 elif path == config_path:
476 return False
477 return False
478
479 with patch("os.path.exists", side_effect=exists_side_effect):
480 with patch("builtins.open", mock_open()):
481 with patch("os.chmod"):
482 logrotate_bin = self.mock_module.get_bin_path.return_value
483 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
484 result = config.apply()
485 content = result["config_content"]
486 self.assertIn("shred", content)
487 self.assertIn("shredcycles 3", content)
488 self.assertTrue(result["changed"])
489
490 def test_copy_parameter(self):
491 """Test copy parameter."""
492 from ansible_collections.community.general.plugins.modules import logrotate
493
494 self._setup_module_params(copy=True, copy_truncate=False)
495 config_path = os.path.join(self.config_dir, "test")
496
497 def exists_side_effect(path):
498 if path == self.config_dir:
499 return True
500 elif path == config_path:
501 return False
502 return False
503
504 with patch("os.path.exists", side_effect=exists_side_effect):
505 with patch("builtins.open", mock_open()):
506 with patch("os.chmod"):
507 logrotate_bin = self.mock_module.get_bin_path.return_value
508 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
509 result = config.apply()
510 content = result["config_content"]
511 self.assertIn("copy", content)
512 self.assertNotIn("copytruncate", content)
513 self.assertTrue(result["changed"])
514
515 def test_rename_copy_parameter(self):
516 """Test rename_copy parameter."""
517 from ansible_collections.community.general.plugins.modules import logrotate
518
519 self._setup_module_params(rename_copy=True)
520 config_path = os.path.join(self.config_dir, "test")
521
522 def exists_side_effect(path):
523 if path == self.config_dir:
524 return True
525 elif path == config_path:
526 return False
527 return False
528
529 with patch("os.path.exists", side_effect=exists_side_effect):
530 with patch("builtins.open", mock_open()):
531 with patch("os.chmod"):
532 logrotate_bin = self.mock_module.get_bin_path.return_value
533 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
534 result = config.apply()
535 content = result["config_content"]
536 self.assertIn("renamecopy", content)
537 self.assertTrue(result["changed"])
538
539 def test_min_size_parameter(self):
540 """Test min_size parameter."""
541 from ansible_collections.community.general.plugins.modules import logrotate
542
543 self._setup_module_params(min_size="100k")
544 config_path = os.path.join(self.config_dir, "test")
545
546 def exists_side_effect(path):
547 if path == self.config_dir:
548 return True
549 elif path == config_path:
550 return False
551 return False
552
553 with patch("os.path.exists", side_effect=exists_side_effect):
554 with patch("builtins.open", mock_open()):
555 with patch("os.chmod"):
556 logrotate_bin = self.mock_module.get_bin_path.return_value
557 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
558 result = config.apply()
559 content = result["config_content"]
560 self.assertIn("minsize 100k", content)
561 self.assertTrue(result["changed"])
562
563 def test_date_yesterday_parameter(self):
564 """Test date_yesterday parameter."""
565 from ansible_collections.community.general.plugins.modules import logrotate
566
567 self._setup_module_params(date_ext=True, date_yesterday=True)
568 config_path = os.path.join(self.config_dir, "test")
569
570 def exists_side_effect(path):
571 if path == self.config_dir:
572 return True
573 elif path == config_path:
574 return False
575 return False
576
577 with patch("os.path.exists", side_effect=exists_side_effect):
578 with patch("builtins.open", mock_open()):
579 with patch("os.chmod"):
580 logrotate_bin = self.mock_module.get_bin_path.return_value
581 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
582 result = config.apply()
583 content = result["config_content"]
584 self.assertIn("dateext", content)
585 self.assertIn("dateyesterday", content)
586 self.assertTrue(result["changed"])
587
588 def test_create_old_dir_parameter(self):
589 """Test create_old_dir parameter."""
590 from ansible_collections.community.general.plugins.modules import logrotate
591
592 self._setup_module_params(old_dir="/var/log/archives", create_old_dir=True)
593 config_path = os.path.join(self.config_dir, "test")
594
595 def exists_side_effect(path):
596 if path == self.config_dir:
597 return True
598 elif path == config_path:
599 return False
600 return False
601
602 with patch("os.path.exists", side_effect=exists_side_effect):
603 with patch("builtins.open", mock_open()):
604 with patch("os.chmod"):
605 logrotate_bin = self.mock_module.get_bin_path.return_value
606 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
607 result = config.apply()
608 content = result["config_content"]
609 self.assertIn("olddir /var/log/archives", content)
610 self.assertIn("createolddir", content)
611 self.assertTrue(result["changed"])
612
613 def test_start_parameter(self):
614 """Test start parameter."""
615 from ansible_collections.community.general.plugins.modules import logrotate
616
617 self._setup_module_params(start=1)
618 config_path = os.path.join(self.config_dir, "test")
619
620 def exists_side_effect(path):
621 if path == self.config_dir:
622 return True
623 elif path == config_path:
624 return False
625 return False
626
627 with patch("os.path.exists", side_effect=exists_side_effect):
628 with patch("builtins.open", mock_open()):
629 with patch("os.chmod"):
630 logrotate_bin = self.mock_module.get_bin_path.return_value
631 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
632 result = config.apply()
633 content = result["config_content"]
634 self.assertIn("start 1", content)
635 self.assertTrue(result["changed"])
636
637 def test_syslog_parameter(self):
638 """Test syslog parameter."""
639 from ansible_collections.community.general.plugins.modules import logrotate
640
641 self._setup_module_params(syslog=True)
642 config_path = os.path.join(self.config_dir, "test")
643
644 def exists_side_effect(path):
645 if path == self.config_dir:
646 return True
647 elif path == config_path:
648 return False
649 return False
650
651 with patch("os.path.exists", side_effect=exists_side_effect):
652 with patch("builtins.open", mock_open()):
653 with patch("os.chmod"):
654 logrotate_bin = self.mock_module.get_bin_path.return_value
655 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
656 result = config.apply()
657 content = result["config_content"]
658 self.assertIn("syslog", content)
659 self.assertTrue(result["changed"])
660
661 def test_validation_shred_cycles_positive(self):
662 """Test validation when shred_cycles is not positive."""
663 from ansible_collections.community.general.plugins.modules import logrotate
664
665 self._setup_module_params(shred_cycles=0)
666 config_path = os.path.join(self.config_dir, "test")
667
668 def exists_side_effect(path):
669 if path == self.config_dir:
670 return True
671 elif path == config_path:
672 return False
673 return False
674
675 with patch("os.path.exists", side_effect=exists_side_effect):
676 logrotate_bin = self.mock_module.get_bin_path.return_value
677 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
678 with self.assertRaises(Exception) as context:
679 config.apply()
680 self.assertIn("fail_json called", str(context.exception))
681
682 def test_validation_start_non_negative(self):
683 """Test validation when start is negative."""
684 from ansible_collections.community.general.plugins.modules import logrotate
685
686 self._setup_module_params(start=-1)
687 config_path = os.path.join(self.config_dir, "test")
688
689 def exists_side_effect(path):
690 if path == self.config_dir:
691 return True
692 elif path == config_path:
693 return False
694 return False
695
696 with patch("os.path.exists", side_effect=exists_side_effect):
697 logrotate_bin = self.mock_module.get_bin_path.return_value
698 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
699 with self.assertRaises(Exception) as context:
700 config.apply()
701 self.assertIn("fail_json called", str(context.exception))
702
703 def test_all_new_parameters_together(self):
704 """Test all new parameters together in one configuration."""
705 from ansible_collections.community.general.plugins.modules import logrotate
706
707 self._setup_module_params(
708 no_delay_compress=True,
709 shred=True,
710 shred_cycles=3,
711 copy=True,
712 min_size="100k",
713 date_ext=True,
714 date_yesterday=True,
715 old_dir="/var/log/archives",
716 create_old_dir=True,
717 start=1,
718 syslog=True,
719 rename_copy=False,
720 copy_truncate=False,
721 delay_compress=False,
722 )
723
724 config_path = os.path.join(self.config_dir, "test")
725
726 def exists_side_effect(path):
727 if path == self.config_dir:
728 return True
729 elif path == config_path:
730 return False
731 return False
732
733 with patch("os.path.exists", side_effect=exists_side_effect):
734 with patch("builtins.open", mock_open()):
735 with patch("os.chmod"):
736 logrotate_bin = self.mock_module.get_bin_path.return_value
737 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
738 result = config.apply()
739 content = result["config_content"]
740 self.assertTrue(result["changed"])
741
742 self.assertIn("nodelaycompress", content)
743 self.assertIn("shred", content)
744 self.assertIn("shredcycles 3", content)
745 self.assertIn("copy", content)
746 self.assertIn("minsize 100k", content)
747 self.assertIn("dateext", content)
748 self.assertIn("dateyesterday", content)
749 self.assertIn("olddir /var/log/archives", content)
750 self.assertIn("createolddir", content)
751 self.assertIn("start 1", content)
752 self.assertIn("syslog", content)
753
754 lines = [line.strip() for line in content.split("\n")]
755 self.assertNotIn("copytruncate", lines)
756 self.assertNotIn("renamecopy", lines)
757 self.assertNotIn("delaycompress", lines)
758
759 def test_size_format_validation(self):
760 """Test validation of size format parameters."""
761 from ansible_collections.community.general.plugins.modules import logrotate
762
763 valid_sizes = ["100k", "100M", "1G", "10", "500K", "2M", "3G"]
764
765 for size in valid_sizes:
766 with self.subTest(valid_size=size):
767 self._setup_module_params(size=size)
768 config_path = os.path.join(self.config_dir, "test")
769
770 def exists_side_effect(path, current_config_path=config_path):
771 if path == self.config_dir:
772 return True
773 elif path == current_config_path:
774 return False
775 return False
776
777 with patch("os.path.exists", side_effect=exists_side_effect):
778 with patch("builtins.open", mock_open()):
779 with patch("os.chmod"):
780 logrotate_bin = self.mock_module.get_bin_path.return_value
781 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
782
783 result = config.apply()
784 self.assertIn(f"size {size}", result["config_content"])
785
786 invalid_sizes = ["100kb", "M100", "1.5G", "abc", "100 MB"]
787
788 for size in invalid_sizes:
789 with self.subTest(invalid_size=size):
790 self._setup_module_params(size=size)
791 config_path = os.path.join(self.config_dir, "test")
792
793 def exists_side_effect(path, current_config_path=config_path):
794 if path == self.config_dir:
795 return True
796 elif path == current_config_path:
797 return False
798 return False
799
800 with patch("os.path.exists", side_effect=exists_side_effect):
801 logrotate_bin = self.mock_module.get_bin_path.return_value
802 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
803
804 with self.assertRaises(Exception) as context:
805 config.apply()
806
807 self.assertIn("fail_json called", str(context.exception))
808
809 def test_max_size_format_validation(self):
810 """Test validation of max_size format parameters."""
811 from ansible_collections.community.general.plugins.modules import logrotate
812
813 valid_sizes = ["100k", "100M", "1G", "10", "500K", "2M", "3G"]
814
815 for size in valid_sizes:
816 with self.subTest(valid_size=size):
817 self._setup_module_params(max_size=size)
818 config_path = os.path.join(self.config_dir, "test")
819
820 def exists_side_effect(path, current_config_path=config_path):
821 if path == self.config_dir:
822 return True
823 elif path == current_config_path:
824 return False
825 return False
826
827 with patch("os.path.exists", side_effect=exists_side_effect):
828 with patch("builtins.open", mock_open()):
829 with patch("os.chmod"):
830 logrotate_bin = self.mock_module.get_bin_path.return_value
831 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
832
833 result = config.apply()
834 self.assertIn(f"maxsize {size}", result["config_content"])
835
836 invalid_sizes = ["100kb", "M100", "1.5G", "abc", "100 MB"]
837
838 for size in invalid_sizes:
839 with self.subTest(invalid_size=size):
840 self._setup_module_params(max_size=size)
841 config_path = os.path.join(self.config_dir, "test")
842
843 def exists_side_effect(path, current_config_path=config_path):
844 if path == self.config_dir:
845 return True
846 elif path == current_config_path:
847 return False
848 return False
849
850 with patch("os.path.exists", side_effect=exists_side_effect):
851 logrotate_bin = self.mock_module.get_bin_path.return_value
852 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
853
854 with self.assertRaises(Exception) as context:
855 config.apply()
856
857 self.assertIn("fail_json called", str(context.exception))
858
859 def test_backup_disabled_skips_backup(self):
860 """Test that backup is not created when backup parameter is False."""
861 from ansible_collections.community.general.plugins.modules import logrotate
862
863 self._setup_module_params(rotate_count=14, backup=False)
864 config_path = os.path.join(self.config_dir, "test")
865 existing_content = """/var/log/test/*.log {
866 daily
867 rotate 7
868 compress
869 }"""
870
871 def exists_side_effect(path):
872 if path == self.config_dir:
873 return True
874 elif path == config_path:
875 return True
876 return False
877
878 with patch("os.path.exists", side_effect=exists_side_effect):
879 with patch("builtins.open", mock_open(read_data=existing_content)):
880 with patch("os.remove"):
881 with patch("os.chmod"):
882 logrotate_bin = self.mock_module.get_bin_path.return_value
883 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
884 result = config.apply()
885 self.assertTrue(result["changed"])
886 self.mock_module.backup_local.assert_not_called()
887 self.assertNotIn("backup_file", result)
888
889 def test_backup_enabled_by_default(self):
890 """Test that backup is created by default."""
891 from ansible_collections.community.general.plugins.modules import logrotate
892
893 self._setup_module_params(rotate_count=14)
894 config_path = os.path.join(self.config_dir, "test")
895 expected_backup_path = config_path + ".20260101_120000"
896 self.mock_module.backup_local = Mock(return_value=expected_backup_path)
897 existing_content = """/var/log/test/*.log {
898 daily
899 rotate 7
900 compress
901 }"""
902
903 def exists_side_effect(path):
904 if path == self.config_dir:
905 return True
906 elif path == config_path:
907 return True
908 return False
909
910 with patch("os.path.exists", side_effect=exists_side_effect):
911 with patch("builtins.open", mock_open(read_data=existing_content)):
912 with patch("os.remove"):
913 with patch("os.chmod"):
914 logrotate_bin = self.mock_module.get_bin_path.return_value
915 config = logrotate.LogrotateConfig(self.mock_module, logrotate_bin)
916 result = config.apply()
917 self.assertTrue(result["changed"])
918 self.mock_module.backup_local.assert_called_once_with(config_path)
919 self.assertEqual(result["backup_file"], expected_backup_path)
920
921 def test_logrotate_bin_used_in_apply(self):
922 """Test that logrotate binary path is used in apply method."""
923 from ansible_collections.community.general.plugins.modules import logrotate
924
925 self._setup_module_params()
926
927 test_logrotate_path = "/usr/local/sbin/logrotate"
928 self.mock_module.get_bin_path.return_value = test_logrotate_path
929
930 config_path = os.path.join(self.config_dir, "test")
931
932 def exists_side_effect(path):
933 if path == self.config_dir:
934 return True
935 elif path == config_path:
936 return False
937 return False
938
939 with patch("os.path.exists", side_effect=exists_side_effect):
940 with patch("builtins.open", mock_open()):
941 with patch("os.chmod"):
942 config = logrotate.LogrotateConfig(self.mock_module, test_logrotate_path)
943 config.apply()
944
945 self.mock_module.run_command.assert_called_once()
946 call_args = self.mock_module.run_command.call_args[0][0]
947 self.assertEqual(call_args[0], test_logrotate_path)
948
949
950 if __name__ == "__main__":
951 unittest.main()