Skip to content
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

Add custom content patterns. #285

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion _data/doc-categories.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ extensibility:
- extending-wiremock
- extensibility/filtering-requests
- extensibility/transforming-responses
- extensibility/custom-matching
- extensibility/custom-request-matching
- extensibility/custom-content-matching
Copy link
Member

Choose a reason for hiding this comment

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

If implemented as is, it breaks the original page access. At least a redirect is needed in the markdown file

- extensibility/listening-for-serve-events
- extensibility/extending-the-admin-api
- extensibility/adding-template-helpers
Expand Down
65 changes: 57 additions & 8 deletions _docs/extending-wiremock.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ At present, the following extension interfaces are available:
* `ResponseTransformerV2`: Modify the response served to the client. See [Transforming responses](../extensibility/transforming-responses/).
* `ServeEventListener`: Listen for events at various points in the request processing lifecycle. See [Listening for Serve Events](../extensibility/listening-for-serve-events/).
* `AdminApiExtension`: Add admin API functions. See [Admin API Extensions](../extensibility/extending-the-admin-api/).
* `RequestMatcherExtension`: Implement custom request matching logic. See [Custom matching](../extensibility/custom-matching/).
* `RequestMatcherExtension`: Implement custom request matching logic. See [Custom Request Matching](../extensibility/custom-request-matching/).
* `ContentPatternExtension`: Implement custom content matching logic. See [Custom Content Matching](../extensibility/custom-content-matching/).
* `GlobalSettingsListener`: Listen for changes to the settings object. See [Listening for Settings Changes](../extensibility/listening-for-settings-changes/).
* `StubLifecycleListener`: Listen for changes to the stub mappings. See [Listening for Stub Changes](../extensibility/listening-for-stub-changes/).
* `TemplateHelperProviderExtension`: Provide custom Handlebars helpers to the template engine. See [Adding Template Helpers](../extensibility/adding-template-helpers/).
Expand All @@ -35,18 +36,35 @@ initialisation or cleanup tasks.

## Registering Extensions

You can directly register the extension programmatically via its class name,
class or an instance:
You can directly register the extension programmatically via its class name, class or an instance.

Server:
```java
new WireMockServer(wireMockConfig()
.extensions("com.mycorp.BodyContentTransformer", "com.mycorp.HeaderMangler"));
.extensions("com.mycorp.ClassNameOne", "com.mycorp.ClassNameTwo")
.extensions(ClassOne.class, ClassTwo.class)
.extensions(new InstanceOne(), new InstanceTwo()));
```

new WireMockServer(wireMockConfig()
.extensions(BodyContentTransformer.class, HeaderMangler.class));
Client:
```java
// Only need to register extensions that change how a mapping is parsed/written (i.e. ContentPatternExtension).
WireMock.create()
.extensions("com.mycorp.ClassNameOne", "com.mycorp.ClassNameTwo")
.extensions(ClassOne.class, ClassTwo.class)
.extensions(new InstanceOne(), new InstanceTwo())
.build();
```

new WireMockServer(wireMockConfig()
.extensions(new BodyContentTransformer(), new HeaderMangler()));
Extension:
```java
@RegisterExtension
static WireMockExtension wm = WireMockExtension.newInstance()
.options(wireMockConfig()
.extensions("com.mycorp.ClassNameOne", "com.mycorp.ClassNameTwo")
.extensions(ClassOne.class, ClassTwo.class)
.extensions(new InstanceOne(), new InstanceTwo()))
.build();
```

See [Running as a Standalone Process](../running-standalone/) for details on running with extensions from the command line.
Expand Down Expand Up @@ -76,11 +94,42 @@ Services currently available to extension factories are:
* `Extensions`: the service for creating and providing extension implementations.
* `TemplateEngine`: the Handlebars template engine.

For factories that register extensions that change how a mapping is parsed/written (i.e. ContentPatternExtension), must implement `ExtensionFactory#createForClient()`
to return those extension.

## Extension registration via service loading

Extensions that are packaged with the relevant [Java service loader framework](https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html) metadata
will be loaded automatically if they are placed on the classpath.

Server:
```java
new WireMockServer(wireMockConfig().extensionScanningEnabled(true));
```

Client:
```java
WireMock.create()
.extensionScanningEnabled(true)
.build();
```

Extension:
```java
@RegisterExtension
static WireMockExtension wm = WireMockExtension.newInstance()
.options(wireMockConfig()
.extensionScanningEnabled(true))
.build();

// or

@WireMockTest(extensionScanningEnabled = true)
public class MyTest {
...
}
```

See [https://github.com/wiremock/wiremock/tree/master/test-extension](https://github.com/wiremock/wiremock/tree/master/test-extension) for an example of such an extension.


Expand Down
150 changes: 150 additions & 0 deletions _docs/extensibility/custom-content-matching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
---
layout: docs
title: Custom Content Matching
meta_title: Adding custom content matchers
description: Adding custom content matchers via extensions
---

If WireMock's standard set of content matching strategies isn't sufficient, you can register one or more content
matcher classes containing your own logic.

Custom content matchers can be attached directly to stubs via the Java API when using the local admin interface (by
calling `stubFor(...)` on `WireMockServer`, `WireMockExtension`, or `WireMockRule`). They can also be added via the
extension mechanism on a remote admin interface (by calling `extensions(...)` on `WireMockBuilder`).

To create a custom content matcher extend `ContentPattern<byte[]>` or `StringValuePattern` (ensuring `Json.write(...)`
appropriately serializes your matcher and a `@JsonCreator` is defined):
```java
public class MagicBytesPattern extends ContentPattern<byte[]> {

public enum Format {
GIF("47 49 46 38 37 61", "47 49 46 38 39 61"),
PNG("89 50 4E 47 0D 0A 1A 0A"),
ZIP("50 4B 03 04", "50 4B 05 06", "50 4B 07 08");

private final Set<byte[]> magicBytes;

Format(String... magicBytes) {
HexFormat hexFormat = HexFormat.ofDelimiter(" ");
this.magicBytes = Stream.of(magicBytes).map(hexFormat::parseHex).collect(toSet());
}
}

private final Format format;

@JsonCreator
public MagicBytesPattern(@JsonProperty("magicBytes") Format format) {
super(format.magicBytes.iterator().next());
this.format = format;
}

@Override
public String getName() {
return "magicBytes";
}

@Override
public String getExpected() {
return format.toString();
}

@Override
public MatchResult match(byte[] value) {
for (byte[] magicByte : format.magicBytes) {
if (value.length >= magicByte.length) {
boolean matches = true;
for (int i = 0; i < magicByte.length; i++) {
if (value[i] != magicByte[i]) {
matches = false;
break;
}
}
if (matches) {
return MatchResult.exactMatch();
}
}
}
return MatchResult.noMatch();
}

public Format getMagicBytes() {
return format;
}
}
```
```java
public class StartsWithMatcher extends StringValuePattern {

@JsonCreator
public StartsWithMatcher(@JsonProperty("startsWith") String startsWith) {
super(startsWith);
}

@Override
public MatchResult match(String value) {
return MatchResult.of(value.startsWith(expectedValue));
}

public String getStartsWith() {
return expectedValue;
}
}
```

Then, implement `ContentPatternExtension` giving the extension a unique name and identifying the class of your matcher:
```java
public class StartsWithPatternExtension implements ContentPatternExtension {

@Override
public Class<? extends ContentPattern<?>> getContentPatternClass() {
return StartsWithPattern.class;
}

@Override
public String getName() {
return "starts-with-pattern";
}
}
```

After the extension is properly registered, you can define a stub with it:

{% codetabs %}

{% codetab Java %}

```java
stubFor(
post("/gif")
.withHeader("X-FileName", new StartsWithMatcher("gif"))
.withRequestBody(new MagicBytesPattern(MagicBytesPattern.Format.GIF))
.willReturn(ok()));
```

{% endcodetab %}

{% codetab JSON %}

```json
{
"request": {
"url": "/gif",
"method": "POST",
"headers": {
"X-FileName": {
"startsWith": "gif"
}
},
"bodyPatterns": [{
"magicBytes": "GIF"
}]
},
"response": {
"status": 200
}
}
```

{% endcodetab %}

{% endcodetabs %}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
layout: docs
title: Custom Matching
title: Custom Request Matching
Copy link
Contributor

Choose a reason for hiding this comment

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

This all looks fine. @oleg-nenashev is correct about the redirect though. Changing the name of the file will change the url structure so all the indexed pages in the search engines will return a 404. If you take a look at the other pages on the site, some of them have a redirect_from element in the front matter. This is what we need here

meta_title: Adding custom request matchers
description: Adding custom request matchers via extensions
---
Expand Down
Loading