diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c70aa783..891a5d68 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ jobs: - name: Setup Ruby uses: ruby/setup-ruby@55283cc23133118229fd3f97f9336ee23a179fcf # v1.146.0 with: - ruby-version: '2.7.6' # Not needed with a .ruby-version file + ruby-version: '2.7.2' # Not needed with a .ruby-version file bundler: '2.4.10' bundler-cache: false # runs 'bundle install' and caches installed gems automatically cache-version: 3 # Increment this number if you need to re-download cached gems @@ -28,7 +28,7 @@ jobs: id: pages uses: actions/configure-pages@v3 - name: Update RubyGems and Co - run: gem update --system + run: gem update - name: Install Ruby Bundles run: bundle install - name: Build with Jekyll diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index adfb4b90..b641376f 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -2,8 +2,8 @@ name: Deploy Jekyll site to Pages on: # Runs on pushes targeting the default branch - push: - branches: ["main"] + # push: + # branches: ["main"] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: @@ -40,7 +40,7 @@ jobs: id: pages uses: actions/configure-pages@v3 - name: Update RubyGems and Co - run: gem update --system + run: gem update - name: Install Ruby Bundles run: bundle install - name: Build with Jekyll diff --git a/.github/workflows/updatecli.yaml b/.github/workflows/updatecli.yaml deleted file mode 100644 index f3aafbcf..00000000 --- a/.github/workflows/updatecli.yaml +++ /dev/null @@ -1,32 +0,0 @@ ---- -name: "Updatecli" - -on: - workflow_dispatch: - schedule: - # * is a special character in YAML so you have to quote this string - # trigger every hour the following pipeline - - cron: '0 * * * *' - -permissions: - contents: write - pull-requests: write - -jobs: - updatecli: - runs-on: ubuntu-latest - # Ensure we only run the following pipeline from main branch - # with a GITHUB_TOKEN that has "contents: write" permission - if: github.ref == 'refs/heads/main' - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Install Updatecli Binary - uses: updatecli/updatecli-action@v2 - - - name: Run Updatecli in enforce mode - run: "updatecli apply --config .github/updatecli/updatecli.d" - env: - GITHUB_ACTOR: ${{ github.actor }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/Gemfile.lock b/Gemfile.lock index b968d007..dae010b3 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -108,11 +108,11 @@ GEM tzinfo (2.0.6) concurrent-ruby (~> 1.0) unicode-display_width (2.4.2) - wdm (0.1.1) webrick (1.8.1) PLATFORMS arm64-darwin-21 + arm64-darwin-23 x64-mingw32 x86_64-linux @@ -126,7 +126,6 @@ DEPENDENCIES jemoji json (~> 1.8.6) nokogiri (>= 1.7.2) - wdm (~> 0.1.0) webrick (~> 1.7) BUNDLED WITH diff --git a/_config.yml b/_config.yml index 0dc9f33e..30b074cc 100644 --- a/_config.yml +++ b/_config.yml @@ -234,11 +234,11 @@ compress_html: ignore: envs: development -wiremock_version: 3.3.1 +wiremock_version: 3.6.0 wiremock_baseline: 3.x pageEditPrefix: https://github.com/wiremock/wiremock.org/edit/main/ -grpc_extension_version: 0.4.0 +grpc_extension_version: 0.6.0 community_slack: join_url: https://slack.wiremock.org/ diff --git a/_data/doc-categories.yml b/_data/doc-categories.yml index 2e6a15f4..abbae640 100644 --- a/_data/doc-categories.yml +++ b/_data/doc-categories.yml @@ -26,7 +26,9 @@ java: - java-usage - configuration - running-without-http-server + - jetty-12 - android + - pact stubbing-and-verifying: title: Stubbing & Verifying @@ -40,8 +42,8 @@ stubbing-and-verifying: - proxying - verifying -templating: - title: Templating +library: + title: Mock API Template Library link: /docs/mock-api-templates pages: - mock-api-templates @@ -59,6 +61,7 @@ protocols: - webhooks-and-callbacks - grpc - solutions/graphql + - jwt - https configuration: diff --git a/_docs/configuration.md b/_docs/configuration.md index accf16a5..69ec41c1 100644 --- a/_docs/configuration.md +++ b/_docs/configuration.md @@ -5,6 +5,8 @@ meta_title: Configuring WireMock in Java | WireMock description: Configuring WireMock progammatically in Java. --- +
Centralize and scale your API mocks with WireMock Cloud.
+ Both `WireMockServer` and the `WireMockRule` take a configuration builder as the parameter to their constructor e.g. ```java @@ -98,6 +100,20 @@ WireMock uses the trust store for three purposes: 3. As a proxy, WireMock will trust a target server if it presents a public certificate in this trust store + +## HTTP/2 configuration + +HTTP/2 can be disabled separately for plain text (HTTP) and TLS (HTTPS): + +```java +// Disable HTTP/2 over HTTP +.http2PlainDisabled(true); + +// Disable HTTP/2 over HTTPS +.http2TlsDisabled(true); +``` + + ## Proxy settings ```java @@ -130,6 +146,11 @@ WireMock uses the trust store for three purposes: // The type of the CA key store .caKeystoreType("JKS") + +// Which proxy encodings to proxy through to the target if the request contains an Accept-Encoding header +// By default this is null, which means the header is sent to the target unchanged +// If there is an Accept-Encoding header on the request, and it does not contain any of the supported proxy encodings, the header is not sent to the target. +.withSupportedProxyEncodings("gzip", "deflate") ``` ## File locations diff --git a/_docs/download-and-installation.md b/_docs/download-and-installation.md index 6c7fa81a..11943b0b 100644 --- a/_docs/download-and-installation.md +++ b/_docs/download-and-installation.md @@ -4,17 +4,18 @@ title: Download and Installation meta_title: "How to Download and Install WireMock" toc_rank: 13 description: > - WireMock is available as a standalone service (for Docker of Java), Java library - and integrations for modern languages and technology stacks. -redirect_from: - - "/download.html" - - "/download/" - - "/downloads.html" - - "/downloads/" - - "/docs/download.html" - - "/docs/download/" + WireMock is available as a standalone service (for Docker of Java), Java library + and integrations for modern languages and technology stacks. +redirect_from: + - "/download.html" + - "/download/" + - "/downloads.html" + - "/downloads/" + - "/docs/download.html" + - "/docs/download/" --- +
To create publicly hosted mock APIs without anything to install, learn more about WireMock Cloud.
## Download options @@ -58,7 +59,7 @@ docker run -it --rm -p 8080:8080 --name wiremock \ {% endcodetab %} -{% codetab Gradle Groovy %} +{% codetab Gradle %} ```groovy testImplementation "org.wiremock:wiremock-standalone:{{ site.wiremock_version }}" diff --git a/_docs/extending-wiremock.md b/_docs/extending-wiremock.md index bebd4462..be464785 100644 --- a/_docs/extending-wiremock.md +++ b/_docs/extending-wiremock.md @@ -7,6 +7,8 @@ redirect_from: "/extending-wiremock.html" description: You can register the extension programmatically via its class name, class or an instance --- +
Chaos testing, RBAC, dynamic state and more with WireMock Cloud.
+ WireMock can be customised via a variety of extension points. Each extension point is defined by an interface that extends from `Extension` and extension implementations are loaded at startup time. @@ -26,6 +28,10 @@ At present, the following extension interfaces are available: The interfaces in this list ending with `V2` supercede deprecated equivalents with an older, more restrictive interface. Additionally `ServeEventListener` deprecates `PostServeAction`. +As of WireMock version `3.6.0`, the `Extension` interface has two new lifecycle methods called `start()` and `stop()`. +The `start()` method is called on each extension when the WireMock server first starts (just before the stub mappings +are loaded) and the `stop()` method is called when the server is stopped. This allows extensions to perform any +initialisation or cleanup tasks. ## Registering Extensions diff --git a/_docs/extensibility/adding-template-model-data.md b/_docs/extensibility/adding-template-model-data.md index 7dc0f456..c4bb1be7 100644 --- a/_docs/extensibility/adding-template-model-data.md +++ b/_docs/extensibility/adding-template-model-data.md @@ -5,7 +5,7 @@ meta_title: Adding Template Model Data description: Adding extra elements to the template model during request processing --- -Extensions that implement the `TemplateHelperProviderExtension` interface provide additional Handlebars helpers to the templating system: +Extensions that implement the `TemplateModelDataProviderExtension` interface provide additional model elements to the templating system: ```java new WireMockServer(.extensions( diff --git a/_docs/extensibility/filtering-requests.md b/_docs/extensibility/filtering-requests.md index 3bda7a62..2d3be6a4 100644 --- a/_docs/extensibility/filtering-requests.md +++ b/_docs/extensibility/filtering-requests.md @@ -5,6 +5,8 @@ meta_title: Filtering and Modifying Requests description: Filtering and modifying requests via extensions --- +
If you need to protect your mock APIs with Enterprise-grade security options, learn about WireMock Cloud.
+ Requests to both stubs and the admin API can be intercepted and either modified or halted with an immediate response. This supports a number of use cases including: authentication, URL rewriting and request header injection. diff --git a/_docs/getting-started.md b/_docs/getting-started.md index 76c09df5..8b3bbbe3 100644 --- a/_docs/getting-started.md +++ b/_docs/getting-started.md @@ -18,6 +18,7 @@ At the moment, we provide the following quick starts for beginners: - [API Mocking with Java and JUnit 4](../quickstart/java-junit) - [Downloading and Installing WireMock](../download-and-installation) +- [Using WireMock with Jetty 12](../jetty-12) diff --git a/_docs/grpc.md b/_docs/grpc.md index 7d264bc3..e7ffd8ff 100644 --- a/_docs/grpc.md +++ b/_docs/grpc.md @@ -32,7 +32,7 @@ Add the extension JAR dependency to your project: Gradle: ```gradle -implementation 'org.wiremock:wiremock-grpc-extension:{{ site.grpc_extension_version }}' +testImplementation 'org.wiremock:wiremock-grpc-extension:{{ site.grpc_extension_version }}' ``` Maven: @@ -42,6 +42,7 @@ Maven: org.wiremock wiremock-grpc-extension {{ site.grpc_extension_version }} + test ``` @@ -174,4 +175,4 @@ gRPC stubs are defined using WireMock's standard JSON format. Requests should al ## More Demos -For more see the [standalone demo project](https://github.com/wiremock/wiremock-grpc-demos/tree/main/standalone). \ No newline at end of file +For more see the [standalone demo project](https://github.com/wiremock/wiremock-grpc-demos/tree/main/standalone). diff --git a/_docs/https.md b/_docs/https.md index 289c16c4..391940bd 100644 --- a/_docs/https.md +++ b/_docs/https.md @@ -1,7 +1,7 @@ --- layout: docs -title: Serving HTTPs -meta_title: Using WireMock with HTTPs using self-signed or custom certificates | WireMock +title: Serving HTTPS +meta_title: Using WireMock with HTTPS using self-signed or custom certificates | WireMock redirect_from: "/https.html" description: WireMock can optionally accept requests over HTTPS. By default it will serve its own self-signed TLS certificate. --- @@ -76,4 +76,4 @@ HTTP port with a client that's expecting HTTPS (i.e. has `https://` in the URL). `org.apache.hc.core5.http.NoHttpResponseException: The target server failed to respond`: Could mean you've tried to connect to the HTTPS port with a client expecting HTTP. -`javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target`: You are using WireMock's default (self-signed) TLS certificate or another certificate that isn't signed by a CA. In this case you need to specifically configure your HTTP client to trust the certificate being presented, or to trust all certificates. Here is an example of [how to do this with the Apache HTTP client](https://github.com/tomakehurst/wiremock/blob/{{ site.wiremock_version }}/src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java). +`javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target`: You are using WireMock's default (self-signed) TLS certificate or another certificate that isn't signed by a CA. In this case you need to specifically configure your HTTP client to trust the certificate being presented, or to trust all certificates. Here is an example of [how to do this with the Apache HTTP client](https://github.com/wiremock/wiremock/blob/3.4.2/src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java#L207). diff --git a/_docs/jetty-12.md b/_docs/jetty-12.md new file mode 100644 index 00000000..91769fe8 --- /dev/null +++ b/_docs/jetty-12.md @@ -0,0 +1,62 @@ +--- +layout: docs +title: "Using WireMock with Jetty 12" +meta_title: Using WireMock with Jetty 12 | WireMock +description: WireMock ships with Jetty 11 by default but fully supports Jetty 12 as well. +--- + +WireMock ships with Jetty 11 by default but fully supports Jetty 12 as well with a new module `wiremock-jetty12`. In this tutorial we are going to see how Wiremock could be configured to use Jetty 12. + +## Prerequisites + +- Java 17 +- Maven or Gradle, recent versions +- A Java project, based on Maven or Gradle + +## Add WireMock Dependency to your project + +{% codetabs %} + +{% codetab Maven %} + +```xml + + org.wiremock + wiremock-jetty12 + {{ site.wiremock_version }} + test + +``` + +{% endcodetab %} + +{% codetab Gradle %} + +```groovy +testImplementation "org.wiremock:wiremock-jetty12:{{ site.wiremock_version }}" +``` + +{% endcodetab %} + +{% endcodetabs %} + +## Limitations + +There are few limitations that usage of Jetty 12 is imposing with respect to stubbing behavior. + +- status message will not be returned to the client even if set by the stub explicitly + ```java + stubFor(get("/my/resource") + .willReturn(status(400) + .withStatusMessage("ERROR"))); + + URI uri = URI.create(wireMockRule.url("/my/resource")); + HttpURLConnection connection = (HttpURLConnection) uri.toURL ().openConnection (); + connection.setRequestMethod ("GET"); + + assertThat(connection.getResponseCode()).isEqualTo(400); + assertThat(connection.getResponseMessage()).isEqualTo("Bad Request"); /* the status message is not returned */ + ``` +- when using multipart form data, the body is not decoded into plain text in case of `base64` (or other encodings) + +- serving files from configured file locations always ends up with redirect when folder (without trailing `/`) is requested diff --git a/_docs/junit-jupiter.md b/_docs/junit-jupiter.md index 2645fb75..0139f260 100644 --- a/_docs/junit-jupiter.md +++ b/_docs/junit-jupiter.md @@ -79,6 +79,18 @@ public class HttpsFixedPortDeclarativeWireMockTest { } ``` +### Enabling Extension Scanning + +When [extending WireMock via service loading](extending-wiremock.md#extension-registration-via-service-loading), it may +be helpful to have WireMock scan for extensions automatically via the `extensionScanningEnabled` parameter. + +```java +@WireMockTest(extensionScanningEnabled = true) +public class ExtensionScanningDeclarativeWireMockTest { + ... +} +``` + ## Advanced usage - programmatic Invoking the extension programmatically with `@RegisterExtension` allows you to run any number of WireMock instances and provides full control diff --git a/_docs/jwt.md b/_docs/jwt.md new file mode 100644 index 00000000..1bd3e9c0 --- /dev/null +++ b/_docs/jwt.md @@ -0,0 +1,10 @@ +--- +layout: docs +title: JSON Web Tokens (JWT) +meta_title: JSON Web Tokens +description: Generating JWTs and JWKSs +--- + +The JWT extension provides support for generating JWTs and corresponding JSON Web Key Sets (JWKS) in stub responses via response templating. + +For details see [the project's README](https://github.com/wiremock/wiremock-jwt-extension/blob/main/README.md). \ No newline at end of file diff --git a/_docs/mock-api-templates.md b/_docs/mock-api-templates.md index aa0dbc56..3229a7d6 100644 --- a/_docs/mock-api-templates.md +++ b/_docs/mock-api-templates.md @@ -8,6 +8,8 @@ description: > that can be used with both WireMock or WireMock Cloud. --- +
To easily share templates across teams or choose from thousands of popular 3rd party templates, learn more about WireMock Cloud.
+ The [library.wiremock.org](https://library.wiremock.org) site provides a catalog of API Templates that can be used with both [WireMock](https://wiremock.org/) or [WireMock Cloud](https://wiremock.io). diff --git a/_docs/proxying.md b/_docs/proxying.md index 4bd01be1..0ff4f76c 100644 --- a/_docs/proxying.md +++ b/_docs/proxying.md @@ -7,6 +7,8 @@ redirect_from: "/proxying.html" description: Proxy responses are defined in exactly the same manner as stubs, meaning that the same request matching criteria can be used. --- +
Create stubs and scenarios with WireMock Cloud's intuitive editor and share with your team.
+ WireMock has the ability to selectively proxy requests through to other hosts. This supports a proxy/intercept setup where requests are by default proxied to another (possibly real, live) service, but where @@ -102,7 +104,7 @@ the request to the destination: stubFor(get(urlMatching(".*")) .willReturn(aResponse() .proxiedFrom("http://otherhost.com") - .withAdditionalRequestHeader("User-Agent", "Mozilla/5.0 (iPhone; U; CPU iPhone)")); + .withAdditionalRequestHeader("User-Agent", "Mozilla/5.0 (iPhone; U; CPU iPhone)"))); ``` or @@ -124,6 +126,35 @@ or You can also add response headers via the same method as for non-proxy responses (see [Stubbing](../stubbing/)). +# Remove headers + +It is possible to configure the proxy to remove headers before forwarding the reques to the destination +([additional headers](#additional-headers) matching the removed headers will still be added). + +```java +stubFor(get(urlMatching(".*")) + .willReturn(aResponse() + .proxiedFrom("http://otherhost.com") + .withRemoveRequestHeader("User-Agent"))); +``` + +or + +```json +{ + "request": { + "method": "GET", + "urlPattern": ".*" + }, + "response": { + "proxyBaseUrl": "http://otherhost.com", + "removeProxyRequestHeaders": [ + "User-Agent" + ] + } +} +``` + ## Standalone shortcut It is possible to start the standalone running with the catch-all stub diff --git a/_docs/quickstart/java-junit.md b/_docs/quickstart/java-junit.md index d9bc384a..270af2a4 100644 --- a/_docs/quickstart/java-junit.md +++ b/_docs/quickstart/java-junit.md @@ -5,6 +5,8 @@ meta_title: "API Mocking QuickStart with Java and JUnit 4 | WireMock" description: "Shows how to write your API Client first test with WireMock and JUnit" --- +
Centralize and scale your API mocks with WireMock Cloud.
+ In this guide we will write an API Unit test with WireMock and JUnit 4. ## Prerequisites @@ -47,7 +49,7 @@ like [Apache HttpClient](https://hc.apache.org/httpcomponents-client-5.2.x/#). {% endcodetab %} -{% codetab Gradle Groovy %} +{% codetab Gradle %} ```groovy testImplementation "org.wiremock:wiremock:{{ site.wiremock_version }}" @@ -100,7 +102,7 @@ public void exampleTest() { // Setup HTTP POST request (with HTTP Client embedded in Java 11+) final HttpClient client = HttpClient.newBuilder().build(); final HttpRequest request = HttpRequest.newBuilder() - .uri(wiremockServer.getRequestURI("/my/resource")) + .uri(wiremockServer.url("/my/resource")) .header("Content-Type", "text/xml") .POST().build(); @@ -151,6 +153,7 @@ int httpsPort = wireMockRule.httpsPort(); ## Further reading - For more details on verifying requests and stubbing responses, see [Stubbing](../../stubbing) and [Verifying](../../verifying/) -- For more information on the JUnit rules see [The JUnit 4 Rule](../../junit-4/). +- For more information on the JUnit 4 rules see [The JUnit 4 Rule](../../junit-4/). +- For more information on the JUnit 5 Jupiter extension see [JUnit 5+ Jupiter](../../junit-jupiter/); for previous JUnit versions you can use [the JUnit 4 Rule](../../junit-extensions/). - For many more examples of JUnit tests check out the [WireMock's own acceptance tests](https://github.com/wiremock/wiremock/tree/master/src/test/java/com/github/tomakehurst/wiremock) diff --git a/_docs/request-matching.md b/_docs/request-matching.md index 73b06d58..b781ce70 100644 --- a/_docs/request-matching.md +++ b/_docs/request-matching.md @@ -6,6 +6,8 @@ toc_rank: 61 description: WireMock supports matching of requests to stubs and verification queries using the following attributes. --- +
If you need to protect your mock APIs with Enterprise-grade security options, learn about WireMock Cloud.
+ WireMock enables flexible definition of a [mock API](/) by supporting rich matching of incoming requests. Stub matching and verification queries can use the following request attributes: - URL @@ -105,7 +107,7 @@ Configuration file: ```java stubFor(post(urlPathEqualTo("/mock")) - .withFormParam("tool", equalTo("WireMock")) + .withFormParam("tool", equalTo("WireMock") ).willReturn(ok())); ``` @@ -800,7 +802,38 @@ stubFor( .willReturn(ok())); ``` -JSON: +JSON (supported in 3.4+): + +```json +{ + "request" : { + "urlPath" : "/schema-match", + "method" : "POST", + "bodyPatterns" : [ { + "matchesJsonSchema" : { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "schemaVersion" : "V202012" + } ] + }, + "response" : { + "status" : 200 + } +} +``` + +JSON with string literal: ```json { diff --git a/_docs/response-templating.md b/_docs/response-templating.md index a724cda7..c7a281c3 100644 --- a/_docs/response-templating.md +++ b/_docs/response-templating.md @@ -30,6 +30,24 @@ WireMockServer wm = See [the command line docs](../standalone/java-jar/#command-line-options) for the standalone equivalents of these parameters. +Response templating can also be disabled on a per-stub basis when using the `bodyFileName` element by adding the +`disableBodyFileTemplating` parameter to the `transformerParameters` object in the stub response definition. + +```json +{ + "request": { + "method": "GET", + "urlPath": "/test" + }, + "response": { + "status": 200, + "bodyFileName": "response.json", + "transformerParameters": { + "disableBodyFileTemplating": true + } + } +} +``` ## Customising and extending the template engine @@ -323,6 +341,30 @@ Variable assignment and number helpers are available: {% endraw %} +## Val helper + +The `val` helper can be used to access values or provide a default if the value is not present. It can also be used to +assign a value to a variable much like the `assign` helper. The main difference between `val` and `assign` is that `val` +will maintain the type of the date being assigned whereas `assign` will always assign a string. + +{% raw %} + +```handlebars +{{val request.query.search or='default'}} // the value of request.query.search or 'default' if it's not present +{{val request.query.search default='default'}} // the value of request.query.search or 'default' if it's not present +{{val request.query.search}} // the value of request.query.search or null if it's not present +{{val request.query.search or='default' assign='myVar'}} // assign the value of request.query.search or 'default' to myVar +{{val request.query.search assign='myVar'}} // assign the value of request.query.search to myVar + + +{{val (array 1 2 3) default='123'}} // [1, 2, 3] +{{val 'value for myVar' assign='myVar'}}{{myVar}} // value for myVar +{{val null or='other value for myVar' assign='myVar'}}{{myVar}} // other value for myVar +{{val 10 assign='myVar'}}{{#lt myVar 20}}Less Than{{else}}More Than{{/lt}} // Less Than +``` + +{% endraw %} + ## XPath helpers Additionally some helpers are available for working with JSON and XML. @@ -701,6 +743,91 @@ Providing no parameters will result in an empty array. {% endraw %} +## Array add & remove helpers +The `arrayAdd` and `arrayRemove` helpers can be used to add or remove elements from an array based on a position value +or the `start` or `end` keywords. If no position is specified, the element will be added or removed from the end of the +array. + +{% raw %} + +```handlebars +{{arrayAdd (array 1 'three') 2 position=1}} // [1, 2, three] +{{arrayAdd (array 1 'three') 2 position='start'}} // [2, 1, three] +{{arrayAdd (array 1 'three') 2 position='end'}} // [1, three, 2] +{{arrayAdd (array 1 'three') 2}} // [1, three, 2] + +{{arrayRemove (array 1 2 'three') position=1}} // [1, three] +{{arrayRemove (array 1 2 'three') position='start'}} // [2, three] +{{arrayRemove (array 1 2 'three') position='end'}} // [1, 2] +{{arrayRemove (array 1 2 'three')}} // [1, 2] +``` + +{% endraw %} + +## arrayJoin helper + +The `arrayJoin` helper will concatenate the values passed to it with the separator specified: + +{% raw %} + +```handlebars +{{arrayJoin ',' (array 'One' 'Two' 'Three')}} // One,Two,Three +{{arrayJoin ' - ' 'a' 'b' 'c'}} // a - b - c +{{arrayJoin ', ' (range 1 5)}} // 1, 2, 3, 4, 5 +{{arrayJoin (pickRandom ':') (array 'One' 'Two' 'Three')}} // One:Two:Three +{{arrayJoin '' (array 'W' 'i' 'r' 'e' 'M' 'o' 'c' 'k' ' ' 'R' 'o' 'c' 'k' 's')}} // WireMock Rocks +``` + +{% endraw %} + +You can also specify a `prefix` and `suffix` to be added to the start and end of the result: + +{% raw %} + +```handlebars +{{arrayJoin ',' (array 'One' 'Two' 'Three') prefix='[' suffix=']'}} // [One,Two,Three] +{{arrayJoin ' * ' (array 1 2 3) prefix='(' suffix=')'}} // (1 * 2 * 3) +``` + +{% endraw %} + +The `arrayJoin` helper can also be used as a block helper: + +{% raw %} + +```handlebars +{{#parseJson 'myThings'}} +[ + { "id": 1, "name": "One" }, + { "id": 2, "name": "Two" }, + { "id": 3, "name": "Three" } +] +{{/parseJson}} +[{{#arrayJoin ',' myThings as |item|}} +{ +"name{{item.id}}": "{{item.name}}" +} +{{/arrayJoin}}] // [{ "name1": "One" }, { "name2": "Two" }, { "name3": "Three" }] + + +// or the same example with the prefix and suffix parameters +{{#parseJson 'myThings'}} + [ + { "id": 1, "name": "One" }, + { "id": 2, "name": "Two" }, + { "id": 3, "name": "Three" } + ] +{{/parseJson}} +{{#arrayJoin ',' myThings prefix='[' suffix=']' as |item|}} + { + "name{{item.id}}": "{{item.name}}" + } +{{/arrayJoin}} // [{ "name1": "One" }, { "name2": "Two" }, { "name3": "Three" }] +``` + +{% endraw %} + + ## Contains helper The `contains` helper returns a boolean value indicating whether the string or array passed as the first parameter @@ -909,12 +1036,25 @@ Environment variables and system properties can be printed: {% raw %} ```handlebars +{{systemValue key='PATH'}} {{systemValue type='ENVIRONMENT' key='PATH'}} {{systemValue type='PROPERTY' key='os.path'}} ``` {% endraw %} +Since 3.5 a default value can be supplied: + +{% raw %} + +```handlebars +{{systemValue key='PATH' default='DEFAULT'}} +{{systemValue type='ENVIRONMENT' key='PATH' default='DEFAULT'}} +{{systemValue type='PROPERTY' key='os.path' default='DEFAULT'}} +``` + +{% endraw %} + If you want to add permitted extensions to your rule, then you can use the `ResponseTemplateTransformer` when constructing the response template extension. diff --git a/_docs/simulating-faults.md b/_docs/simulating-faults.md index fd2af476..458f7d65 100644 --- a/_docs/simulating-faults.md +++ b/_docs/simulating-faults.md @@ -7,6 +7,8 @@ redirect_from: "/simulating-faults.html" description: One of the main reasons it’s beneficial to use web service fakes when testing is to inject faulty behaviour that might be difficult to get the real service to produce on demand. --- +
To go beyond simulating faults and test product reliability in unexpected fault scenarios using Chaos Engineering, learn about WireMock Cloud.
+ **One of the main reasons it's beneficial to use web service fakes when testing is to inject faulty behaviour that might be difficult to get the real service to produce on demand. In addition to being able to send diff --git a/_docs/solutions/android.md b/_docs/solutions/android.md index 580b287d..488f93d4 100644 --- a/_docs/solutions/android.md +++ b/_docs/solutions/android.md @@ -8,6 +8,9 @@ redirect_from: "/docs/android.html" logo: /images/logos/technology/android.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
+ + ## Guide by Sam Edwards As documented by Sam Edwards in 2016, diff --git a/_docs/solutions/c_cpp.md b/_docs/solutions/c_cpp.md index 832036f9..d3e1460a 100644 --- a/_docs/solutions/c_cpp.md +++ b/_docs/solutions/c_cpp.md @@ -7,6 +7,8 @@ logo: /images/logos/technology/c.png og_image: solutions/testcontainers/testcontainers_c_opengraph.png --- +
Centralize and scale your API mocks with WireMock Cloud.
+ ## Testcontainers for C/C++ module Testcontainers C diff --git a/_docs/solutions/dotnet.md b/_docs/solutions/dotnet.md index 81ac805e..a332c58c 100644 --- a/_docs/solutions/dotnet.md +++ b/_docs/solutions/dotnet.md @@ -6,6 +6,7 @@ description: "Additional solutions for WireMock when using .NET" logo: /images/logos/technology/dotnet.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
## WireMock.Net diff --git a/_docs/solutions/golang.md b/_docs/solutions/golang.md index 5e2b8c5a..78454888 100644 --- a/_docs/solutions/golang.md +++ b/_docs/solutions/golang.md @@ -10,6 +10,8 @@ redirect_from: hide-disclaimer: true --- +
Centralize and scale your API mocks with WireMock Cloud.
+ ## Testcontainers module for Go The WireMock community provides a [Testcontainers for Go module](https://github.com/wiremock/wiremock-testcontainers-go) module diff --git a/_docs/solutions/graphql.md b/_docs/solutions/graphql.md index 24b0f91e..e25f55ce 100644 --- a/_docs/solutions/graphql.md +++ b/_docs/solutions/graphql.md @@ -11,6 +11,8 @@ redirect_from: hide-disclaimer: true --- +
Centralize and scale your API mocks with WireMock Cloud.
+ ## WireMock Extension There is a [GraphQL extension for WireMock](https://github.com/wiremock/wiremock-graphql-extension) diff --git a/_docs/solutions/groovy.md b/_docs/solutions/groovy.md index 400f251c..11d3134d 100644 --- a/_docs/solutions/groovy.md +++ b/_docs/solutions/groovy.md @@ -6,6 +6,8 @@ description: "Additional solutions for WireMock when using Groovy" logo: /images/logos/technology/groovy.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
+ ## DSL Bindings There is a [Groovy DSL binding library](https://github.com/tomjankes/wiremock-groovy) diff --git a/_docs/solutions/jvm.md b/_docs/solutions/jvm.md index ff6c06d9..d647848b 100644 --- a/_docs/solutions/jvm.md +++ b/_docs/solutions/jvm.md @@ -7,6 +7,8 @@ logo: /images/logos/technology/java.svg hide-disclaimer: true --- +
Centralize and scale your API mocks with WireMock Cloud.
+ WireMock was originally created for Java development, and there are plenty of solutions when developing applications powered by the Java Virtual Machine. @@ -64,5 +66,6 @@ sorted by alphabet: - [Clojure](https://docs.google.com/document/d/1TQccT9Bk-o2lvRVN8_mMaGttaOnwbYFLkn0DsmwGIOA/edit#heading=h.gvb3rxc1ab9p) - [Groovy](../groovy) - [Kotlin](../kotlin) +- [Pact](../pact) - [Scala](https://docs.google.com/document/d/1TQccT9Bk-o2lvRVN8_mMaGttaOnwbYFLkn0DsmwGIOA/edit#heading=h.gvb3rxc1ab9p) - [Spring Boot](../spring-boot) diff --git a/_docs/solutions/kotlin.md b/_docs/solutions/kotlin.md index 322b90d8..1fdb38bb 100644 --- a/_docs/solutions/kotlin.md +++ b/_docs/solutions/kotlin.md @@ -6,6 +6,7 @@ description: Additional solutions for WireMock when using Kotlin logo: /images/logos/technology/kotlin.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
## Kotlin DSL Bindings diff --git a/_docs/solutions/kubernetes.md b/_docs/solutions/kubernetes.md index 5e22728b..47bb695a 100644 --- a/_docs/solutions/kubernetes.md +++ b/_docs/solutions/kubernetes.md @@ -7,6 +7,8 @@ logo: /images/logos/technology/kubernetes.svg hide-disclaimer: true --- +
Centralize and scale your API mocks with WireMock Cloud.
+ ## WireMock Helm Chart (Experimental) There is an [experimental Helm Chart](https://wiremock.github.io/helm-charts/) for WireMock. diff --git a/_docs/solutions/nodejs.md b/_docs/solutions/nodejs.md index 47f9f867..1d8a6c9b 100644 --- a/_docs/solutions/nodejs.md +++ b/_docs/solutions/nodejs.md @@ -6,6 +6,8 @@ description: Additional solutions for WireMock when using Node.js logo: /images/logos/technology/nodejs.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
+ ## WireMock Captain WireMock Captain provides an easy interface for testing HTTP-based APIs. @@ -61,3 +63,11 @@ console.log(stubMappings); await wireMock.global.shutdown(); ``` + +## WireMock NPM package + +The WireMock NPM package is the WireMock standalone JAR packaged inside an NPM package. It has the exact same features as WireMock standalone and uses the same versioning. + +The main benefit of packaging it inside an NPM package is that the user will only need access to an NPM registry to use it. This is often the situation when working behind firewalls in organizations. + +- [GitHUb Repository](https://github.com/wiremock/wiremock-npm) diff --git a/_docs/solutions/pact.md b/_docs/solutions/pact.md new file mode 100644 index 00000000..9ef7935d --- /dev/null +++ b/_docs/solutions/pact.md @@ -0,0 +1,176 @@ +--- +layout: solution +title: "Using WireMock with Pact" +meta_title: Running WireMock with Pact | WireMock +description: The recorded invocations on WireMock can be used to generate the JSON files that are needed to publish contracts to the Pactflow broker. +redirect_from: +- "/docs/pact.html" +--- + +## WireMock Pact + +WireMock Pact will get the requests from [WireMock](https://github.com/wiremock/wiremock/) and create [Pact JSON](https://docs.pact.io/) files on the filesystem. The Pact JSON can be published to a [Pactflow broker](https://test.pactflow.io/). + +WireMock Pact contains: + +- `wiremock-pact-lib` - *A library that can transform WireMock [ServeEvent](https://github.com/wiremock/wiremock/blob/master/src/main/java/com/github/tomakehurst/wiremock/stubbing/ServeEvent.java):s to Pact JSON.* +- `wiremock-pact-extension-junit5` - *A WireMock extension, and JUnit 5, that is intended to ease usage of the library.* +- `wiremock-pact-example-springboot-app` - *A SpringBoot application that shows how it can be used.* + +WireMock Pact is released to [Maven Central](https://central.sonatype.com/search?q=se.bjurr.wiremockpact). And [available on GitHub](https://github.com/wiremock/wiremock-pact). + +## Usage - Junit 5 + +The extension is both a WireMock extension and a JUnit 5 extension. When using [`wiremock-spring-boot`](https://wiremock.org/docs/solutions/spring-boot/) it can be configured like this in a base class of your tests: + +```java +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.maciejwalkowiak.wiremock.spring.ConfigureWireMock; +import com.maciejwalkowiak.wiremock.spring.EnableWireMock; +import com.maciejwalkowiak.wiremock.spring.WireMockConfigurationCustomizer; +import org.junit.jupiter.api.extension.RegisterExtension; +import se.bjurr.wiremockpact.wiremockpactextensionjunit5.WireMockPactExtension; +import se.bjurr.wiremockpact.wiremockpactlib.api.WireMockPactConfig; + +@EnableWireMock({ + @ConfigureWireMock( + name = "wiremock-service-name", + property = "wiremock.server.url", + stubLocation = "wiremock", + configurationCustomizers = {WireMockPactBaseTest.class}) +}) +public class WireMockPactBaseTest implements WireMockConfigurationCustomizer { + @RegisterExtension + static WireMockPactExtension WIREMOCK_PACT_EXTENSION = + new WireMockPactExtension( + WireMockPactConfig.builder() // + .setConsumerDefaultValue("WireMockPactExample") // + .setProviderDefaultValue("UnknownProvider") // + .setPactJsonFolder("src/test/resources/pact-json")); + + @Override + public void customize( + final WireMockConfiguration configuration, final ConfigureWireMock options) { + configuration.extensions(WIREMOCK_PACT_EXTENSION); + } +} +``` + +### Usage - Library + +It can be used as a library. + +```java +public class ExampleTest { + private static WireMockServer server; + private static WireMockPactApi wireMockPactApi; + + @BeforeAll + public static void beforeEach() throws IOException { + server = new WireMockServer(); + server.start(); + + stubFor( + post(anyUrl()) + .willReturn( + ok() + .withHeader("content-type", "application/json") + .withBody(""" + {"a":"b"} + """)) + .withMetadata( + new Metadata( + Map.of( + WireMockPactMetadata.METADATA_ATTR, + new WireMockPactMetadata() + .setProvider("some-specific-provider"))))); + + wireMockPactApi = + WireMockPactApi.create( + new WireMockPactConfig() + .setConsumerDefaultValue("my-service") + .setProviderDefaultValue("unknown-service") + .setPactJsonFolder("the/pact-json/folder")); + wireMockPactApi.clearAllSaved(); + } + + @Test + public void testInvoke() { + // Do stuff that invokes WireMock... + } + + @AfterAll + public static void after() { + for (final ServeEvent serveEvent : server.getAllServeEvents()) { + wireMockPactApi.addServeEvent(serveEvent); + } + // Save pact-json to folder given in WireMockPactApi + wireMockPactApi.saveAll(); + server.stop(); + } +} +``` + +### Mappings metadata - Set provider in mapping + +You can adjust any mappings file like this to specify the provider of a mapping in its [metadata](https://github.com/wiremock/spec/blob/main/wiremock/wiremock-admin-api/schemas/stub-mapping.yaml) field: + +```diff +{ + "id" : "d68fb4e2-48ed-40d2-bc73-0a18f54f3ece", + "request" : { + "urlPattern" : "/animals/1", + "method" : "GET" + }, + "response" : { + "status" : 202 + }, + "uuid" : "d68fb4e2-48ed-40d2-bc73-0a18f54f3ece", ++ "metadata": { ++ "wireMockPactSettings": { ++ "provider":"some-other-system" ++ } ++ } +} +``` + +Or programmatically: + +```java + stubFor( + post(anyUrl()) + .withMetadata( + new Metadata( + Map.of( + WireMockPactMetadata.METADATA_ATTR, + new WireMockPactMetadata() + .setProvider("some-specific-provider"))))); +``` + +### Publishing to Pact broker + +Pact has a [CLI tool](https://docs.pact.io/pact_broker/publishing_and_retrieving_pacts) that can be used for publishing the contracts. But it requires Ruby or Docker. If you don't have that, perhaps `curl` is an option. There is [a shell script here](https://github.com/tomasbjerre/pactflow-publish-sh) that can also be used [via NPM](https://www.npmjs.com/package/pactflow-publish-sh). + +You may want to use something like [git-changelog-command-line](https://github.com/tomasbjerre/git-changelog-command-line) to get the next version. + +There is a test-server at https://test.pactflow.io/ that can be accessed with user `dXfltyFMgNOFZAxr8io9wJ37iUpY42M` and password `O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1`. + +```sh +current_version=$(npx git-changelog-command-line \ + --patch-version-pattern "^fix.*" \ + --print-current-version) +git_hash=`git rev-parse --short HEAD` +participant_version_number="$current_version-$git_hash" + +npx pactflow-publish-sh \ + --username=dXfltyFMgNOFZAxr8io9wJ37iUpY42M \ + --password=O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1 \ + --pactflow-broker-url=https://test.pactflow.io/contracts/publish \ + --build-url=http://whatever/ \ + --pact-json-folder=wiremock-pact-example-springboot-app/src/test/resources/pact-json \ + --participant-version-number=$participant_version_number +``` + +## Useful pages + +- [WireMock on Java and JVM](../jvm) - Most of JVM generic solutions are applicable to Spring Boot development too diff --git a/_docs/solutions/python.md b/_docs/solutions/python.md index 8f4f2f93..a57ce433 100644 --- a/_docs/solutions/python.md +++ b/_docs/solutions/python.md @@ -7,6 +7,7 @@ logo: /images/logos/technology/python.svg hide-disclaimer: true --- +
Centralize and scale your API mocks with WireMock Cloud.
## Python WireMock diff --git a/_docs/solutions/quarkus.md b/_docs/solutions/quarkus.md index eb642a3d..b4360e88 100644 --- a/_docs/solutions/quarkus.md +++ b/_docs/solutions/quarkus.md @@ -6,6 +6,7 @@ description: "Additional solutions for WireMock when developing with Quarkus" logo: /images/logos/technology/quarkus.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
## WireMock Extension for Quarkus diff --git a/_docs/solutions/rust.md b/_docs/solutions/rust.md index 150db781..a2bceffc 100644 --- a/_docs/solutions/rust.md +++ b/_docs/solutions/rust.md @@ -6,6 +6,8 @@ description: "Additional solutions for WireMock when using Rust" logo: /images/logos/technology/rust.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
+ ## wiremock-rs. Server implementation in Rust [LukeMathWalker/wiremock-rs](https://github.com/LukeMathWalker/wiremock-rs) is an API Mock Server implementation in Rust. diff --git a/_docs/solutions/spring-boot.md b/_docs/solutions/spring-boot.md index bb27b622..9056da9c 100644 --- a/_docs/solutions/spring-boot.md +++ b/_docs/solutions/spring-boot.md @@ -9,6 +9,10 @@ redirect_from: logo: /images/logos/technology/spring.svg --- +
Centralize and scale your API mocks with WireMock Cloud.
+ +
Centralize and scale your API mocks with WireMock Cloud.
+ ## WireMock Spring Boot [WireMock Spring Boot](https://github.com/maciejwalkowiak/wiremock-spring-boot) @@ -37,14 +41,14 @@ class TodoControllerTests { void aTest() { // returns a URL to WireMockServer instance env.getProperty("user-client.url"); - wiremock.stubFor(stubFor(get("/todolist").willReturn(aResponse() + wiremock.stubFor(get("/todolist").willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(""" [ { "id": 1, "userId": 1, "title": "my todo" }, ] """) - ))); + )); } } ``` @@ -59,6 +63,14 @@ See [Spring Cloud Contract WireMock](https://docs.spring.io/spring-cloud-contrac The article [Faking OAuth2 Single Sign-on in Spring](https://engineering.pivotal.io/post/faking_oauth_sso/) from Pivotal's blog shows how WireMock can be used to test Spring apps that use 3rd party OAuth2 login. + +## Jetty version issues when running WireMock and Spring together. + +WireMock's main artifact is built on Jetty 11, largely so that Java 11 support can be maintained. However, many Spring applications depend on Jetty 12 and the presence of both on the classpath causes WireMock to fail with a `ClassNotFoundException` or `NoClassDefFoundError` for Servlet API classes thrown during startup. + +To rectify this, WireMock now has a dedicated Jetty 12 artifact which can be added to your project's classpath. See the [Jetty 12 page](../../jetty-12/) for details. + + ## Useful pages -- [WireMock on Java and JVM](../solutions/jvm) - Most of JVM generic solutions are applicable to Spring Boot development too +- [WireMock on Java and JVM](../jvm) - Most of JVM generic solutions are applicable to Spring Boot development too diff --git a/_docs/solutions/testcontainers.md b/_docs/solutions/testcontainers.md index c1d5f83b..0925f66d 100644 --- a/_docs/solutions/testcontainers.md +++ b/_docs/solutions/testcontainers.md @@ -12,6 +12,8 @@ redirect_from: - "/testcontainers/" --- +
Centralize and scale your API mocks with WireMock Cloud.
+ The WireMock community provides modules for [Testcontainers](https://testcontainers.com/). They allow provisioning the WireMock server as a standalone container within your tests, based on [WireMock Docker](https://github.com/wiremock/wiremock-docker). diff --git a/_docs/standalone.md b/_docs/standalone.md index 5c731e2b..b539afcb 100644 --- a/_docs/standalone.md +++ b/_docs/standalone.md @@ -10,6 +10,8 @@ description: > We provide the JAR file and Docker image distributions for it. --- +
WireMock Cloud offers secure, publicly hosted mock APIs with nothing to install.
+ WireMock can run as a standalone service, configured via the Java API, JSON over HTTP or JSON files. We provide the JAR file and Docker image distributions for it. diff --git a/_docs/standalone/admin-api-reference.md b/_docs/standalone/admin-api-reference.md index 8476f05e..e0ee326c 100644 --- a/_docs/standalone/admin-api-reference.md +++ b/_docs/standalone/admin-api-reference.md @@ -10,6 +10,8 @@ redirect_from: - "/docs/api/" --- +
WireMock Cloud offers secure, publicly hosted mock APIs with nothing to install.
+ The WireMock admin API is described in [OpenAPI 3.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md). The spec file plus an instance of Swagger UI can be accessed from a running WireMock instance under `/__admin/docs/`, e.g. `http://localhost:8080/__admin/docs/`. Below is the full API reference: diff --git a/_docs/standalone/administration.md b/_docs/standalone/administration.md index ff573545..2197f2c1 100644 --- a/_docs/standalone/administration.md +++ b/_docs/standalone/administration.md @@ -5,12 +5,14 @@ meta_title: Administration API in WireMock Standalone | WireMock description: Provides tips on managing standalone WireMock servers --- +
WireMock Cloud offers secure, publicly hosted mock APIs with nothing to install.
+ WireMock Standalone offers the REST API for administration, troubleshooting and analysis purposes. You can find the key use-cases and the full specification below. ## Fetching all of your stub mappings (and checking WireMock is working) -A GET request to the root admin URL e.g `http://localhost:8080/__admin` +A GET request to the mappings admin URL e.g `http://localhost:8080/__admin/mappings` will return all currently registered stub mappings. This is a useful way to check whether WireMock is running on the host and port you expect. diff --git a/_docs/standalone/docker.md b/_docs/standalone/docker.md index 2ebc00b4..1d6eee86 100644 --- a/_docs/standalone/docker.md +++ b/_docs/standalone/docker.md @@ -9,6 +9,8 @@ redirect_from: - "/docs/docker/" --- +
WireMock Cloud offers secure, publicly hosted mock APIs with nothing to install.
+ From version 2.31.0 WireMock has an [official Docker image](https://hub.docker.com/r/wiremock/wiremock). ## Getting started @@ -123,6 +125,7 @@ services: image: "wiremock/wiremock:latest" container_name: my_wiremock volumes: + - ./extensions:/var/wiremock/extensions - ./__files:/home/wiremock/__files - ./mappings:/home/wiremock/mappings entrypoint: ["/docker-entrypoint.sh", "--global-response-templating", "--disable-gzip", "--verbose"] diff --git a/_docs/standalone/java-jar.md b/_docs/standalone/java-jar.md index fd949cff..c095e3c6 100644 --- a/_docs/standalone/java-jar.md +++ b/_docs/standalone/java-jar.md @@ -11,10 +11,12 @@ redirect_from: description: The WireMock server can be run in its own process, and configured via the Java API, JSON over HTTP or JSON files. --- +
WireMock Cloud offers secure, publicly hosted mock APIs with nothing to install.
+ The WireMock server can be run in its own process, and configured via the Java API, JSON over HTTP or JSON files. -Once you have [downloaded the standalone JAR](../../download) you can run it simply by doing this: +Once you have [downloaded the standalone JAR](../../download-and-installation/) you can run it simply by doing this: ```bash $ java -jar wiremock-standalone-{{ site.wiremock_version }}.jar @@ -28,6 +30,10 @@ The following can optionally be specified on the command line: `--disable-http`: Disable the HTTP listener, option available only if HTTPS is enabled. +`--disable-http2-plain`: Disable HTTP/2 over plain text (HTTP). + +`--disable-http2-tls`: Disable HTTP/2 over TLS (HTTPS). + `--https-port`: If specified, enables HTTPS on the supplied port. Note: When you specify this parameter, WireMock will still, additionally, bind to an HTTP port (8080 by default). So when running multiple WireMock servers you will also need to specify the `--port` parameter in order to avoid conflicts. @@ -94,6 +100,10 @@ internet access via an opaque proxy). e.g. `--proxy-via webproxy.mycorp.com:8080`. Also supports proxy authentication, e.g. `--proxy-via http://username:password@webproxy.mycorp.com:8080/`. +`--supported-proxy-encodings`: The set of acceptable compression methods represented in the `accept-encoding` request header +sent by WireMock when proxying or recording expressed as a comma-separated list e.g `gzip,deflate`. This is particularly useful if you want to avoid recording e.g. brotli compresssed responses +that can't then be viewed in the request log or served with a different compression scheme on playback, which can be achieved via `--supported-proxy-encodings=identity`. + `--enable-browser-proxying`: Run as a browser proxy. See [Running as a browser proxy](../../proxying#running-as-a-browser-proxy). @@ -212,7 +222,7 @@ You can create a stub mapping by posting to WireMock's HTTP API: ```bash $ curl -X POST \ --data '{ "request": { "url": "/get/this", "method": "GET" }, "response": { "status": 200, "body": "Here it is!\n" }}' \ -http://localhost:8080/__admin/mappings/new +http://localhost:8080/__admin/mappings ``` And then fetch it back: diff --git a/_docs/stateful-behaviour.md b/_docs/stateful-behaviour.md index d4a5838a..32ef3739 100644 --- a/_docs/stateful-behaviour.md +++ b/_docs/stateful-behaviour.md @@ -6,6 +6,8 @@ redirect_from: "/stateful-behaviour.html" description: Most web services tend to have some state, which changes as you and others interact with it. --- +
Create stubs and scenarios with WireMock Cloud's intuitive editor and share with your team.
+ **Most web services tend to have some state, which changes as you and others interact with it. So it's pretty useful to be able to simulate this when you've swapped a real service for a test double.** diff --git a/_docs/stubbing.md b/_docs/stubbing.md index eb72e0c3..f323c344 100644 --- a/_docs/stubbing.md +++ b/_docs/stubbing.md @@ -7,6 +7,8 @@ redirect_from: "/stubbing.html" description: A core feature of WireMock is the ability to return canned HTTP responses for requests matching criteria. These are described in detail in Request Matching. --- +
Create stubs and scenarios with WireMock Cloud's intuitive editor and share with your team.
+ A core feature of WireMock [API mocking]({{ '/' | absolute_url }}) is the ability to return canned HTTP responses for requests matching criteria. These are described in detail in [Request Matching](../request-matching/). @@ -133,8 +135,31 @@ stubFor(put("/status-only") More DSL examples [can be found here](https://github.com/tomakehurst/wiremock/tree/master/src/test/java/ignored/Examples.java#374). HTTP methods currently supported are: -`GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS`. You can specify `ANY` if -you want the stub mapping to match on any request method. +`GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS, GET_OR_HEAD`. You can specify `ANY` if +you want the stub mapping to match on any request method. `GET_OR_HEAD` is a special +method that could be used to match incoming requests for both `GET` or `HEAD` http +method. A ```HEAD``` request will result in the same behaviour expected from a web server i.e. +the ```Content-Type``` and ```Content-Length``` headers will be emitted but no response body. +A detailed guide about various HTTP methods can be found [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). +```GET_OR_HEAD``` can be used the following way + +{% codetabs %} + +{% codetab Java %} + +```java +@Test +public void getOrHeadDemo() { + stubFor(getOrHead(urlEqualTo("/get-or-head-test")) + .willReturn(okJson("{\"key\": \"value\"}"))); + + assertThat(testClient.get("/get-or-head-test").statusCode(), is(200)); +} +``` + +{% endcodetab %} + +{% endcodetabs %} ### Setting the response status message @@ -517,15 +542,29 @@ This feature is also available with the standard JAR. To use it, define the file ## Removing stubs -Stub mappings can be deleted via the Java API as follows: +Stub mappings can be deleted via the Java API, either by passing the stub object or the stub ID: ```java -StubMapping stubMapping = stubFor(get(urlEqualTo("/delete-me")) - .willReturn(aResponse().withStatus(200))); - -// Do things with the stub +UUID stubId = UUID.randomUUID(); +StubMapping stubMapping = stubFor(get("/delete-me") + .withId(stubId) + .willReturn(ok())); removeStub(stubMapping); + +// or + +removeStub(stubId); +``` + +Where stubs have metadata set on them this can be used to remove them: + +```java +stubFor(get("/delete-me") + .withMetadata(metadata().attr("tag", "payments")) + .willReturn(ok())); + +removeStubsByMetadata(matchingJsonPath("$.tag", equalTo("payments"))); ``` They can be deleted via the HTTP API by issuing a `DELETE` to `http://:/__admin/mappings/{id}` @@ -630,3 +669,20 @@ This can be changed by setting `duplicatePolicy` in the JSON to `IGNORE` or call If you want to ensure that the only stubs loaded after the import has completed are the ones it contains, you can set `"deleteAllNotInImport": true` in the JSON or call `deleteAllExistingStubsNotInImport()` on the Java builder. + +### Disabling Gzip at the ResponseDefinitionBuilder + +If you want to user Gzip disabled response option at the ResponseDefinitionBuilder level. +You can use `.withGzipDisabled(true)` + +```java + +wireMockServer.stubFor(get(urlEqualTo("/todo/items")) + .willReturn(aResponse() + .withStatus(200) + .withGzipDisabled(true) + .withBody( + "Here is some kind of response body" + + "Here is some kind of response body" + + "Here is some kind of response body"))); +``` diff --git a/_docs/verifying.md b/_docs/verifying.md index 4aee216b..c9abd2b3 100644 --- a/_docs/verifying.md +++ b/_docs/verifying.md @@ -7,6 +7,8 @@ redirect_from: "/verifying.html" description: Verifying and querying requests relies on the request journal, which is an in-memory log of received requests. This can be disabled for load testing. --- + + The WireMock server records all requests it receives in memory (at least until it is [reset](../stubbing#reset)). This makes it possible to verify that a request matching a specific pattern was received, and also to fetch diff --git a/_includes/masthead.html b/_includes/masthead.html index e49257ec..9577618d 100644 --- a/_includes/masthead.html +++ b/_includes/masthead.html @@ -66,7 +66,7 @@
- Go to WM Cloud + Try WireMock Cloud Free forever. No credit card needed
@@ -80,7 +80,7 @@