Skip to content

Add testing for ServerLogging.java. Configure ServerLogging.java for tests. - #34

Merged
bamsemats merged 3 commits into
mainfrom
feature/serverlogging-test
Feb 11, 2026
Merged

Add testing for ServerLogging.java. Configure ServerLogging.java for tests.#34
bamsemats merged 3 commits into
mainfrom
feature/serverlogging-test

Conversation

@bamsemats

@bamsemats bamsemats commented Feb 11, 2026

Copy link
Copy Markdown

Closes #30

Summary
This PR improves the testability and robustness of the ServerLogging utility and adds comprehensive unit tests to verify its behavior.

Tests added
The following aspects are now covered by ServerLoggingTest:

Verifies that getLogger() returns the same logger instance (singleton behavior)

Ensures a ConsoleHandler is configured on the logger

Confirms that duplicate handlers are not added on repeated access

Asserts that the default log level is INFO

Verifies that parent handlers are disabled

Ensures the log level can be configured via the log.level system property in an isolated and deterministic way

Changes to ServerLogging
Extracted logger configuration into a separate configure(Logger logger) method

Prevents duplicate handler registration

Decouples configuration logic from static initialization, making the class easier to test and safer to reuse

Result
The logging setup is now deterministic, testable, and more resilient to future changes.

Summary by CodeRabbit

  • Tests

    • Added comprehensive tests for logger behavior: singleton consistency, handler management (including avoiding duplicates), default log level, parent-handler usage, and system-property-driven level configuration.
  • Refactor

    • Reorganized logger initialization into a dedicated configuration routine, added validation of configured log level with a fallback and warning on invalid values, and cleaned up class structure for clearer internal organization.

@coderabbitai

coderabbitai Bot commented Feb 11, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Extracts logger setup from a static initializer into a package-private configure(Logger) method in ServerLogging, adds validation for log.level input and ensures a ConsoleHandler when none exist, and introduces JUnit 5 tests validating logger reuse, handler management, levels, and parent-handler behavior.

Changes

Cohort / File(s) Summary
Logger Configuration Refactor
src/main/java/org/juv25d/logging/ServerLogging.java
Moved static-block logger initialization into a package-private configure(Logger) method; sets useParentHandlers=false, ensures a ConsoleHandler with SimpleFormatter if no handlers exist, reads log.level from system property or LOG_LEVEL env var (uppercased) and parses to Level, and catches invalid level values to default to INFO. Minor formatting and constructor compaction.
Logger Tests
src/test/java/org/juv25d/logging/ServerLoggingTest.java
Adds JUnit 5 tests that reset handlers between runs and assert: singleton logger instance, console handler presence, no duplicate handlers on repeated config calls, default level INFO, parent handlers disabled, and respect for log.level system property (with restoration).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nudged the logger, tidy and spry,
Pulled setup to a method, gave levels a try.
Handlers lined up, no echoes to chase,
Tests thump their feet in a neat little race.

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: adding tests for ServerLogging and refactoring it for testability.
Linked Issues check ✅ Passed The PR implements comprehensive unit tests for ServerLogging covering singleton behavior, handler configuration, log levels, and parent handlers, directly addressing issue #30.
Out of Scope Changes check ✅ Passed All changes are directly related to testing ServerLogging and refactoring it for testability. No unrelated modifications detected.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/serverlogging-test

No actionable comments were generated in the recent review. 🎉


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@src/main/java/org/juv25d/logging/ServerLogging.java`:
- Around line 16-32: The Level.parse call in configure can throw
IllegalArgumentException for invalid level strings; wrap the parse and
logger.setLevel calls in a try-catch that catches IllegalArgumentException (and
optionally NullPointerException), fallback to Level.INFO when parsing fails, and
emit a warning via the provided Logger (e.g., logger.warning or logger.log)
describing the invalid levelName; ensure this change is applied inside the
static configure(Logger logger) method around Level.parse(...) and
logger.setLevel(...).

In `@src/test/java/org/juv25d/logging/ServerLoggingTest.java`:
- Around line 76-82: The test is brittle because it relies on global state;
instead create an isolated logger and explicitly control properties: use
Logger.getLogger("test.default.level") to obtain a fresh logger, clear the
system property "log.level" and unset any LOG_LEVEL env var (or mock/ensure it's
absent), then call ServerLogging.configure() (or the configure method used in
other tests) to initialize defaults, and finally assert that logger.getLevel()
equals Level.INFO; reference ServerLogging.getLogger(),
ServerLogging.configure(), and the "log.level"/LOG_LEVEL settings when making
these changes.
- Around line 62-74: The test currently calls ServerLogging.getLogger() twice
which returns the same static logger and doesn't exercise the duplicate-handler
guard; update the test to obtain the logger once (Logger logger =
ServerLogging.getLogger()), then call ServerLogging.configure(logger) twice and
assert that logger.getHandlers().length remains 1 (or equals the initial handler
count) to verify the if (logger.getHandlers().length == 0) protection in
ServerLogging.configure.
🧹 Nitpick comments (1)
src/test/java/org/juv25d/logging/ServerLoggingTest.java (1)

18-27: setUp removes handlers but doesn't re-apply configure().

After stripping all handlers, tests that don't explicitly call configure() (e.g., logger_shouldHaveInfoLevelByDefault, logger_shouldNotUseParentHandlers) rely on state left over from the static initializer rather than a known-good baseline. This is fragile — consider calling ServerLogging.configure(logger) at the end of setUp() so every test starts from a fully configured state, or intentionally leave it unconfigured and call configure() explicitly in each test that needs it.

Comment thread src/main/java/org/juv25d/logging/ServerLogging.java
Comment thread src/test/java/org/juv25d/logging/ServerLoggingTest.java
Comment thread src/test/java/org/juv25d/logging/ServerLoggingTest.java
fmazmz
fmazmz previously approved these changes Feb 11, 2026
HerrKanin
HerrKanin previously approved these changes Feb 11, 2026
…es in configure method (logger.parse => setLevel).
@bamsemats
bamsemats dismissed stale reviews from HerrKanin and fmazmz via da4ada4 February 11, 2026 11:58
@bamsemats
bamsemats merged commit b0d7583 into main Feb 11, 2026
2 checks passed
@fmazmz
fmazmz deleted the feature/serverlogging-test branch February 11, 2026 12:58
annikaholmqvist94 pushed a commit that referenced this pull request Feb 11, 2026
…tests. (#34)

* Add testing for ServerLogging.java. Configure ServerLogging.java to improve its testability.

* Update logger_shouldNotAddDuplicateHandlers test to properly test non-inclusion of duplicates.

* Update ServerLogging.java to guard against invalid level string entries in configure method (logger.parse => setLevel).
fmazmz added a commit that referenced this pull request Feb 12, 2026
* Implement static file handler with security and tests

Core Implementation:
- Add StaticFileHandler for serving files from /resources/static/
- Add MimeTypeResolver for Content-Type detection
- Add security validation to prevent path traversal attacks

Testing:
- Add MimeTypeResolverTest (15 test cases)
- Add StaticFileHandlerTest (20+ test cases)
- All tests passing

Example Files:
- Add index.html demo page with gradient styling
- Add styles.css for professional styling
- Add app.js for JavaScript functionality demo

Note: Integration with Server/ConnectionHandler will be added
after PR #28 merges to avoid conflicts.

Foundation work for #18

* Introduce ADR structure and first ADR - Add ADR README explaining the ADR process for the team
                                     - Add TEMPLATE for writing future ADRs
                                      - Add ADR-001 documenting static file serving architecture

                                      Closes #16

* Rename SocketServer to Server Move HTTP request handling logic to a dedicated ConnectionHandler. (#28)

* Rename SocketServer to Server
Move HTTP request handling logic to a dedicated ConnectionHandler.

* Convert createSocket to an instance method named start().

* Replace console prints with Logger in ConnectionHandler

* Fixed typo in ConnectionHandler

* refactor Server and ConnectionHandler:
- Inject Logger inside of constructor
- Inject handlerFactory into the Server that handles creation of a new ConnectionHandler on each request
- Remove HttpParser from Server as it is not handling the parsing of a request

* accept ConnectionHandlerFactory and not a specific implementation

* normalize handlerFactory name

---------

Co-authored-by: WHITEROSE <firasmoussa60@gmail.com>

* Add testing for ServerLogging.java. Configure ServerLogging.java for tests. (#34)

* Add testing for ServerLogging.java. Configure ServerLogging.java to improve its testability.

* Update logger_shouldNotAddDuplicateHandlers test to properly test non-inclusion of duplicates.

* Update ServerLogging.java to guard against invalid level string entries in configure method (logger.parse => setLevel).

* feature/FilterPlugin (#17)

* http parser

* Bunny fixes. (only using input stream to recieve requests)

* Bunny review improvements

* Improved http parser ReadLine helper method to eliminate dependency on mark() and reset(). Implemented handleClient() using socket as a try-with-resources to avoid memory leakage in case of exception thrown by httpparser-methods.

* NumberFormatException fix on line 53 -> 60

* Added foundation for Filters and Plugins. Added FilterChain to use created filters, and a Pipeline class to handle the workflow (Client → Filters → Plugin → Response → Client). Modified SocketServer handleClient() to use FilterChain. Added example code in App.java for Pipeline usage. TODO: Initialize HttpResponse class

* Fixing build fail

* add init and destroy to filter interface

* add methods to pipeline class

* Add servlet-style filter pipeline with lifecycle support

* add documentation about temporary server impl

* test: verify filters execute in order and plugin is called last

* test: add coverage for filter blocking, lifecycle init, and empty pipeline

* add loggingfiltertest

* fix: construct HttpResponse with required arguments

* fix: construct HttpResponse with required arguments

* Update FilterChainImpl tests to use full HttpResponse constructor to ensure compatibility with future implementations

* remove duplicated class

---------

Co-authored-by: Kristina M <kristina0x7@gmail.com>
Co-authored-by: WHITEROSE <firasmoussa60@gmail.com>

* Add charset=utf-8 to text-based Content-Type headers

* Integrate StaticFileHandler with Pipeline architecture

* Refactor  to use immutable fields and clean up unused setters; update  with usage notes for future integration.

* Enhance StaticFilesPlugin to properly handle headers with map iteration; simplify and clarify class documentation.

* Update tests to verify Content-Type headers include charset=utf-8

* connect StaticFilesPlugin

---------

Co-authored-by: johanbriger <johanbriger@gmail.com>
Co-authored-by: WHITEROSE <firasmoussa60@gmail.com>
Co-authored-by: Mats Rönnqvist <203552386+bamsemats@users.noreply.github.com>
Co-authored-by: Linus Westling <141355850+LinusWestling@users.noreply.github.com>
Co-authored-by: Kristina M <kristina0x7@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Impl tests for ServerLogging.java

5 participants