Skip to content

Better configurability for MockEngine #4846

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

jonapoul
Copy link

@jonapoul jonapoul commented May 10, 2025

Subsystem
Client testing

Motivation
I recently started using Ktor as a replacement for OkHttp for various reasons, and I came across MockEngine as an apparent replacement for MockWebServer. One thing that I did quite a lot with MockWebServer was to:

  1. initialise the client in a test's @Before block
  2. pass it into the rest of the system under test
  3. specify HTTP behaviour on a per-test basis
  4. make the call
  5. verify the behaviour
  6. maybe repeat steps 3-6 several times, depending on test complexity

But with MockEngine as it is I need to pass in an initial MockRequestHandler, otherwise an exception is thrown.

Solution
This change adds the option to intialise MockEngine without a MockRequestHandler using the MockEngine.empty() function - allowing us to enqueue one or more handlers later in the test lifecycle. If no handler exists at the time of a call being made, it still throws error() as it did before.

Obviously this isn't going to cover all user's needs so I left the default constructor behaving as it always has, but personally I think this will help people to structure their tests a little better.

CI seems to be failing, but I'm fairly sure(???) that's not the fault of this branch.

Copy link

coderabbitai bot commented May 10, 2025

Walkthrough

The changes make the MockEngine class open for inheritance and add a nested subclass Queue that supports manual queuing of request handlers. Constructors and methods for enqueuing handlers and operator overloading are introduced. The companion object’s factory method is simplified. Tests are updated to cover the new queuing behavior and fix a method name typo.

Changes

File(s) Change Summary
ktor-client/ktor-client-mock/api/ktor-client-mock.api
ktor-client/ktor-client-mock/api/ktor-client-mock.klib.api
Changed MockEngine from final to open class to allow inheritance. Added nested subclass MockEngine.Queue with constructors and methods enqueue and plusAssign to manage request handlers queue. Made properties config and supportedCapabilities and methods close and execute open for override. Companion object factory methods remain but simplified in signature.
ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt Modified MockEngine constructor to internal with a boolean flag controlling empty handler enforcement; added a public secondary constructor. Added nested subclass Queue with default config and reuseHandlers = false, disabling empty handler check. Added enqueue and operator plusAssign methods in Queue for adding request handlers. Simplified companion object invoke operator to accept a MockRequestHandler directly. No changes to core request execution or history tracking.
ktor-client/ktor-client-mock/jvm/test/io/ktor/client/tests/mock/MockEngineTests.kt Renamed test method testWithContentNegotationPlugin to testWithContentNegotiationPlugin to fix typo. Added new test testEngineWithManualQueueing that verifies initial empty handler list in MockEngine.Queue, manual queuing of handlers, correct response returns for queued handlers, and that a request without a queued handler throws an IllegalStateException.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1767ab4 and 57987a4.

📒 Files selected for processing (4)
  • ktor-client/ktor-client-mock/api/ktor-client-mock.api (2 hunks)
  • ktor-client/ktor-client-mock/api/ktor-client-mock.klib.api (1 hunks)
  • ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt (4 hunks)
  • ktor-client/ktor-client-mock/jvm/test/io/ktor/client/tests/mock/MockEngineTests.kt (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • ktor-client/ktor-client-mock/jvm/test/io/ktor/client/tests/mock/MockEngineTests.kt
  • ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt
🔇 Additional comments (5)
ktor-client/ktor-client-mock/api/ktor-client-mock.api (2)

1-1: Good change to enable inheritance.

Making MockEngine non-final allows for extension and customization, which is appropriate for the new queuing functionality being added. This change maintains backward compatibility while enabling new use cases.


18-26: Well-designed subclass for queue functionality.

The new MockEngine$Queue subclass provides a good solution to the problem stated in the PR objectives. By allowing initialization without an initial handler and supporting later enqueuing, this will help users structure their tests better. The API design looks clean with:

  1. Appropriate constructors
  2. An enqueue method that returns a boolean (presumably to indicate success)
  3. A plusAssign operator for more idiomatic Kotlin usage with +=
  4. Proper property overrides

This implementation addresses the author's concern about initializing MockEngine in a test's @Before block without having to specify handlers upfront.

ktor-client/ktor-client-mock/api/ktor-client-mock.klib.api (3)

26-39: Good architectural changes for extensibility.

Making MockEngine open and its key methods/properties overridable is a sound design decision. This maintains backward compatibility while allowing for customization through inheritance. The change is consistent across both API files.

The specific properties and methods marked as open are appropriate:

  • config and supportedCapabilities properties
  • close() and execute() methods

These are precisely the elements that a subclass would need to override or extend.


41-49: Well-designed Queue implementation.

The Queue subclass has a clean API design that provides exactly what was requested in the PR objectives. It allows:

  1. Initializing without an initial handler (via optional parameter in constructor)
  2. Adding handlers later via enqueue()
  3. Using the += operator via plusAssign()

This implementation solves the problem described by the author where they needed to initialize the client in a test's @Before block but specify HTTP behavior per test.


51-54: Companion object remains appropriately unchanged.

Keeping the factory methods in the companion object unchanged is a good decision for backward compatibility. The API signature still shows them here even though they haven't changed, which is expected in an API diff.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jonapoul jonapoul changed the title Mock engine configurability More configurability for MockEngine May 10, 2025
@jonapoul jonapoul changed the title More configurability for MockEngine Better configurability for MockEngine May 10, 2025
@jonapoul jonapoul marked this pull request as ready for review May 10, 2025 10:26
Copy link

@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: 0

🧹 Nitpick comments (3)
ktor-client/ktor-client-mock/api/ktor-client-mock.api (1)

6-6: The enqueue method return value could use more documentation

The boolean return value from enqueue implies success or failure, but it's not clear from this API definition when it would return false.

ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt (2)

98-108: Well-documented implementation of handler management methods

The documentation clearly explains what the methods do. However, the enqueue method could benefit from additional documentation explaining what the boolean return value represents.

Consider adding to the KDoc for enqueue:

/**
 * Appends a new [MockRequestHandler], to be called/removed after any previous handlers have been consumed.
+ * @return true if the handler was successfully added, false otherwise.
 */

125-141: Well-documented factory method with clear usage guidance

The documentation thoroughly explains:

  1. What the method does
  2. The implications of using an empty engine
  3. When this approach is most useful
  4. A warning about handler disposal

Consider adding a parameter to customize the reuseHandlers value, as some users might want to reuse handlers even with an empty initial configuration.

-public fun empty(): MockEngine {
+/**
+ * @param reuseHandlers Whether handlers should be reused after they are consumed.
+ *                       Defaults to false to ensure each handler is used only once.
+ */
+public fun empty(reuseHandlers: Boolean = false): MockEngine {
     val config = MockEngineConfig().apply {
         // Every time a handler is called, it gets disposed. So make sure enough handlers are registered for
         // requests you intend to make!
-        reuseHandlers = false
+        this.reuseHandlers = reuseHandlers
     }
     return MockEngine(config, throwIfEmptyConfig = false)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f487b2a and 1767ab4.

📒 Files selected for processing (4)
  • ktor-client/ktor-client-mock/api/ktor-client-mock.api (1 hunks)
  • ktor-client/ktor-client-mock/api/ktor-client-mock.klib.api (2 hunks)
  • ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt (4 hunks)
  • ktor-client/ktor-client-mock/jvm/test/io/ktor/client/tests/mock/MockEngineTests.kt (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
ktor-client/ktor-client-mock/jvm/test/io/ktor/client/tests/mock/MockEngineTests.kt (2)
ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockUtils.kt (2)
  • respondOk (67-69)
  • respondError (56-60)
ktor-server/ktor-server-test-suites/jvm/src/io/ktor/server/testing/suites/Utils.kt (1)
  • assertFailsWith (94-104)
🔇 Additional comments (11)
ktor-client/ktor-client-mock/api/ktor-client-mock.api (3)

4-4: New constructor with throwIfEmptyConfig parameter is a good addition

This new constructor allows for creating a MockEngine without requiring an initial handler, which supports the goal of allowing more flexible test setup.


13-13: Good syntactic sugar with plusAssign operator

The plusAssign operator provides a cleaner syntax for adding handlers, which will make test code more readable.


18-18: The empty() factory method solves the stated problem well

This factory method directly addresses the PR objective of allowing initialization without an initial handler, making it easier to structure tests with handler setup in each test case.

ktor-client/ktor-client-mock/jvm/test/io/ktor/client/tests/mock/MockEngineTests.kt (2)

77-77: Fixed typo in test name

Changed "testWithContentNegotationPlugin" to "testWithContentNegotiationPlugin" to correct the spelling of "Negotiation".


95-114: Well-structured test for the new empty engine functionality

This test thoroughly validates the new features:

  1. Creating an empty MockEngine
  2. Verifying the initial empty state
  3. Testing both enqueue (via +=) and handler response
  4. Verifying proper exception when no handlers remain

The test covers all the critical aspects of the new functionality and demonstrates the intended use case.

ktor-client/ktor-client-mock/api/ktor-client-mock.klib.api (3)

11-11: Constructor addition is consistent across API files

This matches the constructor added in the main API file, ensuring consistent functionality across platforms.


23-24: New methods for dynamically adding handlers are properly exposed in the API

Both enqueue and plusAssign methods are correctly defined in the API, making them accessible to clients.


29-29: The empty() factory method is properly exposed in the API

This ensures the new factory method is available across all supported platforms.

ktor-client/ktor-client-mock/common/src/io/ktor/client/engine/mock/MockEngine.kt (3)

20-24: Good implementation of constructor with backward compatibility

The implementation:

  1. Adds the new parameter to the primary constructor
  2. Provides a secondary constructor that maintains backward compatibility
  3. Uses descriptive parameter naming

This is a clean way to extend functionality while ensuring existing code continues to work.


41-46: Core implementation of the empty engine functionality

This conditional check is the key change that allows initializing the engine without handlers. By making the check conditional based on the throwIfEmptyConfig parameter, you enable the creation of an initially empty engine.


119-124: Simplified invoke operator in companion object

This simplification makes the code cleaner while maintaining the same functionality.

Copy link
Contributor

❌ Junie can be launched only by a repository collaborator

Copy link
Contributor

@bjhham bjhham left a comment

Choose a reason for hiding this comment

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

Nice idea! I think the introduction of the queue functions on the MockEngine does create a little dissonance in the abstraction since the engine is externally immutable. I think it might make sense here to introduce something like class MockEngine.Queue: MockEngine() to expose the queue methods.

Then the test would look something like:

val engine = MockEngine.Queue()
assertTrue(engine.isEmpty())

val client = HttpClient(engine)

engine += { respondOk("hello") }
val response1 = client.get { url("http://127.0.0.1/normal-request") }
assertEquals("hello", response1.body<String>())

engine += { respondError(HttpStatusCode.BadRequest) }
val response2 = client.get { url("http://127.0.0.1/failed-request") }
assertEquals(HttpStatusCode.BadRequest, response2.status)

assertFailsWith<IllegalStateException> {
    client.get { url("http://127.0.0.1/no-more-handlers-registered") }
}

Copy link
Contributor

❌ Junie can be launched only by a repository collaborator

@jonapoul
Copy link
Author

Thats fair (I'll take a look a bit later today). Out of interest - is there any reason why MockEngine should have an immutable interface?

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.

2 participants