Skip to content

Limit mock calls with up_to_n_times - #108

Merged
FalkWoldmann merged 1 commit into
httpmock:masterfrom
wfchandler:wc/add-delete-after-n
Oct 14, 2026
Merged

FalkWoldmann merged 1 commit into
httpmock:masterfrom
wfchandler:wc/add-delete-after-n

Conversation

@wfchandler

@wfchandler wfchandler commented Jul 25, 2024 •

Copy link
Copy Markdown
Contributor

When a component is expected to retry an endpoint automatically, manually calling delete on a Mock between attempts may not be an option.

Add a new Then::up_to_n_times method that stops matching after the specified non-zero number of calls. The mock remains registered so that calls to calls and assert_calls work, and later requests fall through to other mocks. The limit can also be set in static YAML mocks, or on an existing mock with Mock::up_to_n_times.

Remote servers that predate this change would ignore the limit. The client detects this and panics instead of registering an unlimited mock.

Resetting the server will clear the call counters of static mocks, as static mocks survive a reset and would otherwise stay exhausted for the lifetime of the server.

Related to #76
Related to #96

@alexliesenfeld

alexliesenfeld commented Jul 25, 2024 •

Copy link
Copy Markdown
Member

Thank you for your PR @wfchandler! Looks like a useful addition. I will have a closer look at it and get back to you!

wfchandler added a commit to oxidecomputer/oxide.rs that referenced this pull request Sep 16, 2024
From a user perspective uploading a disk is a single operation, but
doing so via the SDK is a very involved process, involving stringing
together multiple API calls with any interruption leaving the disk in a
state that cannot be directly removed.

Add a new `extras` module to the SDK that will contain convenience
wrappers around actions that functions that are overly complicated.
Create a `disk_import` function in `extras` that will perform a disk
upload as a single step, and attempts to cleanup partially imported
disks on failure. We make the `disk upload` CLI command a thin wrapper
around the new SDK function, responsible only for cancellation and
progress. We manually recreate the builder interface, as creating a
procmacro to do this would require creating a new crate. If/when
`extras` continues to grow we should reconsider this.

`disk_import` also give callers access to a `DiskImportHandle` with a
`watch` channel with the current number of bytes uploaded for use in
progress tracking, and provides a `cancel` function that allows users
to gracefully stop the disk upload. A disk that has been successfully
created will not be removed, only those that are partially imported.

The `cancel` function uses `tokio::select` to cancel the `Future` of
the upload task. This should be safe in our in our case no locks are
held across `await` points. No operations need to be safe to restart as
we only call `tokio::select` a single time, they will be dropped
immediately and losing a message is not a problem.

We are forced to remove tests `test_disk_import_bulk_import_start_fail`
and `test_disk_import_bulk_write_import_fail` as we now poll for disks
in `Created` state, which may happen if a user immediately cancels a new
request. This state is not eligible to be finalized, so we need to wait
for the disk to progress to the next state, but `HttpMock` does not
provide a way to programatically delete or update a mock after sending
`n` responses. This means that the disk will always be returned as
non-existing when querying, and cleanup will be skipped. I have opened
httpmock/httpmock#108 to add a
`delete_after_n` method, but this seems unlikely to be merged. We may
want to consider moving to `wiremock` in the long term, which provides
this functionality.

Co-authored-by: Adam Leventhal <[email protected]>
wfchandler added a commit to oxidecomputer/oxide.rs that referenced this pull request Sep 16, 2024
From a user perspective uploading a disk is a single operation, but
doing so via the SDK is a very involved process, involving stringing
together multiple API calls with any interruption leaving the disk in a
state that cannot be directly removed.

Add a new `extras` module to the SDK that will contain convenience
wrappers around actions that functions that are overly complicated.
Create a `disk_import` function in `extras` that will perform a disk
upload as a single step, and attempts to cleanup partially imported
disks on failure. We make the `disk upload` CLI command a thin wrapper
around the new SDK function, responsible only for cancellation and
progress. We manually recreate the builder interface, as creating a
procmacro to do this would require creating a new crate. If/when
`extras` continues to grow we should reconsider this.

`disk_import` also give callers access to a `DiskImportHandle` with a
`watch` channel with the current number of bytes uploaded for use in
progress tracking, and provides a `cancel` function that allows users
to gracefully stop the disk upload. A disk that has been successfully
created will not be removed, only those that are partially imported.

The `cancel` function uses `tokio::select` to cancel the `Future` of
the upload task. This should be safe in our in our case no locks are
held across `await` points. No operations need to be safe to restart as
we only call `tokio::select` a single time, they will be dropped
immediately and losing a message is not a problem.

We are forced to remove tests `test_disk_import_bulk_import_start_fail`
and `test_disk_import_bulk_write_import_fail` as we now poll for disks
in `Created` state, which may happen if a user immediately cancels a new
request. This state is not eligible to be finalized, so we need to wait
for the disk to progress to the next state, but `HttpMock` does not
provide a way to programatically delete or update a mock after sending
`n` responses. This means that the disk will always be returned as
non-existing when querying, and cleanup will be skipped. I have opened
httpmock/httpmock#108 to add a
`delete_after_n` method, but this seems unlikely to be merged. We may
want to consider moving to `wiremock` in the long term, which provides
this functionality.

Co-authored-by: Adam Leventhal <[email protected]>
wfchandler added a commit to oxidecomputer/oxide.rs that referenced this pull request Sep 16, 2024
From a user perspective uploading a disk is a single operation, but
doing so via the SDK is a very involved process, involving stringing
together multiple API calls with any interruption leaving the disk in a
state that cannot be directly removed.

Add a new `extras` module to the SDK that will contain convenience
wrappers around actions that functions that are overly complicated.
Create a `disk_import` function in `extras` that will perform a disk
upload as a single step, and attempts to cleanup partially imported
disks on failure. We make the `disk upload` CLI command a thin wrapper
around the new SDK function, responsible only for cancellation and
progress. We manually recreate the builder interface, as creating a
procmacro to do this would require creating a new crate. If/when
`extras` continues to grow we should reconsider this.

`disk_import` also give callers access to a `DiskImportHandle` with a
`watch` channel with the current number of bytes uploaded for use in
progress tracking, and provides a `cancel` function that allows users
to gracefully stop the disk upload. A disk that has been successfully
created will not be removed, only those that are partially imported.

The `cancel` function uses `tokio::select` to cancel the `Future` of
the upload task. This should be safe in our in our case no locks are
held across `await` points. No operations need to be safe to restart as
we only call `tokio::select` a single time, they will be dropped
immediately and losing a message is not a problem.

We are forced to remove tests `test_disk_import_bulk_import_start_fail`
and `test_disk_import_bulk_write_import_fail` as we now poll for disks
in `Created` state, which may happen if a user immediately cancels a new
request. This state is not eligible to be finalized, so we need to wait
for the disk to progress to the next state, but `HttpMock` does not
provide a way to programatically delete or update a mock after sending
`n` responses. This means that the disk will always be returned as
non-existing when querying, and cleanup will be skipped. I have opened
httpmock/httpmock#108 to add a
`delete_after_n` method, but this seems unlikely to be merged. We may
want to consider moving to `wiremock` in the long term, which provides
this functionality.

Co-authored-by: Adam Leventhal <[email protected]>
wfchandler added a commit to oxidecomputer/oxide.rs that referenced this pull request Sep 23, 2024
From a user perspective uploading a disk is a single operation, but
doing so via the SDK is a very involved process, involving stringing
together multiple API calls with any interruption leaving the disk in a
state that cannot be directly removed.

Add a new `extras` module to the SDK that will contain convenience
wrappers around actions that functions that are overly complicated.
Create a `disk_import` function in `extras` that will perform a disk
upload as a single step, and attempts to cleanup partially imported
disks on failure. We make the `disk upload` CLI command a thin wrapper
around the new SDK function, responsible only for cancellation and
progress. We manually recreate the builder interface, as creating a
procmacro to do this would require creating a new crate. If/when
`extras` continues to grow we should reconsider this.

`disk_import` also give callers access to a `DiskImportHandle` with a
`watch` channel with the current number of bytes uploaded for use in
progress tracking, and provides a `cancel` function that allows users
to gracefully stop the disk upload. A disk that has been successfully
created will not be removed, only those that are partially imported.

The `cancel` function uses `tokio::select` to cancel the `Future` of
the upload task. This should be safe in our in our case no locks are
held across `await` points. No operations need to be safe to restart as
we only call `tokio::select` a single time, they will be dropped
immediately and losing a message is not a problem.

We are forced to remove tests `test_disk_import_bulk_import_start_fail`
and `test_disk_import_bulk_write_import_fail` as we now poll for disks
in `Created` state, which may happen if a user immediately cancels a new
request. This state is not eligible to be finalized, so we need to wait
for the disk to progress to the next state, but `HttpMock` does not
provide a way to programatically delete or update a mock after sending
`n` responses. This means that the disk will always be returned as
non-existing when querying, and cleanup will be skipped. I have opened
httpmock/httpmock#108 to add a
`delete_after_n` method, but this seems unlikely to be merged. We may
want to consider moving to `wiremock` in the long term, which provides
this functionality.

Co-authored-by: Adam Leventhal <[email protected]>
wfchandler added a commit to oxidecomputer/oxide.rs that referenced this pull request Sep 23, 2024
From a user perspective uploading a disk is a single operation, but
doing so via the SDK is a very involved process, involving stringing
together multiple API calls with any interruption leaving the disk in a
state that cannot be directly removed.

Add a new `extras` module to the SDK that will contain convenience
wrappers around actions that functions that are overly complicated.
Create a `disk_import` function in `extras` that will perform a disk
upload as a single step, and attempts to cleanup partially imported
disks on failure. We make the `disk upload` CLI command a thin wrapper
around the new SDK function, responsible only for cancellation and
progress. We manually recreate the builder interface, as creating a
procmacro to do this would require creating a new crate. If/when
`extras` continues to grow we should reconsider this.

`disk_import` also give callers access to a `DiskImportHandle` with a
`watch` channel with the current number of bytes uploaded for use in
progress tracking, and provides a `cancel` function that allows users
to gracefully stop the disk upload. A disk that has been successfully
created will not be removed, only those that are partially imported.

The `cancel` function uses `tokio::select` to cancel the `Future` of
the upload task. This should be safe in our in our case no locks are
held across `await` points. No operations need to be safe to restart as
we only call `tokio::select` a single time, they will be dropped
immediately and losing a message is not a problem.

We are forced to remove tests `test_disk_import_bulk_import_start_fail`
and `test_disk_import_bulk_write_import_fail` as we now poll for disks
in `Created` state, which may happen if a user immediately cancels a new
request. This state is not eligible to be finalized, so we need to wait
for the disk to progress to the next state, but `HttpMock` does not
provide a way to programatically delete or update a mock after sending
`n` responses. This means that the disk will always be returned as
non-existing when querying, and cleanup will be skipped. I have opened
httpmock/httpmock#108 to add a
`delete_after_n` method, but this seems unlikely to be merged. We may
want to consider moving to `wiremock` in the long term, which provides
this functionality.

Co-authored-by: Adam Leventhal <[email protected]>
wfchandler added a commit to oxidecomputer/oxide.rs that referenced this pull request Sep 23, 2024
From a user perspective uploading a disk is a single operation, but
doing so via the SDK is a very involved process, involving stringing
together multiple API calls with any interruption leaving the disk in a
state that cannot be directly removed.

Add a new `extras` module to the SDK that will contain convenience
wrappers around actions that functions that are overly complicated.
Create a `disk_import` function in `extras` that will perform a disk
upload as a single step, and attempts to cleanup partially imported
disks on failure. We make the `disk upload` CLI command a thin wrapper
around the new SDK function, responsible only for cancellation and
progress. We manually recreate the builder interface, as creating a
procmacro to do this would require creating a new crate. If/when
`extras` continues to grow we should reconsider this.

`disk_import` also give callers access to a `DiskImportHandle` with a
`watch` channel with the current number of bytes uploaded for use in
progress tracking, and provides a `cancel` function that allows users
to gracefully stop the disk upload. A disk that has been successfully
created will not be removed, only those that are partially imported.

The `cancel` function uses `tokio::select` to cancel the `Future` of
the upload task. This should be safe in our in our case no locks are
held across `await` points. No operations need to be safe to restart as
we only call `tokio::select` a single time, they will be dropped
immediately and losing a message is not a problem.

We are forced to remove tests `test_disk_import_bulk_import_start_fail`
and `test_disk_import_bulk_write_import_fail` as we now poll for disks
in `Created` state, which may happen if a user immediately cancels a new
request. This state is not eligible to be finalized, so we need to wait
for the disk to progress to the next state, but `HttpMock` does not
provide a way to programatically delete or update a mock after sending
`n` responses. This means that the disk will always be returned as
non-existing when querying, and cleanup will be skipped. I have opened
httpmock/httpmock#108 to add a
`delete_after_n` method, but this seems unlikely to be merged. We may
want to consider moving to `wiremock` in the long term, which provides
this functionality.

Co-authored-by: Adam Leventhal <[email protected]>
@mothran mothran mentioned this pull request Oct 31, 2024
@fhsgoncalves

Copy link
Copy Markdown

Hey! Any updates on this PR?
It would be really useful for my use case, which is similar to the one describe on #96.

@wfchandler

Copy link
Copy Markdown
Contributor Author

I'm happy to rebase this against master if @alexliesenfeld is interested.

@alexliesenfeld

Copy link
Copy Markdown
Member

@wfchandler I am wondering if having a separate method to set this deletion behavior might be slightly more consistent with the current API. For example:

#[test]
fn delete_mock_test() {
    let server = MockServer::start();

    let mut m1 = server.mock(|when, then| {
        when.method(GET).path("/test");
        then.status(500);
    });

    // ... 
   
    m1.delete(); // current way of deleting
    m1.delete_after_calls(2); // If we want it to be deleted after a number of calls
}

Alternatively, it might also be possible to add options to the mock definitions on demand. For example:

#[test]
fn delete_mock_test() {
    let server = MockServer::start();

    let mut m1 = server.mock_with_options(|when, then, opts| {
        when.method(GET).path("/test");
        then.status(500);
        opts.delete_after_calls(2);
    });

    // ... 
}

I think the first option fits better with the current API, and introducing a third closure parameter feels a bit much ... any thoughts?

@wfchandler

Copy link
Copy Markdown
Contributor Author

introducing a third closure parameter feels a bit much

Thanks @alexliesenfeld, I agree adding an additional parameter is overkill for one option. I'll take a stab at your first suggestion.

@wfchandler
wfchandler force-pushed the wc/add-delete-after-n branch from fa1632d to 0910a89 Compare July 10, 2025 18:02
@wfchandler wfchandler changed the title Add delete_after_n method to When Add delete_after_count method to Mock Jul 10, 2025
@wfchandler

Copy link
Copy Markdown
Contributor Author

@alexliesenfeld I've force pushed the update, I didn't think there was any benefit to keeping the original commit around since it was so outdated.

@FalkWoldmann

Copy link
Copy Markdown
Member

Hi @wfchandler, sorry this sat for so long. Master has moved a lot since then (state.rs is now state/mod.rs, the adapters were rewritten), so this needs more than a rebase. A few things I'd want to get right when redoing it:

  • Once the mock deletes itself, its call counter is gone too, so hits() and assert_calls(n) on it panic afterwards. Keeping it as an inactive mock that matching skips would let tests check it was called n times.
  • The limit is compared against the total count after serving, so a mock with 3 hits before delete_after_calls(2) still serves a 4th request.
  • Setting the limit in a separate request after creating the mock isn't atomic, so a client that's already retrying can get requests in before it lands. I'd rather store it on the mock definition, which also drops the extra route and makes it work for YAML mocks. Mock::delete_after_calls could stay as a thin wrapper. @alexliesenfeld what do you think?
  • A count of 0 is only rejected on the client side, and local and remote servers disagree when the mock is already gone (no-op vs. panic).

Would you still be up for redoing it on top of master? Otherwise one of us can pick it up, since it's the fix for #96.

@wfchandler

Copy link
Copy Markdown
Contributor Author

Thanks for the review @FalkWoldmann, happy to get the PR updated in the next couple of days.

When a component is expected to retry an endpoint automatically,
manually calling `delete` on a `Mock` between attempts may not be an
option.

Add a new `Then::up_to_n_times` method that stops matching after the
specified non-zero number of calls. The mock remains registered so that
calls to `calls` and `assert_calls` work, and later requests fall
through to other mocks. The limit can also be set in static YAML mocks,
or on an existing mock with `Mock::up_to_n_times`.

Remote servers that predate this change would ignore the limit. The
client detects this and panics instead of registering an unlimited
mock.

Resetting the server will clear the call counters of static mocks, as
static mocks survive a reset and would otherwise stay exhausted for the
lifetime of the server.
@wfchandler
wfchandler force-pushed the wc/add-delete-after-n branch from 0910a89 to 9435624 Compare October 13, 2026 20:34
@wfchandler wfchandler changed the title Add delete_after_count method to Mock Limit mock calls with up_to_n_times Oct 13, 2026
@wfchandler

Copy link
Copy Markdown
Contributor Author

@FalkWoldmann I've rewritten the PR. The method is renamed to up_to_n_times, and will disable, but not delete the mock, allowing users to assert against it. Thanks again for taking a look.

@FalkWoldmann FalkWoldmann left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks a lot for sticking with this for so long and for the rewrite :)

@FalkWoldmann
FalkWoldmann merged commit e17a009 into httpmock:master Oct 14, 2026
13 checks passed
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.

4 participants