From 4b2df482870b8eb6c23c203523b42812a45da2bd Mon Sep 17 00:00:00 2001 From: Dirk Bolte Date: Mon, 24 Jun 2024 22:35:41 +0200 Subject: [PATCH] bug!: fix compatibility issue with wiremock 3.7.0 --- .github/workflows/build-and-test.yml | 4 +- README.md | 1 + build.gradle | 5 +- compatibility_test/build.gradle | 34 +++ compatibility_test/gradle.properties | 0 .../gradle/wrapper/gradle-wrapper.properties | 7 + compatibility_test/gradlew | 249 ++++++++++++++++++ compatibility_test/gradlew.bat | 92 +++++++ compatibility_test/settings.gradle | 0 .../StateExtensionListExampleTest.java | 180 +++++++++++++ .../StateExtensionQueueExampleTest.java | 192 ++++++++++++++ .../StateExtensionStateExampleTest.java | 167 ++++++++++++ .../extensions/DeleteStateEventListener.java | 8 +- .../extensions/RecordStateEventListener.java | 8 +- .../state/extensions/StateRequestMatcher.java | 2 +- .../StateExtensionListExampleTest.java | 2 - .../StateExtensionQueueExampleTest.java | 2 - .../StateExtensionStateExampleTest.java | 2 - .../DeleteStateEventListenerTest.java | 1 + 19 files changed, 938 insertions(+), 18 deletions(-) create mode 100644 compatibility_test/build.gradle create mode 100644 compatibility_test/gradle.properties create mode 100644 compatibility_test/gradle/wrapper/gradle-wrapper.properties create mode 100755 compatibility_test/gradlew create mode 100644 compatibility_test/gradlew.bat create mode 100644 compatibility_test/settings.gradle create mode 100644 compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionListExampleTest.java create mode 100644 compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionQueueExampleTest.java create mode 100644 compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionStateExampleTest.java diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index a5a88ff..08e6fc3 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -37,7 +37,7 @@ jobs: java-version: ${{ matrix.jdk }} distribution: 'temurin' - name: Run the Gradle package task - uses: gradle/gradle-build-action@v2 + uses: gradle/actions/setup-gradle@v3 with: arguments: build check - name: Generate coverage badges @@ -84,7 +84,7 @@ jobs: java-version: 11 distribution: 'temurin' - name: Run the Gradle package task - uses: gradle/gradle-build-action@v2 + uses: gradle/actions/setup-gradle@v3 with: arguments: jar shadowjar - name: Archive production artifacts diff --git a/README.md b/README.md index 3bf7eb7..2fb0f17 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ the `GET` won't have any knowledge of the previous post. | `wiremock-state-extension` version | `WireMock` version | |------------------------------------|--------------------| +| `0.8.0`+ | `3.7.0`+ | | `0.7.0`+ | `3.6.0`+ | | `0.5.1`+ | `3.3.1`+ | | `0.1.0`+ | `3.0.0`+ | diff --git a/build.gradle b/build.gradle index 37e35a0..11624d1 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { plugins { id 'jacoco' id 'com.diffplug.spotless' version '6.25.0' - id 'org.wiremock.tools.gradle.wiremock-extension-convention' version '0.2.0' + id 'org.wiremock.tools.gradle.wiremock-extension-convention' version '0.3.0' } group 'org.wiremock.extensions' @@ -15,14 +15,17 @@ project.ext { versions = [ caffeine : '3.1.8', handlebars : '4.3.1', + wiremock : '3.7.0' ] } dependencies { + compileOnly("org.wiremock:wiremock:${versions.wiremock}") implementation("com.github.ben-manes.caffeine:caffeine:${versions.caffeine}") implementation("com.github.jknack:handlebars-helpers:${versions.handlebars}") { exclude group: 'org.mozilla', module: 'rhino' } + testImplementation("org.wiremock:wiremock:${versions.wiremock}") } java { diff --git a/compatibility_test/build.gradle b/compatibility_test/build.gradle new file mode 100644 index 0000000..4747e3a --- /dev/null +++ b/compatibility_test/build.gradle @@ -0,0 +1,34 @@ +plugins { + id 'java' +} + +repositories { + mavenCentral() + mavenLocal() +} + +group 'org.wiremock.extensions.compatibility' +project.ext { + versions = [ + wiremock : '3.7.0', + stateextension: '0.7.0' + ] +} + +dependencies { + testImplementation("org.wiremock:wiremock:${versions.wiremock}") + testImplementation("org.wiremock.extensions:wiremock-state-extension:${versions.stateextension}") + testImplementation('io.rest-assured:rest-assured:5.4.0') + testImplementation('org.junit.jupiter:junit-jupiter:5.10.2') + testImplementation('org.assertj:assertj-core:3.26.0') + testImplementation('org.awaitility:awaitility:4.2.1') +} + +java { + sourceCompatibility = 11 + targetCompatibility = 11 +} + +test { + useJUnitPlatform() +} diff --git a/compatibility_test/gradle.properties b/compatibility_test/gradle.properties new file mode 100644 index 0000000..e69de29 diff --git a/compatibility_test/gradle/wrapper/gradle-wrapper.properties b/compatibility_test/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3fa8f86 --- /dev/null +++ b/compatibility_test/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/compatibility_test/gradlew b/compatibility_test/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/compatibility_test/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/compatibility_test/gradlew.bat b/compatibility_test/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/compatibility_test/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/compatibility_test/settings.gradle b/compatibility_test/settings.gradle new file mode 100644 index 0000000..e69de29 diff --git a/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionListExampleTest.java b/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionListExampleTest.java new file mode 100644 index 0000000..947ca4d --- /dev/null +++ b/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionListExampleTest.java @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2023 Dirk Bolte + * + * 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 org.wiremock.extensions.state.compatibility; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.common.ConsoleNotifier; +import com.github.tomakehurst.wiremock.extension.Parameters; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.store.Store; +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.http.HttpStatus; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.parallel.Execution; +import org.wiremock.extensions.state.CaffeineStore; +import org.wiremock.extensions.state.StateExtension; + +import java.net.URI; +import java.util.Map; + +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.parallel.ExecutionMode.SAME_THREAD; + +/** + * Sample test for creating a mock for a listing with java. + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Execution(SAME_THREAD) +class StateExtensionListExampleTest { + + private static final String TEST_URL = "/listing"; + private static final Store store = new CaffeineStore(); + private static final ObjectMapper mapper = new ObjectMapper(); + + @RegisterExtension + public static WireMockExtension wm = WireMockExtension.newInstance() + .options( + wireMockConfig().dynamicPort().dynamicHttpsPort().templatingEnabled(true).globalTemplating(true) + .extensions(new StateExtension(store)) + .notifier(new ConsoleNotifier(true)) + ) + .build(); + + + @BeforeEach + public void setup() throws JsonProcessingException { + RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); + createGetStub(); + createPostStub(); + } + + @Test + public void testList() { + var firstNameOne = RandomStringUtils.randomAlphabetic(5); + var lastNameOne = RandomStringUtils.randomAlphabetic(5); + var firstNameTwo = RandomStringUtils.randomAlphabetic(5); + var lastNameTwo = RandomStringUtils.randomAlphabetic(5); + + var idOne = given() + .accept(ContentType.JSON) + .body(Map.of("firstName", firstNameOne, "lastName", lastNameOne)) + .post(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.notNullValue()) + .body("firstName", Matchers.equalTo(firstNameOne)) + .body("lastName", Matchers.equalTo(lastNameOne)) + .extract() + .body() + .jsonPath().get("id"); + var idTwo = given() + .accept(ContentType.JSON) + .body(Map.of("firstName", firstNameTwo, "lastName", lastNameTwo)) + .post(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.notNullValue()) + .body("firstName", Matchers.equalTo(firstNameTwo)) + .body("lastName", Matchers.equalTo(lastNameTwo)) + .extract() + .body() + .jsonPath().get("id"); + + given() + .accept(ContentType.JSON) + .get(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("$", Matchers.hasSize(2)) + .body("[0].id", Matchers.equalTo(idOne)) + .body("[0].firstName", Matchers.equalTo(firstNameOne)) + .body("[0].lastName", Matchers.equalTo(lastNameOne)) + .body("[1].id", Matchers.equalTo(idTwo)) + .body("[1].firstName", Matchers.equalTo(firstNameTwo)) + .body("[1].lastName", Matchers.equalTo(lastNameTwo)); + } + + + private void createPostStub() throws JsonProcessingException { + wm.stubFor( + post(urlPathMatching(TEST_URL)) + .willReturn( + WireMock.ok() + .withHeader("content-type", "application/json") + .withJsonBody( + mapper.readTree( + mapper.writeValueAsString( + Map.of( + "id", "{{randomValue length=32 type='ALPHANUMERIC' uppercase=false}}", + "firstName", "{{jsonPath request.body '$.firstName'}}", + "lastName", "{{jsonPath request.body '$.lastName'}}" + ) + ) + ) + ) + ) + .withServeEventListener( + "recordState", + Parameters.from( + Map.of( + "context", "list", + "list", Map.of( + "addLast", Map.of( + "id", "{{jsonPath response.body '$.id'}}", + "firstName", "{{jsonPath request.body '$.firstName'}}", + "lastName", "{{jsonPath request.body '$.lastName'}}" + ) + ) + ) + ) + ) + ); + } + + private void createGetStub() { + wm.stubFor( + get(urlPathMatching(TEST_URL)) + .willReturn( + WireMock.ok() + .withHeader("content-type", "application/json") + .withBody( + "[\n" + + "{{#each (state context='list' property='list' default='[]') }}" + + " {\n" + + " \"id\": \"{{id}}\",\n" + + " \"firstName\": \"{{firstName}}\",\n" + + " \"lastName\": \"{{lastName}}\"" + + " }{{#unless @last}},{{/unless}}\n" + + "{{/each}}" + + "]" + ) + ) + ); + } +} diff --git a/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionQueueExampleTest.java b/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionQueueExampleTest.java new file mode 100644 index 0000000..517e080 --- /dev/null +++ b/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionQueueExampleTest.java @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2023 Dirk Bolte + * + * 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 org.wiremock.extensions.state.compatibility; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.common.ConsoleNotifier; +import com.github.tomakehurst.wiremock.extension.Parameters; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.store.Store; +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.http.HttpStatus; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.parallel.Execution; +import org.wiremock.extensions.state.CaffeineStore; +import org.wiremock.extensions.state.StateExtension; + +import java.net.URI; +import java.util.Map; + +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.parallel.ExecutionMode.SAME_THREAD; + +/** + * Sample test for creating a mock for a queue with java. + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Execution(SAME_THREAD) +class StateExtensionQueueExampleTest { + + private static final String TEST_URL = "/queue"; + private static final Store store = new CaffeineStore(); + private static final ObjectMapper mapper = new ObjectMapper(); + + @RegisterExtension + public static WireMockExtension wm = WireMockExtension.newInstance() + .options( + wireMockConfig().dynamicPort().dynamicHttpsPort().templatingEnabled(true).globalTemplating(true) + .extensions(new StateExtension(store)) + .notifier(new ConsoleNotifier(true)) + ) + .build(); + + + @BeforeEach + public void setup() throws JsonProcessingException { + RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); + createGetStub(); + createPostStub(); + } + + @Test + public void testQueue() { + var firstNameOne = RandomStringUtils.randomAlphabetic(5); + var lastNameOne = RandomStringUtils.randomAlphabetic(5); + var firstNameTwo = RandomStringUtils.randomAlphabetic(5); + var lastNameTwo = RandomStringUtils.randomAlphabetic(5); + + var idOne = given() + .accept(ContentType.JSON) + .body(Map.of("firstName", firstNameOne, "lastName", lastNameOne)) + .post(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.notNullValue()) + .body("firstName", Matchers.equalTo(firstNameOne)) + .body("lastName", Matchers.equalTo(lastNameOne)) + .extract() + .body() + .jsonPath().get("id"); + var idTwo = given() + .accept(ContentType.JSON) + .body(Map.of("firstName", firstNameTwo, "lastName", lastNameTwo)) + .post(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.notNullValue()) + .body("firstName", Matchers.equalTo(firstNameTwo)) + .body("lastName", Matchers.equalTo(lastNameTwo)) + .extract() + .body() + .jsonPath().get("id"); + + given() + .accept(ContentType.JSON) + .get(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.equalTo(idOne)) + .body("firstName", Matchers.equalTo(firstNameOne)) + .body("lastName", Matchers.equalTo(lastNameOne)); + given() + .accept(ContentType.JSON) + .get(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.equalTo(idTwo)) + .body("firstName", Matchers.equalTo(firstNameTwo)) + .body("lastName", Matchers.equalTo(lastNameTwo)); + } + + + private void createPostStub() throws JsonProcessingException { + wm.stubFor( + post(urlPathMatching(TEST_URL)) + .willReturn( + WireMock.ok() + .withHeader("content-type", "application/json") + .withJsonBody( + mapper.readTree( + mapper.writeValueAsString( + Map.of( + "id", "{{randomValue length=32 type='ALPHANUMERIC' uppercase=false}}", + "firstName", "{{jsonPath request.body '$.firstName'}}", + "lastName", "{{jsonPath request.body '$.lastName'}}" + ) + ) + ) + ) + ) + .withServeEventListener( + "recordState", + Parameters.from( + Map.of( + "context", "queue", + "list", Map.of( + "addLast", Map.of( + "id", "{{jsonPath response.body '$.id'}}", + "firstName", "{{jsonPath request.body '$.firstName'}}", + "lastName", "{{jsonPath request.body '$.lastName'}}" + ) + ) + ) + ) + ) + ); + } + + private void createGetStub() throws JsonProcessingException { + wm.stubFor( + get(urlPathMatching(TEST_URL)) + .willReturn( + WireMock.ok() + .withHeader("content-type", "application/json") + .withJsonBody( + mapper.readTree( + mapper.writeValueAsString(Map.of( + "id", "{{state context='queue' list='[0].id'}}", + "firstName", "{{state context='queue' list='[0].firstName'}}", + "lastName", "{{state context='queue' list='[0].lastName'}}" + ) + ) + ) + ) + ) + .withServeEventListener( + "deleteState", + Parameters.from( + Map.of( + "context", "queue", + "list", Map.of("deleteFirst", true) + ) + ) + ) + ); + } +} diff --git a/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionStateExampleTest.java b/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionStateExampleTest.java new file mode 100644 index 0000000..b8f1805 --- /dev/null +++ b/compatibility_test/src/test/java/org/wiremock/extensions/state/compatibility/StateExtensionStateExampleTest.java @@ -0,0 +1,167 @@ +/* + * Copyright (C) 2023 Dirk Bolte + * + * 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 org.wiremock.extensions.state.compatibility; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.common.ConsoleNotifier; +import com.github.tomakehurst.wiremock.extension.Parameters; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.store.Store; +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.http.HttpStatus; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.parallel.Execution; +import org.wiremock.extensions.state.CaffeineStore; +import org.wiremock.extensions.state.StateExtension; + +import java.net.URI; +import java.util.Map; + +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.parallel.ExecutionMode.SAME_THREAD; + +/** + * Sample test for using this extension to record a state in java. + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Execution(SAME_THREAD) +class StateExtensionStateExampleTest { + + private static final String TEST_URL = "/test"; + private static final Store store = new CaffeineStore(); + private static final ObjectMapper mapper = new ObjectMapper(); + + @RegisterExtension + public static WireMockExtension wm = WireMockExtension.newInstance() + .options( + wireMockConfig().dynamicPort().dynamicHttpsPort().templatingEnabled(true).globalTemplating(true) + .extensions(new StateExtension(store)) + .notifier(new ConsoleNotifier(true)) + ) + .build(); + + + @BeforeEach + public void setup() throws JsonProcessingException { + RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); + createGetStub(); + createPostStub(); + } + + @Test + public void testCrud() { + var firstName = RandomStringUtils.randomAlphabetic(5); + var lastName = RandomStringUtils.randomAlphabetic(5); + + var id = given() + .accept(ContentType.JSON) + .body(Map.of( + "firstName", firstName, + "lastName", lastName + ) + ) + .post(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.notNullValue()) + .body("firstName", Matchers.equalTo(firstName)) + .body("lastName", Matchers.equalTo(lastName)) + .extract() + .body() + .jsonPath().get("id"); + + given() + .accept(ContentType.JSON) + .get(assertDoesNotThrow(() -> new URI(wm.getRuntimeInfo().getHttpBaseUrl() + TEST_URL + "/" + id))) + .then() + .statusCode(HttpStatus.SC_OK) + .body("id", Matchers.equalTo(id)) + .body("firstName", Matchers.equalTo(firstName)) + .body("lastName", Matchers.equalTo(lastName)); + } + + + private void createPostStub() throws JsonProcessingException { + wm.stubFor( + post(urlPathMatching(TEST_URL)) + .willReturn( + WireMock.ok() + .withHeader("content-type", "application/json") + .withJsonBody( + mapper.readTree( + mapper.writeValueAsString( + Map.of( + "id", "{{randomValue length=32 type='ALPHANUMERIC' uppercase=false}}", + "firstName", "{{jsonPath request.body '$.firstName'}}", + "lastName", "{{jsonPath request.body '$.lastName'}}" + ) + ) + ) + ) + ) + .withServeEventListener( + "recordState", + Parameters.from( + Map.of( + "context", "{{jsonPath response.body '$.id'}}", + "state", Map.of( + "id", "{{jsonPath response.body '$.id'}}", + "firstName", "{{jsonPath request.body '$.firstName'}}", + "lastName", "{{jsonPath request.body '$.lastName'}}" + ) + ) + ) + ) + ); + } + + private void createGetStub() throws JsonProcessingException { + wm.stubFor( + get(urlPathMatching(TEST_URL + "/[^/]+")) + .andMatching("state-matcher", Parameters.from( + Map.of("hasContext", "{{request.pathSegments.[1]}}")) + ) + .willReturn( + WireMock.ok() + .withHeader("content-type", "application/json") + .withJsonBody( + mapper.readTree( + mapper.writeValueAsString(Map.of( + "id", "{{state context=request.pathSegments.[1] property='id'}}", + "firstName", "{{state context=request.pathSegments.[1] property='firstName'}}", + "lastName", "{{state context=request.pathSegments.[1] property='lastName'}}" + ) + ) + ) + ) + ) + ); + } +} diff --git a/src/main/java/org/wiremock/extensions/state/extensions/DeleteStateEventListener.java b/src/main/java/org/wiremock/extensions/state/extensions/DeleteStateEventListener.java index f5d2bd9..01d43b3 100644 --- a/src/main/java/org/wiremock/extensions/state/extensions/DeleteStateEventListener.java +++ b/src/main/java/org/wiremock/extensions/state/extensions/DeleteStateEventListener.java @@ -28,6 +28,7 @@ import org.wiremock.extensions.state.internal.api.DeleteStateParameters; import org.wiremock.extensions.state.internal.model.ResponseTemplateModel; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -67,10 +68,9 @@ public boolean applyGlobally() { } public void beforeResponseSent(ServeEvent serveEvent, Parameters parameters) { - var model = Map.of( - "request", RequestTemplateModel.from(serveEvent.getRequest()), - "response", ResponseTemplateModel.from(serveEvent.getResponse()) - ); + final Map model = new HashMap<>(); + model.putAll(wireMockServices.getTemplateEngine().buildModelForRequest(serveEvent)); + model.put("response", ResponseTemplateModel.from(serveEvent.getResponse())); var configuration = Json.mapToObject(parameters, DeleteStateParameters.class); new ListenerInstance(serveEvent.getId().toString(), model, configuration).run(); } diff --git a/src/main/java/org/wiremock/extensions/state/extensions/RecordStateEventListener.java b/src/main/java/org/wiremock/extensions/state/extensions/RecordStateEventListener.java index 96aa1f1..af5c692 100644 --- a/src/main/java/org/wiremock/extensions/state/extensions/RecordStateEventListener.java +++ b/src/main/java/org/wiremock/extensions/state/extensions/RecordStateEventListener.java @@ -28,6 +28,7 @@ import org.wiremock.extensions.state.internal.api.RecordStateParameters; import org.wiremock.extensions.state.internal.model.ResponseTemplateModel; +import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; @@ -52,10 +53,9 @@ public RecordStateEventListener(ContextManager contextManager, WireMockServices } public void beforeResponseSent(ServeEvent serveEvent, Parameters parameters) { - var model = Map.of( - "request", RequestTemplateModel.from(serveEvent.getRequest()), - "response", ResponseTemplateModel.from(serveEvent.getResponse()) - ); + final Map model = new HashMap<>(); + model.putAll(wireMockServices.getTemplateEngine().buildModelForRequest(serveEvent)); + model.put("response", ResponseTemplateModel.from(serveEvent.getResponse())); var configuration = Json.mapToObject(parameters, RecordStateParameters.class); new ListenerInstance(serveEvent.getId().toString(), model, configuration).run(); } diff --git a/src/main/java/org/wiremock/extensions/state/extensions/StateRequestMatcher.java b/src/main/java/org/wiremock/extensions/state/extensions/StateRequestMatcher.java index ec5b90c..9fb77ed 100644 --- a/src/main/java/org/wiremock/extensions/state/extensions/StateRequestMatcher.java +++ b/src/main/java/org/wiremock/extensions/state/extensions/StateRequestMatcher.java @@ -97,7 +97,7 @@ public String getName() { @Override public MatchResult match(Request request, Parameters parameters) { - Map model = new HashMap<>(Map.of("request", RequestTemplateModel.from(request))); + var model = wireMockServices.getTemplateEngine().buildModelForRequest(request); return Optional .ofNullable(parameters.getString("hasContext", null)) .map(template -> hasContext(model, parameters, template)) diff --git a/src/test/java/org/wiremock/extensions/state/examples/StateExtensionListExampleTest.java b/src/test/java/org/wiremock/extensions/state/examples/StateExtensionListExampleTest.java index e9f2aa5..950b8d2 100644 --- a/src/test/java/org/wiremock/extensions/state/examples/StateExtensionListExampleTest.java +++ b/src/test/java/org/wiremock/extensions/state/examples/StateExtensionListExampleTest.java @@ -72,8 +72,6 @@ public void setup() throws JsonProcessingException { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); createGetStub(); createPostStub(); - - wm.saveMappings(); } @Test diff --git a/src/test/java/org/wiremock/extensions/state/examples/StateExtensionQueueExampleTest.java b/src/test/java/org/wiremock/extensions/state/examples/StateExtensionQueueExampleTest.java index aed8c97..b3204e3 100644 --- a/src/test/java/org/wiremock/extensions/state/examples/StateExtensionQueueExampleTest.java +++ b/src/test/java/org/wiremock/extensions/state/examples/StateExtensionQueueExampleTest.java @@ -72,8 +72,6 @@ public void setup() throws JsonProcessingException { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); createGetStub(); createPostStub(); - - wm.saveMappings(); } @Test diff --git a/src/test/java/org/wiremock/extensions/state/examples/StateExtensionStateExampleTest.java b/src/test/java/org/wiremock/extensions/state/examples/StateExtensionStateExampleTest.java index f45f51f..b5b9056 100644 --- a/src/test/java/org/wiremock/extensions/state/examples/StateExtensionStateExampleTest.java +++ b/src/test/java/org/wiremock/extensions/state/examples/StateExtensionStateExampleTest.java @@ -73,8 +73,6 @@ public void setup() throws JsonProcessingException { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); createGetStub(); createPostStub(); - - wm.saveMappings(); } @Test diff --git a/src/test/java/org/wiremock/extensions/state/functionality/DeleteStateEventListenerTest.java b/src/test/java/org/wiremock/extensions/state/functionality/DeleteStateEventListenerTest.java index a31c54a..c44c19e 100644 --- a/src/test/java/org/wiremock/extensions/state/functionality/DeleteStateEventListenerTest.java +++ b/src/test/java/org/wiremock/extensions/state/functionality/DeleteStateEventListenerTest.java @@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.extension.Parameters; import io.restassured.http.ContentType; import org.apache.http.HttpStatus; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest;