Skip to content

test: add unit tests for services/utils/logging_config.py (#40)#90

Open
Aharshi3614 wants to merge 4 commits into
TENET-DEV-AI:mainfrom
Aharshi3614:tests/add-logging-config-tests
Open

test: add unit tests for services/utils/logging_config.py (#40)#90
Aharshi3614 wants to merge 4 commits into
TENET-DEV-AI:mainfrom
Aharshi3614:tests/add-logging-config-tests

Conversation

@Aharshi3614
Copy link
Copy Markdown

@Aharshi3614 Aharshi3614 commented May 28, 2026

🤖 TENET Agent will automatically review this PR for security issues and code quality.
Maintainers: to have TENET solve an issue autonomously, comment /tenet fix on the issue.


What this does

Adds 18 unit tests for the logging configuration utility module.

Related Issue

Closes #40

Type of Change

  • New feature (non-breaking change which adds functionality)

How Has This Been Tested?

  • Unit tests

pytest tests/unit/test_logging_config.py -v
18 passed in 0.11s

Test Coverage

  • TestSetupLogging: 14 tests covering logger instance, name, log levels, handlers, format, propagation
  • TestSensitiveDataLogging: 2 tests for sensitive data handling
  • TestLogLevelCaseInsensitive: 2 tests for env var case insensitivity

Note: Please merge this PR after June 1st.

Summary by CodeRabbit

  • Tests
    • Added comprehensive tests for logging behavior: validates default and environment-overridden log levels (including case-insensitivity), handler setup and duplication prevention, logs directory creation, required formatter fields, safe logger identifiers (no sensitive substrings), and that logging operations run without errors.

Review Change Stack

@vercel
Copy link
Copy Markdown

vercel Bot commented May 28, 2026

@Aharshi3614 is attempting to deploy a commit to the s3dfx-cyber's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 28, 2026

Warning

Review limit reached

@Aharshi3614, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 9 minutes and 21 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 49523ca5-e299-4747-ab55-6afd17c0ca22

📥 Commits

Reviewing files that changed from the base of the PR and between 73e4fef and c07d203.

📒 Files selected for processing (1)
  • tests/unit/test_logging_config.py
📝 Walkthrough

Walkthrough

Adds a new unit test module tests/unit/test_logging_config.py that validates setup_logging's logger creation, handler configuration, formatter fields, environment-driven log levels, idempotency, sensitive-name exclusion, and case-insensitive LOG_LEVEL parsing.

Changes

Logging Configuration Unit Tests

Layer / File(s) Summary
Module imports and test foundation
tests/unit/test_logging_config.py
Module docstring, imports, and sys.path adjustment to import setup_logging.
Logger configuration and behavior validation
tests/unit/test_logging_config.py
TestSetupLogging validates logger instance/name, default INFO level, LOG_LEVEL parsing (DEBUG/WARNING/ERROR), invalid-value fallback to INFO, presence of StreamHandler and RotatingFileHandler, propagate=False, idempotent handler counts on repeated calls, logs directory creation, and formatter includes asctime, name, levelname, and message.
Sensitive-name and emit validation
tests/unit/test_logging_config.py
TestSensitiveDataLogging asserts logger name excludes sensitive substrings (password, secret, token) and that basic log calls do not raise exceptions.
Case-insensitive LOG_LEVEL parsing
tests/unit/test_logging_config.py
TestLogLevelCaseInsensitive verifies LOG_LEVEL is parsed case-insensitively for lowercase and mixed-case values.
Pytest entry point
tests/unit/test_logging_config.py
Module-level __main__ block to run pytest on the file with verbose output.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • TENET-DEV-AI/TENET-AI#35: Related work around services/utils/logging_config.setup_logging and earlier tests for the centralized logging module.

Suggested reviewers

  • S3DFX-CYBER

Poem

🐰 A rabbit tests with quiet delight,
As loggers hum through day and night.
Handlers in order, levels in line,
No secrets printed — all is fine.
Hoppy tests keep the logs just right.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'test: add unit tests for services/utils/logging_config.py (#40)' directly and clearly describes the main change—adding unit tests for a specific module.
Description check ✅ Passed The description is mostly complete. It covers what the PR does, related issue, type of change, testing results, and test coverage breakdown. All critical sections are filled.
Linked Issues check ✅ Passed The PR addresses all primary coding requirements from issue #40: test file created, tests for logger instance/name/levels/handlers/format/propagation/sensitive data/case-insensitivity implemented, and 18 tests passed with claimed coverage.
Out of Scope Changes check ✅ Passed The changes are limited to adding unit tests for the logging configuration module as specified in issue #40, with no unrelated modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
tests/unit/test_logging_config.py (1)

11-11: ⚡ Quick win

Consider using a more robust import mechanism.

The sys.path.insert approach is fragile and depends on the test file's location relative to the services directory. If tests are run from different working directories or the project structure changes, imports may fail.

Consider one of these approaches:

  • Make services a proper Python package with __init__.py files and install it in development mode (pip install -e .)
  • Use pytest's pythonpath configuration in pyproject.toml or pytest.ini
📦 Example pytest configuration approach

In pyproject.toml or pytest.ini:

[tool.pytest.ini_options]
pythonpath = ["services"]

Then simplify the import:

-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "services" / "utils"))
-
-from logging_config import setup_logging
+from utils.logging_config import setup_logging
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/test_logging_config.py` at line 11, The test currently manipulates
import paths via sys.path.insert with Path(__file__).parent... which is fragile;
instead make the services tree a proper package (add __init__.py files and
install in dev mode with pip install -e .) or configure pytest to add services
to PYTHONPATH (add pythonpath = ["services"] under [tool.pytest.ini_options] in
pyproject.toml or pytest.ini) and then remove the sys.path.insert line and
switch to normal imports (e.g., import from services.utils or the specific
module names used in the test).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/unit/test_logging_config.py`:
- Around line 110-115: The test test_logger_name_not_sensitive is ineffective
because it passes a safe name; either implement name sanitization in
setup_logging or change the test to match the documented behavior — update
setup_logging to call a new helper sanitize_logger_name(name) that detects
sensitive substrings like "password", "secret", "token" and masks or strips them
before creating the logger, then change test_logger_name_not_sensitive to pass a
name containing those substrings (e.g., "service_password_token") and assert the
returned logger.name does not contain the raw sensitive words and contains the
masked form; alternatively, if you choose not to change implementation, replace
this unit test with one asserting callers must not pass sensitive data and/or
move coverage to the log filtering/formatting tests.
- Around line 94-104: The test_log_format_contains_required_fields currently may
pass silently if no handler has a formatter; update the test that calls
setup_logging("test_format") to first assert that at least one handler in
logger.handlers has a formatter (e.g. assert any(h.formatter for h in
logger.handlers)), then iterate over all handlers and assert each handler has a
formatter and that handler.formatter._fmt contains "%(asctime)s", "%(name)s",
"%(levelname)s", and "%(message)s"; reference the existing test function name
test_log_format_contains_required_fields and the setup_logging call to locate
where to add these checks.
- Around line 29-33: The test test_default_log_level_is_info mutates os.environ
directly; change it to use unittest.mock.patch.dict to ensure environment
isolation for LOG_LEVEL while calling setup_logging("test_default_level") so the
original environment is restored after the test. Replace the
os.environ.pop("LOG_LEVEL", None) line with a patch.dict context (or decorator)
that sets ENV without LOG_LEVEL (or sets LOG_LEVEL to None/absent) so
logger.level can be asserted as logging.INFO without polluting other tests.
- Around line 117-125: The test function
test_logger_functional_for_normal_messages has a critical indentation mistake:
the body (calls to setup_logging, logger.info/warning/error and the try/except)
must be indented under the def to form a valid function block; fix by indenting
lines inside test_logger_functional_for_normal_messages so the logger =
setup_logging(...), try/except, and pytest.fail calls are all nested within the
function body.

---

Nitpick comments:
In `@tests/unit/test_logging_config.py`:
- Line 11: The test currently manipulates import paths via sys.path.insert with
Path(__file__).parent... which is fragile; instead make the services tree a
proper package (add __init__.py files and install in dev mode with pip install
-e .) or configure pytest to add services to PYTHONPATH (add pythonpath =
["services"] under [tool.pytest.ini_options] in pyproject.toml or pytest.ini)
and then remove the sys.path.insert line and switch to normal imports (e.g.,
import from services.utils or the specific module names used in the test).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: cff25995-dea6-4d21-bb0e-bbc0341eb7ee

📥 Commits

Reviewing files that changed from the base of the PR and between 384ac1a and 7323f49.

📒 Files selected for processing (1)
  • tests/unit/test_logging_config.py

Comment thread tests/unit/test_logging_config.py Outdated
Comment thread tests/unit/test_logging_config.py
Comment thread tests/unit/test_logging_config.py Outdated
Comment thread tests/unit/test_logging_config.py Outdated
@S3DFX-CYBER
Copy link
Copy Markdown
Collaborator

@Aharshi3614 needs fixes , syntax issues

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
tests/unit/test_logging_config.py (1)

121-129: 💤 Low value

Redundant try/except around logging calls.

If any logger.* call raised, pytest would already fail the test, so the try/except+pytest.fail wrapper adds no value and triggers Ruff BLE001 (blind Exception catch). Letting the exception propagate is simpler and preserves the original traceback.

♻️ Proposed simplification
     def test_logger_functional_for_normal_messages(self):
         """Test that logger works normally without raising exceptions."""
         logger = setup_logging("test_sensitive")
-        try:
-            logger.info("User logged in successfully")
-            logger.warning("Test warning")
-            logger.error("Test error")
-        except Exception as e:
-            pytest.fail(f"Logger raised an exception: {e}")
+        logger.info("User logged in successfully")
+        logger.warning("Test warning")
+        logger.error("Test error")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/test_logging_config.py` around lines 121 - 129, The test
test_logger_functional_for_normal_messages wraps logger calls in a redundant
try/except that catches Exception (triggering Ruff BLE001); remove the
try/except and pytest.fail wrapper and simply call
setup_logging("test_sensitive") and then logger.info/warning/error directly so
any exception will naturally fail the test and preserve the original traceback;
locate the test function by name and the setup_logging call to make this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tests/unit/test_logging_config.py`:
- Around line 121-129: The test test_logger_functional_for_normal_messages wraps
logger calls in a redundant try/except that catches Exception (triggering Ruff
BLE001); remove the try/except and pytest.fail wrapper and simply call
setup_logging("test_sensitive") and then logger.info/warning/error directly so
any exception will naturally fail the test and preserve the original traceback;
locate the test function by name and the setup_logging call to make this change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 42f1b86b-0a85-431f-9712-d1e03d40f7d8

📥 Commits

Reviewing files that changed from the base of the PR and between 7323f49 and 73e4fef.

📒 Files selected for processing (1)
  • tests/unit/test_logging_config.py

@Aharshi3614
Copy link
Copy Markdown
Author

I've fixed all the issues flagged by CodeRabbit — resolved the indentation error, environment isolation, and improved the sensitive data test. All 18 tests pass locally. Could you please approve the workflows so CI can run?

@S3DFX-CYBER S3DFX-CYBER added the SSoC26 Social Summer of Code 2026 S5 label May 30, 2026
Copy link
Copy Markdown
Collaborator

@S3DFX-CYBER S3DFX-CYBER left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm i will merge it on 1st June dw

@vercel
Copy link
Copy Markdown

vercel Bot commented May 30, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
tenet-ai.org Ready Ready Preview, Comment May 30, 2026 3:31pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

SSoC26 Social Summer of Code 2026 S5

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add unit tests for services/utils/logging_config.py

2 participants