8000 feat: admin API endpoints to find/remove unmatched stub mappings by MasonM · Pull Request #2991 · wiremock/wiremock · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat: admin API endpoints to find/remove unmatched stub mappings
This integrates the functionality of
https://github.com/MasonM/wiremock-unused-stubs-extension into WireMock
proper, as requested in #615 (comment).

Specifically, it adds two endpoints:
* `GET /__admin/mappings/unmatched` - Retrieve stub mappings that
  haven't matched any requests in the journal.
* `DELETE /__admin/mappings/unmatched` - Remove all such stub mappings.

  Note that the extension supports an additional `?remove_files=1` query
  parameter that I didn't include here because that introduces some
  additional complications:
  https://github.com/MasonM/wiremock-unused-stubs-extension/blob/424dfad1a21e25d588ac9230a46be820a579d7cf/src/main/java/com/github/masonm/wiremock/UnusedStubsAdminExtension.java#L71
  I added that feature because it was requested in
  MasonM/wiremock-unused-stubs-extension#1,
  though I haven't personally used it much, so I'm not sure if it's
  worth porting.

Signed-off-by: Mason Malone <651224+MasonM@users.noreply.github.com>
  • Loading branch information
MasonM committed Mar 15, 2025
commit 74c40ede5d29edba9081884f1f5054f93c1a43de
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2024 Thomas Akehurst
* Copyright (C) 2011-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -531,6 +531,11 @@ public void shutdownServer() {
shutdown();
}

@Override
public ListStubMappingsResult findUnmatchedStubs() {
return wireMockApp.findUnmatchedStubs();
}

@Override
public ListStubMappingsResult findAllStubsByMetadata(StringValuePattern pattern) {
return wireMockApp.findAllStubsByMetadata(pattern);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2016-2024 Thomas Akehurst
* Copyright (C) 2016-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -64,6 +64,8 @@ private void initDefaultRoutes(Router router) {

router.add(POST, "/mappings/save", new SaveMappingsTask());
router.add(POST, "/mappings/reset", new ResetToDefaultMappingsTask());
router.add(GET, "/mappings/unmatched", new GetUnmatchedStubMappingsTask());
router.add(DELETE, "/mappings/unmatched", new RemoveUnmatchedStubMappingsTask());
router.add(GET, "/mappings/{id}", new GetStubMappingTask());
router.add(PUT, "/mappings/{id}", new EditStubMappingTask());
router.add(POST, "/mappings/remove", new RemoveMatchingStubMappingTask());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2016-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tomakehurst.wiremock.admin.tasks;

import com.github.tomakehurst.wiremock.admin.AdminTask;
import com.github.tomakehurst.wiremock.admin.model.ListStubMappingsResult;
import com.github.tomakehurst.wiremock.common.url.PathParams;
import com.github.tomakehurst.wiremock.core.Admin;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;

public class GetUnmatchedStubMappingsTask implements AdminTask {

@Override
public ResponseDefinition execute(Admin admin, ServeEvent serveEvent, PathParams pathParams) {
ListStubMappingsResult result = admin.findUnmatchedStubs();
return ResponseDefinition.okForJson(result);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2016-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tomakehurst.wiremock.admin.tasks;

import com.github.tomakehurst.wiremock.admin.AdminTask;
import com.github.tomakehurst.wiremock.common.url.PathParams;
import com.github.tomakehurst.wiremock.core.Admin;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;

public class RemoveUnmatchedStubMappingsTask implements AdminTask {

@Override
public ResponseDefinition execute(Admin admin, ServeEvent serveEvent, PathParams pathParams) {
admin.findUnmatchedStubs().getMappings().forEach(admin::removeStubMapping);
return ResponseDefinition.okEmptyJson();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2024 Thomas Akehurst
* Copyright (C) 2011-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -406,6 +406,13 @@ public void shutdownServer() {
postJsonAssertOkAndReturnBody(urlFor(ShutdownServerTask.class), null);
}

@Override
public ListStubMappingsResult findUnmatchedStubs() {
return executeRequest(
adminRoutes.requestSpecForTask(GetUnmatchedStubMappingsTask.class),
ListStubMappingsResult.class);
}

@Override
public ListStubMappingsResult findAllStubsByMetadata(StringValuePattern pattern) {
return executeRequest(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2023 Thomas Akehurst
* Copyright (C) 2011-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -106,6 +106,8 @@ public interface Admin {

void shutdownServer();

ListStubMappingsResult findUnmatchedStubs();

ListStubMappingsResult findAllStubsByMetadata(StringValuePattern pattern);

void removeStubsByMetadata(StringValuePattern pattern);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2012-2024 Thomas Akehurst
* Copyright (C) 2012-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -578,6 +578,27 @@ public RecordingStatusResult getRecordingStatus() {
return new RecordingStatusResult(recorder.getStatus().name());
}

private Set<UUID> findMatchedStubIds() {
return requestJournal.getAllServeEvents().stream()
.filter(event -> event.getStubMapping() != null)
.map(event -> event.getStubMapping().getId())
.collect(Collectors.toSet());
}

@Override
public ListStubMappingsResult findUnmatchedStubs() {
// Collect IDs of stub mappings that have matched at least one request in a HashSet for O(1)
// lookups so this method is O(n + m), where n is the number of stubs and m is the number of
// requests in the journal.
// It'd be slightly more efficient to use IdentityHashMap, but that's error-prone.
Set<UUID> servedStubIds = findMatchedStubIds();
List<StubMapping> foundMappings =
stubMappings.getAll().stream()
.filter(stub -> !servedStubIds.contains(stub.getId()))
.collect(Collectors.toList());
return new ListStubMappingsResult(LimitAndOffsetPaginator.none(foundMappings));
}

@Override
public ListStubMappingsResult findAllStubsByMetadata(StringValuePattern pattern) {
return new ListStubMappingsResult(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2021-2024 Thomas Akehurst
* Copyright (C) 2021-2025 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -231,6 +231,11 @@ public void shutdownServer() {
admin.shutdownServer();
}

@Override
public ListStubMappingsResult findUnmatchedStubs() {
return admin.findUnmatchedStubs();
}

@Override
public ListStubMappingsResult findAllStubsByMetadata(StringValuePattern pattern) {
return admin.findAllStubsByMetadata(pattern);
Expand Down
90 changes: 88 additions & 2 deletions src/main/resources/swagger/wiremock-admin-api.json
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,85 @@
}
}
},
"/__admin/mappings/unmatched": {
"get": {
"operationId": "findUnmatchedStubMappings",
"summary": "Find unmatched stub mappings",
"description": "Find stub mappings that haven't matched any requests in the journal",
"tags": [
"Stub Mappings"
],
"responses": {
"200": {
"description": "Unmatched stub mappings",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/stub-mappings"
},
"example": {
"meta": {
"total": 2
},
"mappings": [
{
"id": "76ada7b0-49ae-4229-91c4-396a36f18e09",
"uuid": "76ada7b0-49ae-4229-91c4-396a36f18e09",
"request": {
"method": "GET",
"url": "/search?q=things",
"headers": {
"Accept": {
"equalTo": "application/json"
}
}
},
"response": {
"status": 200,
"jsonBody": [
"thing1",
"thing2"
],
"headers": {
"Content-Type": "application/json"
}
}
},
{
"request": {
"method": "POST",
"urlPath": "/some/things",
"bodyPatterns": [
{
"equalToXml": "<stuff />"
}
]
},
"response": {
"status": 201
}
}
]
}
}
}
}
9E81 }
},
"delete": {
"operationId": "removeUnmatchedStubMappings",
"summary": "Remove unmatched stub mappings",
"description": "Remove stub mappings that haven't matched any requests in the journal",
"tags": [
"Stub Mappings"
],
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/__admin/requests": {
"get": {
"operationId": "getAllRequestsInJournal",
Expand Down Expand Up @@ -1832,7 +1911,7 @@
]
},
"after-pattern": {
"title": "Before datetime",
"title": "After datetime",
Copy link
Contributor Author
@MasonM MasonM Mar 15, 2025

Choose a reason for hiding this comment

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

This change (and the rest of the changes in this file) are unrelated and the result of running cd ui && npm run swagger to regenerate this file, so I assume somebody forgot to do that. Probably should automate that as part of the build process.

"type": "object",
"properties": {
"after": {
Expand Down Expand Up @@ -1949,7 +2028,11 @@
},
"namespaceAwareness": {
"type": "string",
"enum": ["LEGACY", "STRICT", "NONE"]
"enum": [
"LEGACY",
"STRICT",
"NONE"
]
}
},
"required": [
Expand Down Expand Up @@ -2235,6 +2318,9 @@
"name": {
"type": "string"
},
"fileName": {
"type": "string"
},
"matchingType": {
"type": "string",
"description": "Determines whether all or any of the parts must match the criteria for an overall match.",
Expand Down
26 changes: 26 additions & 0 deletions src/main/resources/swagger/wiremock-admin-api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,32 @@ paths:
'200':
description: 'The stub mappings were successfully removed'

/__admin/mappings/unmatched:
get:
operationId: findUnmatchedStubMappings
summary: Find unmatched stub mappings
description: Find stub mappings that haven't matched any requests in the journal
tags:
- Stub Mappings
responses:
'200':
description: Unmatched stub mappings
content:
application/json:
schema:
$ref: 'schemas/stub-mappings.yaml'
example:
$ref: 'examples/stub-mappings.yaml'
delete:
operationId: removeUnmatchedStubMappings
summary: Remove unmatched stub mappings
description: Remove stub mappings that haven't matched any requests in the journal
tags:
- Stub Mappings
responses:
'200':
description: OK

/__admin/requests:
get:
operationId: getAllRequestsInJournal
Expand Down
Loading
0