Skip to content

Commit 40c505f

Browse files
authored
Fix linting errors in CI workflow #58 (#59)
* Fix linting errors in CI workflow #58 This commit fixes a number of linting errors that were causing the CI workflow to fail. The errors were primarily related to unused imports, f-strings without placeholders, and unused variables. * Refactor and clean up test code #58 Removed unused imports and variables in test_maillogsentinel_setup.py and test_sql_exporter.py. Updated test_run_sql_export_basic_flow to use context manager for patching datetime and simplified the mocking of the logger. These changes improve test clarity and maintainability. * Remove duplicate unittest.mock import #58 Consolidated the import of patch and MagicMock from unittest.mock to avoid redundancy in the test file. * Remove unused MagicMock import #58 Cleaned up the import statements by removing MagicMock, which was not used in the test file.
1 parent 2d7e78d commit 40c505f

File tree

9 files changed

+103
-122
lines changed

9 files changed

+103
-122
lines changed

bin/maillogsentinel_setup.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -751,7 +751,7 @@ def interactive_cli_setup(target_config_path, setup_log_fh):
751751
setup_log_fh,
752752
)
753753
_setup_print_and_log(
754-
f"You may need to manually perform these steps or re-run with sudo IF you want systemd integration.",
754+
"You may need to manually perform these steps or re-run with sudo IF you want systemd integration.",
755755
setup_log_fh,
756756
)
757757
_setup_print_and_log(
@@ -965,10 +965,14 @@ def interactive_cli_setup(target_config_path, setup_log_fh):
965965
f"FATAL ERROR during interactive setup: {e_main_interactive.__class__.__name__}: {e_main_interactive}",
966966
setup_log_fh,
967967
)
968-
import traceback
968+
_setup_print_and_log(
969+
f"FATAL ERROR during interactive setup: {e_main_interactive.__class__.__name__}: {e_main_interactive}",
970+
setup_log_fh,
971+
)
972+
# import traceback # No longer needed
969973

970-
_setup_print_and_log(traceback.format_exc(), setup_log_fh)
971-
return False # Indicate failure
974+
# _setup_print_and_log(traceback.format_exc(), setup_log_fh) # No longer needed
975+
return False
972976
return True
973977

974978

@@ -983,13 +987,12 @@ def non_interactive_setup(source_config_path: Path, setup_log_fh):
983987
Updates global backed_up_items and created_final_paths lists.
984988
"""
985989
import sys # Ensure sys is imported for stdout
986-
import traceback
987990

988991
print("non_interactive_setup CALLED", flush=True)
989992
# traceback.print_stack(file=sys.stdout, limit=10) # Removed for debugging
990993
print("---", flush=True)
991994

992-
_setup_print_and_log(f"--- MailLogSentinel Non-Interactive Setup ---", setup_log_fh)
995+
_setup_print_and_log("--- MailLogSentinel Non-Interactive Setup ---", setup_log_fh)
993996

994997
if os.geteuid() != 0:
995998
_setup_print_and_log(
@@ -1156,7 +1159,7 @@ def non_interactive_setup(source_config_path: Path, setup_log_fh):
11561159
)
11571160
usermod_cmd = shutil.which("usermod")
11581161
if not usermod_cmd:
1159-
_setup_print_and_log(f"ERROR: 'usermod' not found.", setup_log_fh)
1162+
_setup_print_and_log("ERROR: 'usermod' not found.", setup_log_fh)
11601163
sys.exit(1) # Restored error
11611164
try:
11621165
process_result = subprocess.run(

lib/maillogsentinel/parser.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
Callable,
1919
)
2020
import logging
21-
import sys
2221

2322
# Add bin directory to sys.path to allow importing ipinfo
2423
# sys.path.append(str(Path(__file__).resolve().parent.parent.parent / "bin")) # Removed for cleaner path management

lib/maillogsentinel/sql_exporter.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@
88

99
import csv
1010
import datetime
11-
import hashlib
1211
import json
1312
import logging
14-
import os
1513
from pathlib import Path
1614
from typing import Optional, List, Dict, Any
1715
import importlib.resources # Added for loading bundled data
1816

17+
import tempfile
18+
import shutil
1919
from lib.maillogsentinel.config import AppConfig # Import AppConfig
2020

2121
# Constants
@@ -608,7 +608,7 @@ def run_sql_export(config: AppConfig, output_log_level: str = "INFO") -> bool:
608608
if sql_file_path.exists():
609609
sql_file_path.unlink(missing_ok=True) # cleanup
610610
return False
611-
except CSVSchemaError as e: # Already logged by validate_csv_header
611+
except CSVSchemaError: # Already logged by validate_csv_header
612612
# Cleanup already handled in validate_csv_header's calling block
613613
return False
614614
except Exception as e:
@@ -663,10 +663,6 @@ def run_sql_export(config: AppConfig, output_log_level: str = "INFO") -> bool:
663663
return True
664664

665665

666-
import tempfile
667-
import shutil
668-
669-
670666
# Test configuration class
671667
class DummyTestConfig:
672668
def __init__(self, mapping_file_path_str="", base_dir_name=None):

lib/maillogsentinel/sql_importer.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,9 @@
1010
import logging
1111
import sqlite3
1212
import time
13-
import datetime # For handling imported file records
1413
import os # For os.getpid() in FileLock
1514
from pathlib import Path
16-
from typing import List, Tuple, Dict, Any, Optional
15+
from typing import Optional
1716
import fcntl # For file locking on POSIX systems
1817

1918
import importlib.resources # Added for loading bundled data
@@ -714,6 +713,3 @@ def __init__(self, base_path: Path):
714713
print("\nsql_importer.py direct test finished.")
715714
# Note: For a real test, you'd use pytest and mock AppConfig, Path.is_file(), open(), etc.
716715
# This direct run is just for very basic flow checking.
717-
718-
# Required for FileLock to get PID (if not already imported by another module like logging)
719-
import os

tests/bin/test_maillogsentinel_setup.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import tempfile
77
import os
88
import io # For mock_log_fh spec
9-
import locale # For mocking in specific test
109
import re
1110

1211

@@ -413,7 +412,6 @@ def test_path_management_creation(self):
413412

414413
try:
415414
original_backed_up_items = mls_setup.backed_up_items
416-
original_created_final_paths = mls_setup.created_final_paths
417415
mls_setup.backed_up_items = []
418416
mls_setup.created_final_paths = []
419417

@@ -433,7 +431,6 @@ def test_path_management_creation(self):
433431
finally:
434432
os.remove(config_path_str)
435433
mls_setup.backed_up_items = original_backed_up_items
436-
mls_setup.created_final_paths = original_created_final_paths
437434

438435
def test_path_management_backup_existing(self):
439436
"""Test backup of workdir and statedir when they already exist."""
@@ -475,7 +472,6 @@ def test_path_management_backup_existing(self):
475472

476473
try:
477474
original_backed_up_items = mls_setup.backed_up_items
478-
original_created_final_paths = mls_setup.created_final_paths
479475
mls_setup.backed_up_items = []
480476
mls_setup.created_final_paths = []
481477

@@ -502,7 +498,6 @@ def test_path_management_backup_existing(self):
502498
finally:
503499
os.remove(config_path_str)
504500
mls_setup.backed_up_items = original_backed_up_items
505-
mls_setup.created_final_paths = original_created_final_paths
506501

507502
# User/Group Management Tests
508503
def test_user_verification_non_existent(self):
@@ -946,7 +941,6 @@ def path_exists_side_effect(*args_passed):
946941
config.read_string(VALID_CONFIG_CONTENT)
947942

948943
try:
949-
original_created_final_paths = mls_setup.created_final_paths
950944
mls_setup.created_final_paths = []
951945
with patch(
952946
"configparser.ConfigParser.read", return_value=[config_path_str_val]
@@ -1374,7 +1368,7 @@ def test_systemd_control_commands_success(self):
13741368
"bin.maillogsentinel_setup.subprocess.run"
13751369
) as mock_subprocess_run, patch(
13761370
"bin.maillogsentinel_setup._setup_print_and_log"
1377-
) as mock_setup_print, patch(
1371+
), patch(
13781372
"bin.maillogsentinel_setup.sys.exit"
13791373
) as mock_sys_exit: # noqa: F841
13801374

@@ -1405,7 +1399,7 @@ def test_systemd_control_commands_success(self):
14051399
# Expected calls to systemd-analyze for calendar validation
14061400
# These come from the VALID_CONFIG_CONTENT and the defaults in non_interactive_setup
14071401
# Order matters here as they are called before systemctl daemon-reload.
1408-
expected_calendar_validation_calls = [
1402+
[
14091403
unittest.mock.call(
14101404
[
14111405
"/usr/bin/systemd-analyze",

tests/lib/maillogsentinel/test_log_utils.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
# Import the function to be tested
77
from lib.maillogsentinel.log_utils import (
88
_parse_log_line,
9-
MONTHS,
109
) # MONTHS needed for test_parse_log_line_invalid_month by implication
1110

1211
# --- Mocks and Fixtures ---

tests/lib/maillogsentinel/test_progress.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
# tests/lib/maillogsentinel/test_progress.py
22
import unittest
3-
from unittest.mock import patch, MagicMock
3+
from unittest.mock import patch
44
import io
55
import sys
66
from lib.maillogsentinel.progress import (
77
ProgressTracker, # Import the class
8-
get_terminal_width,
98
GREEN,
109
RED,
1110
ORANGE,

tests/lib/maillogsentinel/test_report.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ def test_send_report_success(
299299
assert len(attachments) == 1
300300
assert attachments[0].get_filename() == mock_app_config.csv_filename
301301
mock_logger.info.assert_any_call(
302-
f"Report sent from testuser@my.server.com to recipient@example.com"
302+
"Report sent from testuser@my.server.com to recipient@example.com"
303303
)
304304

305305

@@ -376,7 +376,7 @@ def test_send_report_sender_override(
376376
sent_msg: EmailMessage = mock_smtp_instance.send_message.call_args[0][0]
377377
assert sent_msg["From"] == "override@sender.com"
378378
mock_logger.info.assert_any_call(
379-
f"Report sent from override@sender.com to recipient@example.com"
379+
"Report sent from override@sender.com to recipient@example.com"
380380
)
381381

382382

0 commit comments

Comments
 (0)