diff --git a/spring-cloud-contract/2.1.2.RELEASE/css/highlight.css b/spring-cloud-contract/2.1.2.RELEASE/css/highlight.css new file mode 100644 index 00000000..3850f8b9 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/css/manual-multipage.css b/spring-cloud-contract/2.1.2.RELEASE/css/manual-multipage.css new file mode 100644 index 00000000..b790654b --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-contract/2.1.2.RELEASE/css/manual-singlepage.css b/spring-cloud-contract/2.1.2.RELEASE/css/manual-singlepage.css new file mode 100644 index 00000000..303192a8 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-contract/2.1.2.RELEASE/css/manual.css b/spring-cloud-contract/2.1.2.RELEASE/css/manual.css new file mode 100644 index 00000000..20cf07da --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/css/manual.css @@ -0,0 +1,342 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a) > code { + color: #6D180B; +} + +:not(pre) > code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body > *:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1, h2, h3, h4, h5, h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1, h2, h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1, h1 code { + font-size: 32px; +} + +h2, h2 code { + font-size: 24px; +} + +h3, h3 code { + font-size: 20px; +} + +h4, h1 code, h5, h5 code, h6, h6 code { + font-size: 18px; +} + +div.book, div.chapter, div.appendix, div.part, div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage + p, div.titlepage + p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul, ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table, div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting, pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th, table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *, div.note *, div.tip *, div.warning *, div.navheader *, div.navfooter *, div.calloutlist * { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p, div.note p, div.tip p, div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code, div.note code, div.tip code, div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th, .tip th, .warning th { + display: none; +} + +.note tr:first-child td, .tip tr:first-child td, .warning tr:first-child td { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p, div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist > table > tbody > tr > td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important, div.note, div.tip, div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl, dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc > dl > dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc > dl > dd > dl > dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc > dl > dd > dl > dd > dl > dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title > a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title > a:before { + content: "\00A7"; +} + +.title:hover > a, .title > a:hover, .title:hover > a:hover { + visibility: visible; +} + +.title:focus > a, .title > a:focus, .title:focus > a:focus { + outline: 0; +} diff --git a/spring-cloud-contract/2.1.2.RELEASE/ghpages.sh b/spring-cloud-contract/2.1.2.RELEASE/ghpages.sh new file mode 100644 index 00000000..57c5da3a --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/ghpages.sh @@ -0,0 +1,330 @@ +#!/bin/bash -x + +set -e + +# Set default props like MAVEN_PATH, ROOT_FOLDER etc. +function set_default_props() { + # The script should be executed from the root folder + ROOT_FOLDER=`pwd` + echo "Current folder is ${ROOT_FOLDER}" + + if [[ ! -e "${ROOT_FOLDER}/.git" ]]; then + echo "You're not in the root folder of the project!" + exit 1 + fi + + # Prop that will let commit the changes + COMMIT_CHANGES="no" + MAVEN_PATH=${MAVEN_PATH:-} + echo "Path to Maven is [${MAVEN_PATH}]" + REPO_NAME=${PWD##*/} + echo "Repo name is [${REPO_NAME}]" + SPRING_CLOUD_STATIC_REPO=${SPRING_CLOUD_STATIC_REPO:-git@github.com:spring-cloud/spring-cloud-static.git} + echo "Spring Cloud Static repo is [${SPRING_CLOUD_STATIC_REPO}" +} + +# Check if gh-pages exists and docs have been built +function check_if_anything_to_sync() { + git remote set-url --push origin `git config remote.origin.url | sed -e 's/^git:/https:/'` + + if ! (git remote set-branches --add origin gh-pages && git fetch -q); then + echo "No gh-pages, so not syncing" + exit 0 + fi + + if ! [ -d docs/target/generated-docs ] && ! [ "${BUILD}" == "yes" ]; then + echo "No gh-pages sources in docs/target/generated-docs, so not syncing" + exit 0 + fi +} + +function retrieve_current_branch() { + # Code getting the name of the current branch. For master we want to publish as we did until now + # http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch + # If there is a branch already passed will reuse it - otherwise will try to find it + CURRENT_BRANCH=${BRANCH} + if [[ -z "${CURRENT_BRANCH}" ]] ; then + CURRENT_BRANCH=$(git symbolic-ref -q HEAD) + CURRENT_BRANCH=${CURRENT_BRANCH##refs/heads/} + CURRENT_BRANCH=${CURRENT_BRANCH:-HEAD} + fi + echo "Current branch is [${CURRENT_BRANCH}]" + git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script" +} + +# Switches to the provided value of the release version. We always prefix it with `v` +function switch_to_tag() { + git checkout v${VERSION} +} + +# Build the docs if switch is on +function build_docs_if_applicable() { + if [[ "${BUILD}" == "yes" ]] ; then + ./mvnw clean install -P docs -pl docs -DskipTests + fi +} + +# Get the name of the `docs.main` property +# Get whitelisted branches - assumes that a `docs` module is available under `docs` profile +function retrieve_doc_properties() { + MAIN_ADOC_VALUE=$("${MAVEN_PATH}"mvn -q \ + -Dexec.executable="echo" \ + -Dexec.args='${docs.main}' \ + --non-recursive \ + org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + echo "Extracted 'main.adoc' from Maven build [${MAIN_ADOC_VALUE}]" + + + WHITELIST_PROPERTY=${WHITELIST_PROPERTY:-"docs.whitelisted.branches"} + WHITELISTED_BRANCHES_VALUE=$("${MAVEN_PATH}"mvn -q \ + -Dexec.executable="echo" \ + -Dexec.args="\${${WHITELIST_PROPERTY}}" \ + org.codehaus.mojo:exec-maven-plugin:1.3.1:exec \ + -P docs \ + -pl docs) + echo "Extracted '${WHITELIST_PROPERTY}' from Maven build [${WHITELISTED_BRANCHES_VALUE}]" +} + +# Stash any outstanding changes +function stash_changes() { + git diff-index --quiet HEAD && dirty=$? || (echo "Failed to check if the current repo is dirty. Assuming that it is." && dirty="1") + if [ "$dirty" != "0" ]; then git stash; fi +} + +# Switch to gh-pages branch to sync it with current branch +function add_docs_from_target() { + local DESTINATION_REPO_FOLDER + if [[ -z "${DESTINATION}" && -z "${CLONE}" ]] ; then + DESTINATION_REPO_FOLDER=${ROOT_FOLDER} + elif [[ "${CLONE}" == "yes" ]]; then + mkdir -p ${ROOT_FOLDER}/target + local clonedStatic=${ROOT_FOLDER}/target/spring-cloud-static + if [[ ! -e "${clonedStatic}/.git" ]]; then + echo "Cloning Spring Cloud Static to target" + git clone ${SPRING_CLOUD_STATIC_REPO} ${clonedStatic} && git checkout gh-pages + else + echo "Spring Cloud Static already cloned - will pull changes" + cd ${clonedStatic} && git checkout gh-pages && git pull origin gh-pages + fi + DESTINATION_REPO_FOLDER=${clonedStatic}/${REPO_NAME} + mkdir -p ${DESTINATION_REPO_FOLDER} + else + if [[ ! -e "${DESTINATION}/.git" ]]; then + echo "[${DESTINATION}] is not a git repository" + exit 1 + fi + DESTINATION_REPO_FOLDER=${DESTINATION}/${REPO_NAME} + mkdir -p ${DESTINATION_REPO_FOLDER} + echo "Destination was provided [${DESTINATION}]" + fi + cd ${DESTINATION_REPO_FOLDER} + git checkout gh-pages + git pull origin gh-pages + + # Add git branches + ################################################################### + if [[ -z "${VERSION}" ]] ; then + copy_docs_for_current_version + else + copy_docs_for_provided_version + fi + commit_changes_if_applicable +} + + +# Copies the docs by using the retrieved properties from Maven build +function copy_docs_for_current_version() { + if [[ "${CURRENT_BRANCH}" == "master" ]] ; then + echo -e "Current branch is master - will copy the current docs only to the root folder" + for f in docs/target/generated-docs/*; do + file=${f#docs/target/generated-docs/*} + if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then + # Not ignored... + cp -rf $f ${ROOT_FOLDER}/ + git add -A ${ROOT_FOLDER}/$file + fi + done + COMMIT_CHANGES="yes" + else + echo -e "Current branch is [${CURRENT_BRANCH}]" + # http://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin + if [[ ",${WHITELISTED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then + mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH} + echo -e "Branch [${CURRENT_BRANCH}] is whitelisted! Will copy the current docs to the [${CURRENT_BRANCH}] folder" + for f in docs/target/generated-docs/*; do + file=${f#docs/target/generated-docs/*} + if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then + # Not ignored... + # We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html + if [[ "${file}" == "${MAIN_ADOC_VALUE}.html" ]] ; then + # We don't want to copy the spring-cloud-sleuth.html + # we want it to be converted to index.html + cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html + git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html + else + cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH} + git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/$file + fi + fi + done + COMMIT_CHANGES="yes" + else + echo -e "Branch [${CURRENT_BRANCH}] is not on the white list! Check out the Maven [${WHITELIST_PROPERTY}] property in + [docs] module available under [docs] profile. Won't commit any changes to gh-pages for this branch." + fi + fi +} + +# Copies the docs by using the explicitly provided version +function copy_docs_for_provided_version() { + local FOLDER=${DESTINATION_REPO_FOLDER}/${VERSION} + mkdir -p ${FOLDER} + echo -e "Current tag is [v${VERSION}] Will copy the current docs to the [${FOLDER}] folder" + for f in ${ROOT_FOLDER}/docs/target/generated-docs/*; do + file=${f#${ROOT_FOLDER}/docs/target/generated-docs/*} + copy_docs_for_branch ${file} ${FOLDER} + done + COMMIT_CHANGES="yes" + CURRENT_BRANCH="v${VERSION}" +} + +# Copies the docs from target to the provided destination +# Params: +# $1 - file from target +# $2 - destination to which copy the files +function copy_docs_for_branch() { + local file=$1 + local destination=$2 + if ! git ls-files -i -o --exclude-standard --directory | grep -q ^${file}$; then + # Not ignored... + # We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html + if [[ ("${file}" == "${MAIN_ADOC_VALUE}.html") || ("${file}" == "${REPO_NAME}.html") ]] ; then + # We don't want to copy the spring-cloud-sleuth.html + # we want it to be converted to index.html + cp -rf $f ${destination}/index.html + git add -A ${destination}/index.html + else + cp -rf $f ${destination} + git add -A ${destination}/$file + fi + fi +} + +function commit_changes_if_applicable() { + if [[ "${COMMIT_CHANGES}" == "yes" ]] ; then + COMMIT_SUCCESSFUL="no" + git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes" + + # Uncomment the following push if you want to auto push to + # the gh-pages branch whenever you commit to master locally. + # This is a little extreme. Use with care! + ################################################################### + if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then + git push origin gh-pages + fi + fi +} + +# Switch back to the previous branch and exit block +function checkout_previous_branch() { + # If -version was provided we need to come back to root project + cd ${ROOT_FOLDER} + git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script" + if [ "$dirty" != "0" ]; then git stash pop; fi + exit 0 +} + +# Assert if properties have been properly passed +function assert_properties() { +echo "VERSION [${VERSION}], DESTINATION [${DESTINATION}], CLONE [${CLONE}]" +if [[ "${VERSION}" != "" && (-z "${DESTINATION}" && -z "${CLONE}") ]] ; then echo "Version was set but destination / clone was not!"; exit 1;fi +if [[ ("${DESTINATION}" != "" && "${CLONE}" != "") && -z "${VERSION}" ]] ; then echo "Destination / clone was set but version was not!"; exit 1;fi +if [[ "${DESTINATION}" != "" && "${CLONE}" == "yes" ]] ; then echo "Destination and clone was set. Pick one!"; exit 1;fi +} + +# Prints the usage +function print_usage() { +cat </` +- if the destination switch is passed (-d) then the script will check if the provided dir is a git repo and then will + switch to gh-pages of that repo and copy the generated docs to `docs//` + +USAGE: + +You can use the following options: + +-v|--version - the script will apply the whole procedure for a particular library version +-d|--destination - the root of destination folder where the docs should be copied. You have to use the full path. + E.g. point to spring-cloud-static folder. Can't be used with (-c) +-b|--build - will run the standard build process after checking out the branch +-c|--clone - will automatically clone the spring-cloud-static repo instead of providing the destination. + Obviously can't be used with (-d) + +EOF +} + + +# ========================================== +# ____ ____ _____ _____ _____ _______ +# / ____|/ ____| __ \|_ _| __ \__ __| +# | (___ | | | |__) | | | | |__) | | | +# \___ \| | | _ / | | | ___/ | | +# ____) | |____| | \ \ _| |_| | | | +# |_____/ \_____|_| \_\_____|_| |_| +# +# ========================================== + +while [[ $# > 0 ]] +do +key="$1" +case ${key} in + -v|--version) + VERSION="$2" + shift # past argument + ;; + -d|--destination) + DESTINATION="$2" + shift # past argument + ;; + -b|--build) + BUILD="yes" + ;; + -c|--clone) + CLONE="yes" + ;; + -h|--help) + print_usage + exit 0 + ;; + *) + echo "Invalid option: [$1]" + print_usage + exit 1 + ;; +esac +shift # past argument or value +done + +assert_properties +set_default_props +check_if_anything_to_sync +if [[ -z "${VERSION}" ]] ; then + retrieve_current_branch +else + switch_to_tag +fi +build_docs_if_applicable +retrieve_doc_properties +stash_changes +add_docs_from_target +checkout_previous_branch \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/Deps.png b/spring-cloud-contract/2.1.2.RELEASE/images/Deps.png new file mode 100644 index 00000000..14268143 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/Deps.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/Stubs1.png b/spring-cloud-contract/2.1.2.RELEASE/images/Stubs1.png new file mode 100644 index 00000000..ebadfdb9 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/Stubs1.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/Stubs2.png b/spring-cloud-contract/2.1.2.RELEASE/images/Stubs2.png new file mode 100644 index 00000000..e4bad249 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/Stubs2.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/background.png b/spring-cloud-contract/2.1.2.RELEASE/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/background.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/callouts/1.png b/spring-cloud-contract/2.1.2.RELEASE/images/callouts/1.png new file mode 100644 index 00000000..7d473430 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/callouts/1.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/callouts/2.png b/spring-cloud-contract/2.1.2.RELEASE/images/callouts/2.png new file mode 100644 index 00000000..5d09341b Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/callouts/2.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/callouts/3.png b/spring-cloud-contract/2.1.2.RELEASE/images/callouts/3.png new file mode 100644 index 00000000..ef7b7004 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/callouts/3.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/caution.png b/spring-cloud-contract/2.1.2.RELEASE/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/caution.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/important.png b/spring-cloud-contract/2.1.2.RELEASE/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/important.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/logo.png b/spring-cloud-contract/2.1.2.RELEASE/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/logo.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/note.png b/spring-cloud-contract/2.1.2.RELEASE/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/note.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/tip.png b/spring-cloud-contract/2.1.2.RELEASE/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/tip.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/images/warning.png b/spring-cloud-contract/2.1.2.RELEASE/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/images/warning.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/index.html b/spring-cloud-contract/2.1.2.RELEASE/index.html new file mode 100644 index 00000000..b7941c6b --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/index.html @@ -0,0 +1,117 @@ + + + + + + + +spring-cloud-contract + + + + + + + + +
+
+
+
+

2.1.2.RELEASE

+
+
+
+
+

Pick The Documentation Option

+
+
+ +
+
+
+
+ + + + + \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/css/highlight.css b/spring-cloud-contract/2.1.2.RELEASE/multi/css/highlight.css new file mode 100644 index 00000000..3850f8b9 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual-multipage.css b/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual-multipage.css new file mode 100644 index 00000000..b790654b --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual-singlepage.css b/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual-singlepage.css new file mode 100644 index 00000000..303192a8 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual.css b/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual.css new file mode 100644 index 00000000..20cf07da --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/css/manual.css @@ -0,0 +1,342 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a) > code { + color: #6D180B; +} + +:not(pre) > code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body > *:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1, h2, h3, h4, h5, h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1, h2, h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1, h1 code { + font-size: 32px; +} + +h2, h2 code { + font-size: 24px; +} + +h3, h3 code { + font-size: 20px; +} + +h4, h1 code, h5, h5 code, h6, h6 code { + font-size: 18px; +} + +div.book, div.chapter, div.appendix, div.part, div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage + p, div.titlepage + p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul, ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table, div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting, pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th, table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *, div.note *, div.tip *, div.warning *, div.navheader *, div.navfooter *, div.calloutlist * { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p, div.note p, div.tip p, div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code, div.note code, div.tip code, div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th, .tip th, .warning th { + display: none; +} + +.note tr:first-child td, .tip tr:first-child td, .warning tr:first-child td { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p, div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist > table > tbody > tr > td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important, div.note, div.tip, div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl, dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc > dl > dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc > dl > dd > dl > dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc > dl > dd > dl > dd > dl > dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title > a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title > a:before { + content: "\00A7"; +} + +.title:hover > a, .title > a:hover, .title:hover > a:hover { + visibility: visible; +} + +.title:focus > a, .title > a:focus, .title:focus > a:focus { + outline: 0; +} diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/background.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/background.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/1.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/1.png new file mode 100644 index 00000000..7d473430 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/1.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/2.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/2.png new file mode 100644 index 00000000..5d09341b Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/2.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/3.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/3.png new file mode 100644 index 00000000..ef7b7004 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/callouts/3.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/caution.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/caution.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/important.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/important.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/logo.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/logo.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/note.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/note.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/tip.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/tip.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/images/warning.png b/spring-cloud-contract/2.1.2.RELEASE/multi/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/multi/images/warning.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__customization.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__customization.html new file mode 100644 index 00000000..3bcaae3d --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__customization.html @@ -0,0 +1,217 @@ + + + 9. Customization

9. Customization

[Important]Important

This section is valid only for Groovy DSL

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section.

9.1 Extending the DSL

You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of:

  • Creating a JAR with reusable classes.
  • Referencing of these classes in the DSLs.

You can find the full example +here.

9.1.1 Common JAR

The following examples show three classes that can be reused in the DSLs.

PatternUtils contains functions used by both the consumer and the producer.

package com.example;
+
+import java.util.regex.Pattern;
+
+/**
+ * If you want to use {@link Pattern} directly in your tests
+ * then you can create a class resembling this one. It can
+ * contain all the {@link Pattern} you want to use in the DSL.
+ *
+ * <pre>
+ * {@code
+ * request {
+ *     body(
+ *         [ age: $(c(PatternUtils.oldEnough()))]
+ *     )
+ * }
+ * </pre>
+ *
+ * Notice that we're using both {@code $()} for dynamic values
+ * and {@code c()} for the consumer side.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class PatternUtils {
+
+	public static String tooYoung() {
+		//remove::start[]
+		return "[0-1][0-9]";
+		//remove::end[return]
+	}
+
+	public static Pattern oldEnough() {
+		//remove::start[]
+		return Pattern.compile("[2-9][0-9]");
+		//remove::end[return]
+	}
+
+	/**
+	 * Makes little sense but it's just an example ;)
+	 */
+	public static Pattern ok() {
+		//remove::start[]
+		return Pattern.compile("OK");
+		//remove::end[return]
+	}
+}
+//end::impl[]

ConsumerUtils contains functions used by the consumer.

package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the consumer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you can have a regular expression.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you have to have a concrete value.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ConsumerUtils {
+	/**
+	 * Consumer side property. By using the {@link ClientDslProperty}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * request {
+	 *     body(
+	 *         [ age: $(ConsumerUtils.oldEnough())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 *
+	 * @author Marcin Grzejszczak
+	 */
+	public static ClientDslProperty oldEnough() {
+		//remove::start[]
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ClientDslProperty(PatternUtils.oldEnough(), 40);
+		//remove::end[return]
+	}
+
+}
+//end::impl[]

ProducerUtils contains functions used by the producer.

package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the producer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you have to have a concrete value.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you can have a regular expression.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ProducerUtils {
+
+	/**
+	 * Producer side property. By using the {@link ProducerUtils}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * response {
+	 *     body(
+	 *         [ status: $(ProducerUtils.ok())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 */
+	public static ServerDslProperty ok() {
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ServerDslProperty( PatternUtils.ok(), "OK");
+	}
+}
+//end::impl[]

9.1.2 Adding the Dependency to the Project

In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

9.1.3 Test the Dependency in the Project’s Dependencies

First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency:

Maven.  +

<dependency>
+	<groupId>com.example</groupId>
+	<artifactId>beer-common</artifactId>
+	<version>${project.version}</version>
+	<scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")

+

9.1.4 Test a Dependency in the Plugin’s Dependencies

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example:

Maven.  +

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example</packageWithBaseClasses>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*intoxication.*</contractPackageRegex>
+				<baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>com.example</groupId>
+			<artifactId>beer-common</artifactId>
+			<version>${project.version}</version>
+			<scope>compile</scope>
+		</dependency>
+	</dependencies>
+</plugin>

+

Gradle.  +

classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"

+

9.1.5 Referencing classes in DSLs

You can now reference your classes in your DSL, as shown in the following example:

package contracts.beer.rest
+
+import com.example.ConsumerUtils
+import com.example.ProducerUtils
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	description("""
+Represents a successful scenario of getting a beer
+
+```
+given:
+	client is old enough
+when:
+	he applies for a beer
+then:
+	we'll grant him the beer
+```
+
+""")
+	request {
+		method 'POST'
+		url '/check'
+		body(
+				age: $(ConsumerUtils.oldEnough())
+		)
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status 200
+		body("""
+			{
+				"status": "${value(ProducerUtils.ok())}"
+			}
+			""")
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
[Important]Important

You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones.

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__links.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__links.html new file mode 100644 index 00000000..fb9dc1b2 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__links.html @@ -0,0 +1,6 @@ + + + 13. Links \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__migrations.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__migrations.html new file mode 100644 index 00000000..cb308e5a --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__migrations.html @@ -0,0 +1,96 @@ + + + 12. Migrations

12. Migrations

[Tip]Tip

For up to date migration guides please visit +the project’s wiki page.

This section covers migrating from one version of Spring Cloud Contract Verifier to the +next version. It covers the following versions upgrade paths:

12.1 1.0.x → 1.1.x

This section covers upgrading from version 1.0 to version 1.1.

12.1.1 New structure of generated stubs

In 1.1.x we have introduced a change to the structure of generated stubs. If you have +been using the @AutoConfigureWireMock notation to use the stubs from the classpath, +it no longer works. The following example shows how the @AutoConfigureWireMock notation +used to work:

@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)

You must either change the location of the stubs to: +classpath:…​/META-INF/groupId/artifactId/version/mappings or use the new +classpath-based @AutoConfigureStubRunner, as shown in the following example:

@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)

If you do not want to use @AutoConfigureStubRunner and you want to remain with the old +structure, set your plugin tasks accordingly. The following example would work for the +structure presented in the previous snippet.

Maven.  +

<!-- start of pom.xml -->
+
+<properties>
+    <!-- we don't want the verifier to do a jar for us -->
+    <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+</properties>
+
+<!-- ... -->
+
+<!-- You need to set up the assembly plugin -->
+<build>
+    <plugins>
+        <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-assembly-plugin</artifactId>
+            <executions>
+                <execution>
+                    <id>stub</id>
+                    <phase>prepare-package</phase>
+                    <goals>
+                        <goal>single</goal>
+                    </goals>
+                    <inherited>false</inherited>
+                    <configuration>
+                        <attach>true</attach>
+                        <descriptor>${basedir}/src/assembly/stub.xml</descriptor>
+                    </configuration>
+                </execution>
+            </executions>
+        </plugin>
+    </plugins>
+</build>
+<!-- end of pom.xml -->
+
+<!-- start of stub.xml-->
+
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>customer-stubs/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>customer-stubs/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+<!-- end of stub.xml-->

+

Gradle.  +

task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
+//    Preserve directory structure from 1.0.X of spring-cloud-contract
+    from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
+    into "${project.buildDir}/resources/main/customer-stubs"
+}

+

12.2 1.1.x → 1.2.x

This section covers upgrading from version 1.1 to version 1.2.

12.2.1 Custom HttpServerStub

HttpServerStub includes a method that was not in version 1.1. The method is +String registeredMappings() If you have classes that implement HttpServerStub, you +now have to implement the registeredMappings() method. It should return a String +representing all mappings available in a single HttpServerStub.

See issue 355 for more +detail.

12.2.2 New packages for generated tests

The flow for setting the generated tests package name will look like this:

  • Set basePackageForTests
  • If basePackageForTests was not set, pick the package from baseClassForTests
  • If baseClassForTests was not set, pick packageWithBaseClasses
  • If nothing got set, pick the default value: +org.springframework.cloud.contract.verifier.tests

See issue 260 for more +detail.

12.2.3 New Methods in TemplateProcessor

In order to add support for fromRequest.path, the following methods had to be added to the +TemplateProcessor interface:

  • path()
  • path(int index)

See issue 388 for more +detail.

12.2.4 RestAssured 3.0

Rest Assured, used in the generated test classes, got bumped to 3.0. If +you manually set versions of Spring Cloud Contract and the release train +you might see the following exception:

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
+[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist

This exception will occur due to the fact that the tests got generated with +an old version of plugin and at test execution time you have an incompatible +version of the release train (and vice versa).

Done via issue 267

12.3 1.2.x → 2.0.x

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract.html new file mode 100644 index 00000000..548bc741 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract.html @@ -0,0 +1,7 @@ + + + 1. Spring Cloud Contract

1. Spring Cloud Contract

You need confidence when pushing new features to a new application or service in a +distributed system. This project provides support for Consumer Driven Contracts and +service schemas in Spring applications (for both HTTP and message-based interactions), +covering a range of options for writing tests, publishing them as assets, and asserting +that a contract is kept by producers and consumers.

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_faq.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_faq.html new file mode 100644 index 00000000..a5f35887 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_faq.html @@ -0,0 +1,702 @@ + + + 3. Spring Cloud Contract FAQ

3. Spring Cloud Contract FAQ

3.1 Why use Spring Cloud Contract Verifier and not X ?

For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating +software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

  • Possibility to do CDC with messaging
  • Clear and easy to use, statically typed DSL
  • Possibility to copy paste your current JSON file to the contract and only edit its elements
  • Automatic generation of tests from the defined Contract
  • Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory
  • Spring Cloud integration - no discovery service is needed for integration tests
  • Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality
  • Via Docker adds support for any language & framework used

3.2 I don’t want to write a contract in Groovy!

No problem. You can write a contract in YAML!

3.3 What is this value(consumer(), producer()) ?

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. +What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. +Imagine the following JSON request

{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}

and JSON response

{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the +database) by changing the clock in the system or providing stub implementations of data providers. The same is related +to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system +will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned +JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words +you would like the stub to work like this:

{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "foo"
+}

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks +much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. +So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the +producer’s backend can work on. Such a JSON would be a valid one:

{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to +contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d +have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side +what you might want is the following response:

{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "bar"
+}

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? +In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both +sides of the communication. You can pass the values:

Either via the value method

value(consumer(...), producer(...))
+value(stub(...), test(...))
+value(client(...), server(...))

or using the $() method

$(consumer(...), producer(...))
+$(stub(...), test(...))
+$(client(...), server(...))

You can read more about this in the Chapter 8, Contract DSL section.

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). +Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

[Tip]Tip

If on one side you have passed the regular expression and you haven’t passed the other, then the +other side will get auto-generated.

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression +for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

org.springframework.cloud.contract.spec.Contract.make {
+				request {
+					method 'GET'
+					url '/someUrl'
+					body([
+					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "foo"
+					])
+				}
+			response {
+				status OK()
+				body([
+					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "bar"
+					])
+			}
+}
[Important]Important

Please read the Groovy docs related to JSON to understand how to +properly structure the request / response bodies.

3.4 How to do Stubs versioning?

3.4.1 API Versioning

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are +different approaches.

  • use Hypermedia, links and do not version your API by any means
  • pass versions through headers / urls

I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +business value should be picked.

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. +You can create a subfolder for every version or append it to the contract name - whatever suits you more.

3.4.2 JAR versioning

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of +the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version +looks like this (it got built on the 20.10.2016 at 20:15:21) :

1.0.0.20161020-201521-RELEASE

In that case your generated stub jar will look like this.

1.0.0.20161020-201521-RELEASE-stubs.jar

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the + latest version of the stubs. You can do that by passing the + sign. Example

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar +version. Example for 2.1.1.

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})

3.4.3 Dev or prod stubs

You can manipulate the classifier to run the tests against current development version of the stubs of other services + or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier + once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

Example of tests using development version of stubs

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})

Example of tests using production version of stubs

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})

You can pass those values also via properties from your deployment pipeline.

3.5 Common repo with contracts

Another way of storing contracts other than having them with the producer is keeping them in a common place. +It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep +contracts in a single place then you, as a producer, will know how many consumers you have and which +consumer you will break with your local changes.

3.5.1 Repo structure

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, +client2, client3. Then in the repository with common contracts you would have the following setup +(which you can checkout here):

├── com
+│   └── example
+│       └── server
+│           ├── client1
+│           │   └── expectation.groovy
+│           ├── client2
+│           │   └── expectation.groovy
+│           ├── client3
+│           │   └── expectation.groovy
+│           └── pom.xml
+├── mvnw
+├── mvnw.cmd
+├── pom.xml
+└── src
+    └── assembly
+        └── contracts.xml

As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have +expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL +contract files as described throughout this documentation. This repository has to produce a JAR file that maps +one to one to the contents of the repo.

Example of a pom.xml inside the server folder.

<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example</groupId>
+	<artifactId>server</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Server Stubs</name>
+	<description>POM used to install locally stubs for consumer side</description>
+
+	<parent>
+		<groupId>org.springframework.boot</groupId>
+		<artifactId>spring-boot-starter-parent</artifactId>
+		<version>2.1.3.RELEASE</version>
+		<relativePath/>
+	</parent>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+		<java.version>1.8</java.version>
+		<spring-cloud-contract.version>2.1.2.BUILD-SNAPSHOT</spring-cloud-contract.version>
+		<spring-cloud-release.version>Greenwich.BUILD-SNAPSHOT
+		</spring-cloud-release.version>
+		<excludeBuildFolders>true</excludeBuildFolders>
+	</properties>
+
+	<dependencyManagement>
+		<dependencies>
+			<dependency>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-dependencies</artifactId>
+				<version>${spring-cloud-release.version}</version>
+				<type>pom</type>
+				<scope>import</scope>
+			</dependency>
+		</dependencies>
+	</dependencyManagement>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+				<version>${spring-cloud-contract.version}</version>
+				<extensions>true</extensions>
+				<configuration>
+					<!-- By default it would search under src/test/resources/ -->
+					<contractsDirectory>${project.basedir}</contractsDirectory>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+	<repositories>
+		<repository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+	</repositories>
+	<pluginRepositories>
+		<pluginRepository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+	</pluginRepositories>
+
+</project>

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install + stubs of the producer project.

The pom.xml in the root folder can look like this:

<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example.standalone</groupId>
+	<artifactId>contracts</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Contracts</name>
+	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
+		producers to generate tests and stubs
+	</description>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+	</properties>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<executions>
+					<execution>
+						<id>contracts</id>
+						<phase>prepare-package</phase>
+						<goals>
+							<goal>single</goal>
+						</goals>
+						<configuration>
+							<attach>true</attach>
+							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
+							<!-- If you want an explicit classifier remove the following line -->
+							<appendAssemblyId>false</appendAssemblyId>
+						</configuration>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>project</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.basedir}</directory>
+			<outputDirectory>/</outputDirectory>
+			<useDefaultExcludes>true</useDefaultExcludes>
+			<excludes>
+				<exclude>**/${project.build.directory}/**</exclude>
+				<exclude>mvnw</exclude>
+				<exclude>mvnw.cmd</exclude>
+				<exclude>.mvn/**</exclude>
+				<exclude>src/**</exclude>
+			</excludes>
+		</fileSet>
+	</fileSets>
+</assembly>

3.5.2 Workflow

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference + is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on + common contracts in a common repository.

3.5.3 Consumer

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the +consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) +and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

[Tip]Tip

You need to have Maven installed locally

3.5.4 Producer

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency +of the JAR containing the contracts:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<contractsMode>REMOTE</contractsMode>
+		<contractsRepositoryUrl>
+			https://link/to/your/nexus/or/artifactory/or/sth
+		</contractsRepositoryUrl>
+		<contractDependency>
+			<groupId>com.example.standalone</groupId>
+			<artifactId>contracts</artifactId>
+		</contractDependency>
+	</configuration>
+</plugin>

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from http://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the +tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken +when some incompatible changes are done.

The rest of the flow looks the same.

3.5.5 How can I define messaging contracts per topic not per producer?

To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, +we could create the structure when the rest contracts would be placed in a folder per producer and messaging +contracts in the folder per topic.

For Maven Project

To make it possible to work on the producer side we should specify an inclusion pattern for +filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin +allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid.

<plugin>
+   <groupId>org.springframework.cloud</groupId>
+   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+   <version>${spring-cloud-contract.version}</version>
+   <configuration>
+      <contractsMode>REMOTE</contractsMode>
+      <contractsRepositoryUrl>http://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
+      <contractDependency>
+         <groupId>com.example</groupId>
+         <artifactId>common-repo-with-contracts</artifactId>
+         <version>+</version>
+      </contractDependency>
+      <contractsPath>/</contractsPath>
+      <baseClassMappings>
+         <baseClassMapping>
+            <contractPackageRegex>.*messaging.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
+         </baseClassMapping>
+         <baseClassMapping>
+            <contractPackageRegex>.*rest.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
+         </baseClassMapping>
+      </baseClassMappings>
+      <includedFiles>
+         <includedFile>**/${project.artifactId}/**</includedFile>
+         <includedFile>**/${first-topic}/**</includedFile>
+         <includedFile>**/${second-topic}/**</includedFile>
+      </includedFiles>
+   </configuration>
+</plugin>

For Gradle Project

  • Add a custom configuration for the common-repo dependency:
ext {
+    conractsGroupId = "com.example"
+    contractsArtifactId = "common-repo"
+    contractsVersion = "1.2.3"
+}
+
+configurations {
+    contracts {
+        transitive = false
+    }
+}
  • Add the common-repo dependency to your classpath:
dependencies {
+    contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+    testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+}
  • Download the dependency to an appropriate folder:
task getContracts(type: Copy) {
+    from configurations.contracts
+    into new File(project.buildDir, "downloadedContracts")
+}
  • Unzip JAR:
task unzipContracts(type: Copy) {
+    def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
+    def outputDir = file("${buildDir}/unpackedContracts")
+
+    from zipTree(zipFile)
+    into outputDir
+}
  • Cleanup unused contracts:
task deleteUnwantedContracts(type: Delete) {
+    delete fileTree(dir: "${buildDir}/unpackedContracts",
+        include: "**/*",
+        excludes: [
+            "**/${project.name}/**"",
+            "**/${first-topic}/**",
+            "**/${second-topic}/**"])
+}
  • Create task dependencies:
unzipContracts.dependsOn("getContracts")
+deleteUnwantedContracts.dependsOn("unzipContracts")
+build.dependsOn("deleteUnwantedContracts")
  • Configure plugin by specifying the directory containing contracts using contractsDslDir property
contracts {
+    contractsDslDir = new File("${buildDir}/unpackedContracts")
+}

3.6 Do I need a Binary Storage? Can’t I use Git?

In the polyglot world, there are languages that don’t use binary storages like +Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide +mechanisms to store contracts and stubs in a SCM repository. Currently the +only supported SCM is Git.

The repository would have to the following setup +(which you can checkout here):

.
+└── META-INF
+    └── com.example
+        └── beer-api-producer-git
+            └── 0.0.1-SNAPSHOT
+                ├── contracts
+                │   └── beer-api-consumer
+                │       ├── messaging
+                │       │   ├── shouldSendAcceptedVerification.groovy
+                │       │   └── shouldSendRejectedVerification.groovy
+                │       └── rest
+                │           ├── shouldGrantABeerIfOldEnough.groovy
+                │           └── shouldRejectABeerIfTooYoung.groovy
+                └── mappings
+                    └── beer-api-consumer
+                        └── rest
+                            ├── shouldGrantABeerIfOldEnough.json
+                            └── shouldRejectABeerIfTooYoung.json

Under META-INF folder:

  • we group applications via groupId (e.g. com.example)
  • then each application is represented via the artifactId (e.g. beer-api-producer-git)
  • next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning)

    • + or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:

      • if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT
      • if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE
      • if you have a version called latest or + we will pick that folder
    • release - to find the latest release version of your stubs. That means:

      • if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE
      • if you have a version called release we will pick that folder
  • finally, there are two folders:

    • contracts - the good practice is to store the contracts required by each +consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you +can use the stubs-per-consumer feature. Further directory structure is arbitrary.
    • mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push +the stub server mappings. On the consumer side, Stub Runner will scan this folder +to start stub servers with stub definitions. The folder structure will be a copy +of the one created in the contracts subfolder.

3.6.1 Protocol convention

In order to control the type and location of the source of contracts (whether it’s +a binary storage or an SCM repository), you can use the protocol in the URL of +the repository. Spring Cloud Contract iterates over registered protocol resolvers +and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).

For the SCM functionality, currently, we support the Git repository. To use it, +in the property, where the repository URL needs to be placed you just have to prefix +the connection URL with git://. Here you can find a couple of examples:

git://file:///foo/bar
+git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git

3.6.2 Producer

For the producer, to use the SCM approach, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the SCM implementation via the URL that contains +the git:// protocol.

[Important]Important

You have to manually add the pushStubsToScm +goal in Maven or execute (bind) the pushStubsToScm task in +Gradle. We don’t push stubs to origin of your git +repository out of the box.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>

+

Gradle.  +

contracts {
+	// We want to pick contracts from a Git repository
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:${project.version}"
+	}
+	/*
+	We reuse the contract dependency section to set up the path
+	to the folder that contains the contract definitions. In our case the
+	path will be /groupId/artifactId/version/contracts
+	 */
+	contractRepository {
+		repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publish.dependsOn("publishStubsToScm")

+

With such a setup:

  • Git project will be cloned to a temporary directory
  • The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder +to find contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/contracts
  • Tests will be generated from the contracts
  • Stubs will be created from the contracts
  • Once the tests pass, the stubs will be committed in the cloned repository
  • Finally, a push will be done to that repo’s origin

3.6.3 Producer with contracts stored locally

Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.

Maven.  +

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<!-- In the default configuration, we want to use the contracts stored locally -->
+	<configuration>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*messaging.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerMessagingBase</baseClassFQN>
+			</baseClassMapping>
+			<baseClassMapping>
+				<contractPackageRegex>.*rest.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerRestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+		<basePackageForTests>com.example</basePackageForTests>
+	</configuration>
+	<executions>
+		<execution>
+			<phase>package</phase>
+			<goals>
+				<!-- By default we will not push the stubs back to SCM,
+				you have to explicitly add it as a goal -->
+				<goal>pushStubsToScm</goal>
+			</goals>
+			<configuration>
+				<!-- We want to pick contracts from a Git repository -->
+				<contractsRepositoryUrl>git://file://${env.ROOT}/target/contract_empty_git/
+				</contractsRepositoryUrl>
+				<!-- Example of URL via git protocol -->
+				<!--<contractsRepositoryUrl>git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- Example of URL via http protocol -->
+				<!--<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- We reuse the contract dependency section to set up the path
+				to the folder that contains the contract definitions. In our case the
+				path will be /groupId/artifactId/version/contracts -->
+				<contractDependency>
+					<groupId>${project.groupId}</groupId>
+					<artifactId>${project.artifactId}</artifactId>
+					<version>${project.version}</version>
+				</contractDependency>
+				<!-- The mode can't be classpath -->
+				<contractsMode>LOCAL</contractsMode>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>

+

Gradle.  +

contracts {
+		// Base package for generated tests
+	basePackageForTests = "com.example"
+	baseClassMappings {
+		baseClassMapping(".*messaging.*", "com.example.BeerMessagingBase")
+		baseClassMapping(".*rest.*", "com.example.BeerRestBase")
+	}
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publishStubsToScm {
+	// We want to modify the default set up of the plugin when publish stubs to scm is called
+	customize {
+		// We want to pick contracts from a Git repository
+		contractDependency {
+			stringNotation = "${project.group}:${project.name}:${project.version}"
+		}
+		/*
+		We reuse the contract dependency section to set up the path
+		to the folder that contains the contract definitions. In our case the
+		path will be /groupId/artifactId/version/contracts
+		 */
+		contractRepository {
+			repositoryUrl = "git://file://${System.getenv("ROOT")}/target/contract_empty_git/"
+		}
+		// The mode can't be classpath
+		contractsMode = "LOCAL"
+	}
+}
+
+publish.dependsOn("publishStubsToScm")
+publishToMavenLocal.dependsOn("publishStubsToScm")

+

With such a setup:

  • Contracts from the default src/test/resources/contracts directory will be picked
  • Tests will be generated from the contracts
  • Stubs will be created from the contracts
  • Once the tests pass

    • Git project will be cloned to a temporary directory
    • The stubs and contracts will be committed in the cloned repository
  • Finally, a push will be done to that repo’s origin

Keeping contracts with the producer and stubs in an external repository

It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. +This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to +use an artifact repository for storing the stubs.

In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set +contractsRepositoryUrl to the repository where you want to keep the stubs.

3.6.4 Consumer

On the consumer side when passing the repositoryRoot parameter, +either from the @AutoConfigureStubRunner annotation, the +JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the +SCM repository, prefixed with the protocol. For example

@AutoConfigureStubRunner(
+    stubsMode="REMOTE",
+    repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
+    ids="com.example:bookstore:0.0.1.RELEASE"
+)

With such a setup:

  • Git project will be cloned to a temporary directory
  • The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder +to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/
  • Stub servers will be started and fed with mappings
  • Messaging definitions will be read and used in the messaging tests

3.7 Can I use the Pact Broker?

When using Pact you can use the Pact Broker +to store and share Pact definitions. Starting from Spring Cloud Contract +2.0.0 one can fetch Pact files from the Pact Broker to generate +tests and stubs.

As a prerequisite the Pact Converter and Pact Stub Downloader +are required. You have to add them via the spring-cloud-contract-pact dependency. +You can read more about it in the Section 10.1.1, “Pact Converter” section.

[Important]Important

Pact follows the Consumer Contract convention. That means +that the Consumer creates the Pact definitions first, then +shares the files with the Producer. Those expectations are generated +from the Consumer’s code and can break the Producer if the expectations +are not met.

3.7.1 Pact Consumer

The consumer uses Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. An example of such +setup can be found here.

3.7.2 Producer

For the producer, to use the Pact files from the Pact Broker, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the Pact implementation via the URL that contains +the pact:// protocol. It’s enough to pass the URL to the +Pact Broker. An example of such setup can be found here.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <!-- When + is passed, a latest tag will be applied when fetching pacts -->
+            <version>+</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-pact</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+    </dependencies>
+</plugin>

+

Gradle.  +

buildscript {
+	repositories {
+		//...
+	}
+
+	dependencies {
+		// ...
+		// Don't forget to add spring-cloud-contract-pact to the classpath!
+		classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
+	}
+}
+
+contracts {
+	// When + is passed, a latest tag will be applied when fetching pacts
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:+"
+	}
+	contractRepository {
+		repositoryUrl = "pact://http://localhost:8085"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}

+

With such a setup:

  • Pact files will be downloaded from the Pact Broker
  • Spring Cloud Contract will convert the Pact files into tests and stubs
  • The JAR with the stubs gets automatically created as usual

3.7.3 Pact Consumer (Producer Contract approach)

In the scenario where you don’t want to do Consumer Contract approach +(for every single consumer define the expectations) but you’d prefer +to do Producer Contracts (the producer provides the contracts and +publishes stubs), it’s enough to use Spring Cloud Contract with +Stub Runner option. An example of such setup can be found here.

First, remember to add Stub Runner and Spring Cloud Contract Pact module +as test dependencies.

Maven.  +

<dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-dependencies</artifactId>
+            <version>${spring-cloud.version}</version>
+            <type>pom</type>
+            <scope>import</scope>
+        </dependency>
+    </dependencies>
+</dependencyManagement>
+
+<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+<dependencies>
+    <!-- ... -->
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+        <scope>test</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-contract-pact</artifactId>
+        <scope>test</scope>
+    </dependency>
+</dependencies>

+

Gradle.  +

dependencyManagement {
+    imports {
+        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
+    }
+}
+
+dependencies {
+    //...
+    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
+    // Don't forget to add spring-cloud-contract-pact to the classpath!
+    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
+}

+

Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed +with pact:// protocol. E.g. pact://http://localhost:8085

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		ids = "com.example:beer-api-producer-pact",
+		repositoryRoot = "pact://http://localhost:8085")
+public class BeerControllerTest {
+    //Inject the port of the running stub
+    @StubRunnerPort("beer-api-producer-pact") int producerPort;
+    //...
+}

With such a setup:

  • Pact files will be downloaded from the Pact Broker
  • Spring Cloud Contract will convert the Pact files into stub definitions
  • The stub servers will be started and fed with stubs

For more information about Pact support you can go to +the Section 10.7, “Using the Pact Stub Downloader” section.

3.8 How can I debug the request/response being sent by the generated tests client?

The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

logging.level.org.apache.http.wire=DEBUG

3.8.1 How can I debug the mapping/request/response being sent by WireMock?

Starting from version 1.2.0 we turn on WireMock logging to +info and the WireMock notifier to being verbose. Now you will +exactly know what request was received by WireMock server and which +matching response definition was picked.

To turn off this feature just bump WireMock logging to ERROR

logging.level.com.github.tomakehurst.wiremock=ERROR

3.8.2 How can I see what got registered in the HTTP server stub?

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or +`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server +was started will be attached.

3.8.3 Can I reference text from file?

Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays. +If you’re using YAML just use the bodyFromFile property.

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_stub_runner.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_stub_runner.html new file mode 100644 index 00000000..181cb341 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_stub_runner.html @@ -0,0 +1,868 @@ + + + 6. Spring Cloud Contract Stub Runner

6. Spring Cloud Contract Stub Runner

One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging.

Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you.

6.1 Snapshot versions

Add the additional snapshot repository to your build.gradle file to use snapshot +versions, which are automatically uploaded after every successful build:

Maven.  +

<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>

+

Gradle.  +

buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}

+

6.2 Publishing Stubs as JARs

The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository.

[Tip]Tip

For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to.

Maven.  +

<!-- First disable the default jar setup in the properties section -->
+<!-- we don't want the verifier to do a jar for us -->
+<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+
+<!-- Next add the assembly plugin to your build -->
+<!-- we want the assembly plugin to generate the JAR -->
+<plugin>
+	<groupId>org.apache.maven.plugins</groupId>
+	<artifactId>maven-assembly-plugin</artifactId>
+	<executions>
+		<execution>
+			<id>stub</id>
+			<phase>prepare-package</phase>
+			<goals>
+				<goal>single</goal>
+			</goals>
+			<inherited>false</inherited>
+			<configuration>
+				<attach>true</attach>
+				<descriptors>
+					${basedir}/src/assembly/stub.xml
+				</descriptors>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>src/main/java</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/classes</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>

+

Gradle.  +

ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}

+

6.3 Stub Runner Core

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +Consumer Driven Contracts.

Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. +For messaging, special stub routes are defined.

6.3.1 Retrieving stubs

You can pick the following options of acquiring stubs

  • Aether based solution that downloads JARs with stubs from Artifactory / Nexus
  • Classpath scanning solution that searches classpath via pattern to retrieve stubs
  • Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

The latter example is described in the Custom Stub Runner section.

Stub downloading

You can control the stub downloading via the stubsMode switch. It picks value from the +StubRunnerProperties.StubsMode enum. You can use the following options

  • StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath
  • StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)
  • StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

Example:

@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)

Classpath scanning

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH +(or set nothing since CLASSPATH is the default value) then classpath will get scanned. +Let’s look at the following example:

@AutoConfigureStubRunner(ids = {
+    "com.example:beer-api-producer:+:stubs:8095",
+    "com.example.foo:bar:1.0.0:superstubs:8096"
+})

If you’ve added the dependencies to your classpath

Maven.  +

<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>beer-api-producer-restdocs</artifactId>
+    <classifier>stubs</classifier>
+    <version>0.0.1-SNAPSHOT</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+<dependency>
+    <groupId>com.example.foo</groupId>
+    <artifactId>bar</artifactId>
+    <classifier>superstubs</classifier>
+    <version>1.0.0</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>

+

Gradle.  +

testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
+    transitive = false
+}
+testCompile("com.example.foo:bar:1.0.0:superstubs") {
+    transitive = false
+}

+

Then the following locations on your classpath will get scanned. For com.example:beer-api-producer-restdocs

  • /META-INF/com.example/beer-api-producer-restdocs/*/.*
  • /contracts/com.example/beer-api-producer-restdocs/*/.*
  • /mappings/com.example/beer-api-producer-restdocs/*/.*

and com.example.foo:bar

  • /META-INF/com.example.foo/bar/*/.*
  • /contracts/com.example.foo/bar/*/.*
  • /mappings/com.example.foo/bar/*/.*
[Tip]Tip

As you can see you have to explicitly provide the group and artifact ids when packaging the +producer stubs.

The producer would setup the contracts like this:

└── src
+    └── test
+        └── resources
+            └── contracts
+                └── com.example
+                    └── beer-api-producer-restdocs
+                        └── nested
+                            └── contract3.groovy

To achieve proper stub packaging.

Or using the Maven assembly plugin or +Gradle Jar task you have to create the following +structure in your stubs jar.

└── META-INF
+    └── com.example
+        └── beer-api-producer-restdocs
+            └── 2.0.0
+                ├── contracts
+                │   └── nested
+                │       └── contract2.groovy
+                └── mappings
+                    └── mapping.json

By maintaining this structure classpath gets scanned and you can profit from the messaging / +HTTP stubs without the need to download artifacts.

Configuring HTTP Server Stubs

Stub Runner has a notion of a HttpServerStub that abstracts the underlaying +concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). +Sometimes, you need to perform some additional tuning of the stub servers, +that is concrete for the given implementation. To do that, Stub Runner gives you +the httpServerStubConfigurer property that is available in the annotation, +JUnit rule, and is accessible via system properties, where you can provide +your implementation of the org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer interface. The implementations can alter +the configuration files for the given HTTP server stub.

Spring Cloud Contract Stub Runner comes with an implementation that you +can extend, for WireMock - org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. In the configure method +you can provide your own, custom configuration for the given stub. The use +case might be starting WireMock for the given artifact id, on an HTTPs port. Example:

WireMockHttpServerStubConfigurer implementation.  +

@CompileStatic
+static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+	private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+	@Override
+	WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+		if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+			int httpsPort = SocketUtils.findAvailableTcpPort()
+			log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+			return httpStubConfiguration
+					.httpsPort(httpsPort)
+		}
+		return httpStubConfiguration
+	}
+}

+

You can then reuse it via the annotation

@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)

Whenever an https port is found, it will take precedence over the http one.

6.3.2 Running stubs

Running using main app

You can set the following options to the main class:

-c, --classifier                Suffix for the jar containing stubs (e.
+                                  g. 'stubs' if the stub jar would
+                                  have a 'stubs' classifier for stubs:
+                                  foobar-stubs ). Defaults to 'stubs'
+                                  (default: stubs)
+--maxPort, --maxp <Integer>     Maximum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  15000 (default: 15000)
+--minPort, --minp <Integer>     Minimum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  10000 (default: 10000)
+-p, --password                  Password to user when connecting to
+                                  repository
+--phost, --proxyHost            Proxy host to use for repository
+                                  requests
+--pport, --proxyPort [Integer]  Proxy port to use for repository
+                                  requests
+-r, --root                      Location of a Jar containing server
+                                  where you keep your stubs (e.g. http:
+                                  //nexus.
+                                  net/content/repositories/repository)
+-s, --stubs                     Comma separated list of Ivy
+                                  representation of jars with stubs.
+                                  Eg. groupid:artifactid1,groupid2:
+                                  artifactid2:classifier
+--sm, --stubsMode               Stubs mode to be used. Acceptable values
+                                  [CLASSPATH, LOCAL, REMOTE]
+-u, --username                  Username to user when connecting to
+                                  repository

HTTP Stubs

Stubs are defined in JSON documents, whose syntax is defined in WireMock documentation

Example:

{
+    "request": {
+        "method": "GET",
+        "url": "/ping"
+    },
+    "response": {
+        "status": 200,
+        "body": "pong",
+        "headers": {
+            "Content-Type": "text/plain"
+        }
+    }
+}

Viewing registered mappings

Every stubbed collaborator exposes list of defined mappings under __/admin/ endpoint.

You can also use the mappingsOutputFolder property to dump the mappings to files. + For annotation based approach it would look like this

@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
+mappingsOutputFolder = "target/outputmappings/")

and for the JUnit approach like this:

@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
+			.repoRoot("http://some_url")
+			.downloadStub("a.b.c", "loanIssuance")
+			.downloadStub("a.b.c:fraudDetectionServer")
+			.withMappingsOutputFolder("target/outputmappings")

Then if you check out the folder target/outputmappings you would see the following structure

.
+├── fraudDetectionServer_13705
+└── loanIssuance_12255

That means that there were two stubs registered. fraudDetectionServer was registered at port 13705 +and loanIssuance at port 12255. If we take a look at one of the files we would see (for WireMock) +mappings available for the given server:

[{
+  "id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
+  "request" : {
+    "url" : "/name",
+    "method" : "GET"
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "fraudDetectionServer"
+  },
+  "uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
+},
+...
+]

Messaging Stubs

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

6.4 Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}

There’s also a StubRunnerExtension available for JUnit 5. StubRunnerRule and StubRunnerExtension work in a very +similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

  • download them
  • cache them locally
  • unzip them to a temporary folder
  • start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port
  • feed the WireMock server with all JSON files that are valid WireMock definitions
  • can also send messages (remember to pass an implementation of MessageVerifier interface)

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. +Check their docs for more information.

Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they allow you to find the started stubs:

package org.springframework.cloud.contract.stubrunner;
+
+import java.net.URL;
+import java.util.Collection;
+import java.util.Map;
+
+import org.springframework.cloud.contract.spec.Contract;
+
+/**
+ * Contract for finding registered stubs.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubFinder extends StubTrigger {
+
+	/**
+	 * For the given groupId and artifactId tries to find the matching URL of the running
+	 * stub.
+	 * @param groupId - might be null. In that case a search only via artifactId takes
+	 * place
+	 * @param artifactId - artifact id of the stub
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;
+
+	/**
+	 * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
+	 * tries to find the matching URL of the running stub. You can also pass only
+	 * {@code artifactId}.
+	 * @param ivyNotation - Ivy representation of the Maven artifact
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String ivyNotation) throws StubNotFoundException;
+
+	/**
+	 * @return all running stubs
+	 */
+	RunningStubs findAllRunningStubs();
+
+	/**
+	 * @return the list of Contracts
+	 */
+	Map<StubConfiguration, Collection<Contract>> getContracts();
+
+}

Example of usage in Spock tests:

@ClassRule
+@Shared
+StubRunnerRule rule = new StubRunnerRule()
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule")
+
+
+def 'should start WireMock servers'() {
+	expect: 'WireMocks are running'
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+		rule.findStubUrl('loanIssuance') != null
+		rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+	and:
+		rule.findAllRunningStubs().isPresent('loanIssuance')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+	and: 'Stubs were registered'
+		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+}
+
+def 'should output mappings to output folder'() {
+	when:
+		def url = rule.findStubUrl('fraudDetectionServer')
+	then:
+		new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
+}

Example of usage in JUnit tests:

	@Test
+	public void should_start_wiremock_servers() throws Exception {
+		// expect: 'WireMocks are running'
+		then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
+		then(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isNotNull();
+		// and:
+		then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs",
+				"fraudDetectionServer")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isTrue();
+		// and: 'Stubs were registered'
+		then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
+				.isEqualTo("loanIssuance");
+		then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
+				.isEqualTo("fraudDetectionServer");
+	}
+
+	private String httpGet(String url) throws Exception {
+		try (InputStream stream = URI.create(url).toURL().openStream()) {
+			return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
+		}
+	}
+
+}

JUnit 5 Extension example:

// Visible for Junit
+@RegisterExtension
+static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
+		.repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule");
+
+@BeforeAll
+@AfterAll
+static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+private static String repoRoot() {
+	try {
+		return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
+				.toURI().toString();
+	}
+	catch (Exception e) {
+		return "";
+	}
+}

Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

[Important]Important

To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the +MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). +If you don’t do this, then whenever you try to send a message an exception will be thrown.

6.4.1 Maven settings

The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

6.4.2 Providing fixed ports

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule.

6.4.3 Fluent API

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.withPort(12345).downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}

You can see that for this example the following test is valid:

then(rule.findStubUrl("loanIssuance"))
+		.isEqualTo(URI.create("http://localhost:12345").toURL());
+then(rule.findStubUrl("fraudDetectionServer"))
+		.isEqualTo(URI.create("http://localhost:12346").toURL());

6.4.4 Stub Runner with Spring

Sets up Spring configuration of the Stub Runner project.

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +and registers in WireMock the selected stubs.

If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use +its methods as presented below:

@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
+		'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
+		'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
+@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+@ActiveProfiles("test")
+class StubRunnerConfigurationSpec extends Specification {
+
+	@Autowired
+	StubFinder stubFinder
+	@Autowired
+	Environment environment
+	@StubRunnerPort("fraudDetectionServer")
+	int fraudDetectionServerPort
+	@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+	int fraudDetectionServerPortWithGroupId
+	@Value('${foo}')
+	Integer foo
+
+	@BeforeClass
+	@AfterClass
+	void setupProps() {
+		System.clearProperty("stubrunner.repository.root")
+		System.clearProperty("stubrunner.classifier")
+	}
+
+	def 'should start WireMock servers'() {
+		expect: 'WireMocks are running'
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+		and:
+			stubFinder.findAllRunningStubs().isPresent('loanIssuance')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+		and: 'Stubs were registered'
+			"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+			"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+		and: 'Fraud Detection is an HTTPS endpoint'
+			stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
+	}
+
+	def 'should throw an exception when stub is not found'() {
+		when:
+			stubFinder.findStubUrl('nonExistingService')
+		then:
+			thrown(StubNotFoundException)
+		when:
+			stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId')
+		then:
+			thrown(StubNotFoundException)
+	}
+
+	def 'should register started servers as environment variables'() {
+		expect:
+			environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
+			stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
+	}
+
+	def 'should be able to interpolate a running stub in the passed test property'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			environment.getProperty("foo", Integer) == fraudPort
+			environment.getProperty("fooWithGroup", Integer) == fraudPort
+			foo == fraudPort
+	}
+
+	@Issue("#573")
+	def 'should be able to retrieve the port of a running stub via an annotation'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			fraudDetectionServerPort == fraudPort
+			fraudDetectionServerPortWithGroupId == fraudPort
+	}
+
+	def 'should dump all mappings to a file'() {
+		when:
+			def url = stubFinder.findStubUrl("fraudDetectionServer")
+		then:
+			new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
+	}
+
+	@Configuration
+	@EnableAutoConfiguration
+	static class Config {}
+
+	@CompileStatic
+	static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+		private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+		@Override
+		WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+			if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+				int httpsPort = SocketUtils.findAvailableTcpPort()
+				log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+				return httpStubConfiguration
+						.httpsPort(httpsPort)
+			}
+			return httpStubConfiguration
+		}
+	}
+}

for the following configuration file:

stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids:
+    - org.springframework.cloud.contract.verifier.stubs:loanIssuance
+    - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
+    - org.springframework.cloud.contract.verifier.stubs:bootService
+  stubs-mode: remote

Instead of using the properties you can also use the properties inside the @AutoConfigureStubRunner. +Below you can find an example of achieving the same result by setting values on the annotation.

@AutoConfigureStubRunner(
+		ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
+				"org.springframework.cloud.contract.verifier.stubs:bootService"],
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		repositoryRoot = "classpath:m2repo/repository/")

Stub Runner Spring registers environment variables in the following manner +for every registered WireMock server. Example for Stub Runner ids + com.example:foo, com.example:bar.

  • stubrunner.runningstubs.foo.port
  • stubrunner.runningstubs.com.example.foo.port
  • stubrunner.runningstubs.bar.port
  • stubrunner.runningstubs.com.example.bar.port

Which you can reference in your code.

You can also use the @StubRunnerPort annotation to inject the port of a running stub. +Value of the annotation can be the groupid:artifactid or just the artifactid. Example for Stub Runner ids +com.example:foo, com.example:bar.

@StubRunnerPort("foo")
+int fooPort;
+@StubRunnerPort("com.example:bar")
+int barPort;

6.5 Stub Runner Spring Cloud

Stub Runner can integrate with Spring Cloud.

For real life examples you can check the

6.5.1 Stubbing Service Discovery

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

  • DiscoveryClient
  • Ribbon ServerList

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate +or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

For example this test will pass

def 'should make service discovery work'() {
+	expect: 'WireMocks are running'
+		"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+	and: 'Stubs can be reached via load service discovery'
+		restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance'
+		restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer'
+}

for the following configuration file

stubrunner:
+  idsToServiceIds:
+    ivyNotation: someValueInsideYourCode
+    fraudDetectionServer: someNameThatShouldMapFraudDetectionServer

Test profiles and service discovery

In your integration tests you typically don’t want to call neither a discovery service (e.g. Eureka) +or Config Server. That’s why you create an additional test configuration in which you want to disable +these features.

Due to certain limitations of spring-cloud-commons to achieve this you have disable these properties +via a static block like presented below (example for Eureka)

    //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
+    static {
+        System.setProperty("eureka.client.enabled", "false");
+        System.setProperty("spring.cloud.config.failFast", "false");
+    }

6.5.2 Additional Configuration

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. +You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false +You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

[Tip]Tip

By default all service discovery will be stubbed. That means that regardless of the fact if you have +an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set + stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be + merged with the stubbed ones.

The default Maven configuration used by Stub Runner can be tweaked either +via the following system properties or environment variables

  • maven.repo.local - path to the custom maven local repository location
  • org.apache.maven.user-settings - path to custom maven user settings location
  • org.apache.maven.global-settings - path to maven global settings location

6.6 Stub Runner Boot Application

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +trigger the messaging labels and to access started WireMock servers.

One of the use-cases is to run some smoke (end to end) tests on a deployed application. +You can check out the Spring Cloud Pipelines +project for more information.

6.6.1 How to use it?

Stub Runner Server

Just add the

compile "org.springframework.cloud:spring-cloud-starter-stub-runner"

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

For the properties check the Stub Runner Spring section.

Stub Runner Server Fat Jar

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
+$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...

Spring Cloud CLI

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project you can start Stub Runner Boot by executing spring cloud stubrunner.

In order to pass the configuration just create a stubrunner.yml file in the current working directory +or a subdirectory called config or in ~/.spring-cloud. The file could look like this +(example for running stubs installed locally)

stubrunner.yml.  +

stubrunner:
+  stubsMode: LOCAL
+  ids:
+    - com.example:beer-api-producer:+:9876

+

and then just call spring cloud stubrunner from your terminal window to start +the Stub Runner server. It will be available at port 8750.

6.6.2 Endpoints

HTTP

  • GET /stubs - returns a list of all running stubs in ivy:integer notation
  • GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

Messaging

For Messaging

  • GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation
  • POST /triggers/{label} - executes a trigger with label
  • POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

6.6.3 Example

@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
+@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
+@ActiveProfiles("test")
+class StubRunnerBootSpec extends Specification {
+
+	@Autowired
+	StubRunning stubRunning
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
+				new TriggerController(stubRunning))
+	}
+
+	def 'should return a list of running stub servers in "full ivy:port" notation'() {
+		when:
+			String response = RestAssuredMockMvc.get('/stubs').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
+	}
+
+	def 'should return a port on which a [#stubId] stub is running'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/${stubId}")
+		then:
+			response.statusCode == 200
+			Integer.valueOf(response.body.asString()) > 0
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:+',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService',
+					   'bootService']
+	}
+
+	def 'should return 404 when missing stub was called'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
+		then:
+			response.statusCode == 404
+	}
+
+	def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
+		when:
+			String response = RestAssuredMockMvc.get('/triggers').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"])
+	}
+
+	def 'should trigger a messaging label'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger('delete_book')
+	}
+
+	def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger(stubId, 'delete_book')
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
+	}
+
+	def 'should throw exception when trigger is missing'() {
+		when:
+			RestAssuredMockMvc.post("/triggers/missing_label")
+		then:
+			Exception e = thrown(Exception)
+			e.message.contains("Exception occurred while trying to return [missing_label] label.")
+			e.message.contains("Available labels are")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
+	}
+
+}

6.6.4 Stub Runner Boot with Service Discovery

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? + Let’s assume that you don’t want to deploy 50 microservice to a test environment in order + to check if your application is working fine. You’ve already executed a suite of tests during the build process + but you would also like to ensure that the packaging of your application is fine. What you can do + is to deploy your application to an environment, start it and run a couple of tests on it to see if + it’s working fine. We can call those tests smoke-tests since their idea is to check only a handful + of testing scenarios.

The problem with this approach is such that if you’re doing microservices most likely you’re + using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the + required stubs and register them in a service discovery tool. Let’s take a look at an example of + such a setup with Eureka. Let’s assume that Eureka was already running.

@SpringBootApplication
+@EnableStubRunnerServer
+@EnableEurekaClient
+@AutoConfigureStubRunner
+public class StubRunnerBootEurekaExample {
+
+	public static void main(String[] args) {
+		SpringApplication.run(StubRunnerBootEurekaExample.class, args);
+	}
+
+}

As you can see we want to start a Stub Runner Boot server @EnableStubRunnerServer, enable Eureka client @EnableEurekaClient +and we want to have the stub runner feature turned on @AutoConfigureStubRunner.

Now let’s assume that we want to start this application so that the stubs get automatically registered. + We can do it by running the app java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar where + ${SYSTEM_PROPS} would contain the following list of properties

* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1)
+* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2)
+* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.
+* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework.
+* cloud.contract.verifier.stubs:bootService (3)
+* -Dstubrunner.idsToServiceIds.fraudDetectionServer=
+* someNameThatShouldMapFraudDetectionServer (4)
+*
+* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default
+* behaviour where the discovery service is stubbed. That's why the stub registration will
+* be picked (3) - we provide a list of stubs to download (4) - we provide a list of

That way your deployed application can send requests to started WireMock servers via the service +discovery. Most likely points 1-3 could be set by default in application.yml cause they are not +likely to change. That way you can provide only the list of stubs to download whenever you start +the Stub Runner Boot.

6.7 Stubs Per Consumer

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

[Tip]Tip

This approach also allows you to immediately know which consumer is using which part of your API. +You can remove part of a response that your API produces and you can see which of your autogenerated tests +fails. If none fails then you can safely delete that part of the response cause nobody is using it.

Let’s look at the following example for contract defined for the producer called producer. +There are 2 consumers: foo-consumer and bar-consumer.

Consumer foo-service

request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       foo: "foo"
+    }
+}

Consumer bar-service

request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       bar: "bar"
+    }
+}

You can’t produce for the same request 2 different responses. That’s why you can properly package the +contracts and then profit from the stubsPerConsumer feature.

On the producer side the consumers can have a folder that contains contracts related only to them. +By setting the stubrunner.stubs-per-consumer flag to true we no longer register all stubs but only those that +correspond to the consumer application’s name. In other words we’ll scan the path of every stub and +if it contains the subfolder with name of the consumer in the path only then will it get registered.

On the foo producer side the contracts would look like this

.
+└── contracts
+    ├── bar-consumer
+    │   ├── bookReturnedForBar.groovy
+    │   └── shouldCallBar.groovy
+    └── foo-consumer
+        ├── bookReturnedForFoo.groovy
+        └── shouldCallFoo.groovy

Being the bar-consumer consumer you can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer +Or set the test as follows:

@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = ["spring.application.name=bar-consumer"])
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerSpec extends Specification {
+...
+}

Then only the stubs registered under a path that contains the bar-consumer in its name (i.e. those from the +src/test/resources/contracts/bar-consumer/some/contracts/…​ folder) will be allowed to be referenced.

Or set the consumer name explicitly

@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		consumerName = "foo-consumer",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification {
+...
+}

Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the +src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

You can check out issue 224 for more +information about the reasons behind this change.

6.8 Common

This section briefly describes common properties, including:

6.8.1 Common Properties for JUnit and Spring

You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values:

Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

 

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

 

Array of Ivy notation stubs to download.

stubrunner.username

 

Optional username to access the tool that stores the JARs with +stubs.

stubrunner.password

 

Optional password to access the tool that stores the JARs with +stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for +each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

 

If you want to use a stub for each consumer and want to +override the consumer name just change this value.

6.8.2 Stub Runner Stubs IDs

You can provide the stubs to download via the stubrunner.ids system property. They +follow this pattern:

groupId:artifactId:version:classifier:port

Note that version, classifier and port are optional.

  • If you do not provide the port, a random one will be picked.
  • If you do not provide the classifier, the default is used. (Note that you can +pass an empty classifier this way: groupId:artifactId:version:).
  • If you do not provide the version, then the + will be passed and the latest one is +downloaded.

port means the port of the WireMock server.

[Important]Important

Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +Aether versioning +ranges here.

6.9 Stub Runner Docker

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +that will start the standalone version of Stub Runner.

If you want to learn more about the basics of Maven, artifact ids, +group ids, classifiers and Artifact Managers, just click here Section 4.5, “Docker Project”.

6.9.1 How to use it

Just execute the docker image. You can pass any of the Section 6.8.1, “Common Properties for JUnit and Spring” +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (.) should be separated via underscore (_). E.g. + the stubrunner.repositoryRoot property should be represented + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

6.9.2 Example of client side usage in a non JVM project

We’d like to use the stubs created in this Section 4.5.4, “Server side (nodejs)” step. +Let’s assume that we want to run the stubs on port 9876. The NodeJS code +is available here:

$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore

Let’s run the Stub Runner Boot application with the stubs.

# Provide the Spring Cloud Contract Docker version
+$ SC_CONTRACT_DOCKER_VERSION="..."
+# The IP at which the app is running and Docker container can reach it
+$ APP_IP="192.168.0.100"
+# Spring Cloud Contract Stub Runner properties
+$ STUBRUNNER_PORT="8083"
+# Stub coordinates 'groupId:artifactId:version:classifier:port'
+$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
+$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
+# Run the docker with Stub Runner Boot
+$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"

What’s happening is that

  • a standalone Stub Runner application got started
  • it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876
  • it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local
  • after a while Stub Runner will be running on port 8083
  • and the stubs will be running at port 9876

On the server side we built a stateful stub. Let’s use curl to assert +that the stubs are setup properly.

# let's execute the first request (no response is returned)
+$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
+# Now time for the second request
+$ curl -X GET http://localhost:9876/api/books
+# You will receive contents of the JSON
[Important]Important

If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro"

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_introduction.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_introduction.html new file mode 100644 index 00000000..fe8bdf7d --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_introduction.html @@ -0,0 +1,843 @@ + + + 2. Spring Cloud Contract Verifier Introduction

2. Spring Cloud Contract Verifier Introduction

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture.

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract +definitions are used to produce the following resources:

  • JSON stub definitions to be used by WireMock when doing integration testing on the +client code (client tests). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier.
  • Messaging routes, if you’re using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations.
  • Acceptance tests (in JUnit 4, JUnit 5 or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (server tests). A full test is generated by +Spring Cloud Contract Verifier.

2.1 History

Before becoming Spring Cloud Contract, this project was called Accurest. +It was created by Marcin Grzejszczak and Jakub Kubrynski +from (Codearte.

The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016.

2.2 Why a Contract Verifier?

Assume that we have a system consisting of multiple microservices:

Microservices Architecture

2.2.1 Testing issues

If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things:

  • Deploy all microservices and perform end-to-end tests.
  • Mock other microservices in unit/integration tests.

Both have their advantages but also a lot of disadvantages.

Deploy all microservices and perform end to end tests

Advantages:

  • Simulates production.
  • Tests real communication between services.

Disadvantages:

  • To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc.
  • The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime).
  • They take a long time to run.
  • The feedback comes very late in the process.
  • They are extremely hard to debug.

Mock other microservices in unit/integration tests

Advantages:

  • They provide very fast feedback.
  • They have no infrastructure requirements.

Disadvantages:

  • The implementor of the service creates stubs that might have nothing to do with +reality.
  • You can go to production with passing tests and failing production.

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses.

Stubbed Services

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you’re calling. Also, if you can use them, it means that they +were tested against the producer’s side. In short, you can trust those stubs.

2.3 Purposes

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

  • To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does.
  • To promote ATDD method and Microservices architectural style.
  • To provide a way to publish changes in contracts that are immediately visible on both +sides.
  • To generate boilerplate test code to be used on the server side.
[Important]Important

Spring Cloud Contract Verifier’s purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior.

2.4 How It Works

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

2.4.1 A Three-second Tour

This very brief tour walks through using Spring Cloud Contract:

You can find a somewhat longer tour +here.

On the Producer Side

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +org.springframework.cloud.contract.verifier.tests..

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example RestAssuredMockMvc +controller setup or messaging test setup).

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository.

On the Consumer Side

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the +following example:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

  • By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands:

    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Tip]Tip

    The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail.

  • By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract +Stub Runner properties, as shown in the following example:

    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to +run the collaborators' stubs for you, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
[Tip]Tip

Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work.

Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service.

2.4.2 A Three-minute Tour

This brief tour walks through using Spring Cloud Contract:

You can find an even more brief tour +here.

On the Producer Side

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract in Groovy DSL:

package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url '/fraudcheck'
+		body([
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount: 99999
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+	response {
+		status OK()
+		body([
+			   fraudCheckStatus: "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+}

The same contract expressed in YAML would look like the following example:

request:
+  method: PUT
+  url: /fraudcheck
+  body:
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers:
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id']
+        type: by_regex
+        value: "[0-9]{10}"
+response:
+  status: 200
+  body:
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers:
+    Content-Type: application/json;charset=UTF-8

In the case of messaging, you can define:

  • The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header).
  • The methods that should be called after the message is received.
  • The methods that, when called, should trigger a message.

The following example shows a Camel messaging contract expressed in Groovy DSL:

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}

The following example shows the same contract expressed in YAML:

label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +org.springframework.cloud.contract.verifier.tests..

The following example shows a sample auto-generated test for an HTTP contract:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}

The preceding example uses Spring’s MockMvc to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, +respectively.)

Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient +run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. +In order to use WebTestClient set testMode to WEBTESTCLIENT.

Here is an example of a test generated in WEBTESTCLIENT test mode:

[source,java,indent=0]
@Test
+	public void validate_shouldRejectABeerIfTooYoung() throws Exception {
+		// given:
+			WebTestClientRequestSpecification request = given()
+					.header("Content-Type", "application/json")
+					.body("{\"age\":10}");
+
+		// when:
+			WebTestClientResponse response = given().spec(request)
+					.post("/check");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+			assertThat(response.header("Content-Type")).matches("application/json.*");
+		// and:
+			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+			assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
+	}

Apart from the default JUnit 4, you can instead use JUnit 5 or Spock tests, by setting the plugin +testFramework property to either JUNIT5 or Spock.

[Tip]Tip

You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names.

The following example shows an auto-generated test in Spock for a messaging stub contract:

[source,groovy,indent=0]
given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, RestAssuredMockMvc controller +setup or messaging test setup).

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example:

[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

You can now merge the changes and publish both the application and the stub artifacts +in an online repository.

Docker Project

In order to enable working with contracts while creating applications in non-JVM +technologies, the springcloud/spring-cloud-contract Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the /contracts directory and set a few environment variables.

On the Consumer Side

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

To get started, add the dependency to Spring Cloud Contract Stub Runner:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

  • By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands:

    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Note]Note

    The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail.

  • Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub +Runner properties, as shown in the following example:

    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run +the collaborators' stubs for you, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
[Tip]Tip

Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work.

In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs:

2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

2.4.3 Defining the Contract

As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts.

Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method.

Groovy DSL.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */

+

YAML.  +

request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json;charset=UTF-8
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json;charset=UTF-8`

+

2.4.4 Client Side

Spring Cloud Contract generates stubs, which you can use during client-side testing. +You get a running WireMock instance/Messaging route that simulates the service. +You would like to feed that instance with a proper stub definition.

At some point in time, you need to send a request to the Fraud Detection service.

ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);

Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {

After that, during the tests, Spring Cloud Contract automatically finds the stubs +(simulating the real service) in the Maven repository and exposes them on a configured +(or random) port.

2.4.5 Server Side

Since you are developing your stub, you need to be sure that it actually resembles your +concrete implementation. You cannot have a situation where your stub acts in one way and +your application behaves in a different way, especially in production.

To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide.

The autogenerated test looks, more or less, like this:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}

2.5 Step-by-step Guide to Consumer Driven Contracts (CDC)

Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody.

Assume that Loan Issuance is a client to the Fraud Detection server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud.

Technical remark - Fraud Detection has an artifact-id of http-server, while Loan +Issuance has an artifact-id of http-client, and both have a group-id of com.example.

Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication.

The server +side code is available here and the +client code here.

[Tip]Tip

In this case, the producer owns the contracts. Physically, all the contract are +in the producer’s repository.

2.5.1 Technical note

If using the SNAPSHOT / Milestone / Release Candidate versions please add the +following section to your build:

Maven.  +

<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>

+

Gradle.  +

repositories {
+	mavenCentral()
+	mavenLocal()
+	maven { url "https://repo.spring.io/snapshot" }
+	maven { url "https://repo.spring.io/milestone" }
+	maven { url "https://repo.spring.io/release" }
+}

+

2.5.2 Consumer side (Loan Issuance)

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

  1. Start doing TDD by writing a test for your feature.
  2. Write the missing implementation.
  3. Clone the Fraud Detection service repository locally.
  4. Define the contract locally in the repo of Fraud Detection service.
  5. Add the Spring Cloud Contract Verifier plugin.
  6. Run the integration tests.
  7. File a pull request.
  8. Create an initial implementation.
  9. Take over the pull request.
  10. Write the missing implementation.
  11. Deploy your app.
  12. Work online.

Start doing TDD by writing a test for your feature.

@Test
+public void shouldBeRejectedDueToAbnormalLoanAmount() {
+	// given:
+	LoanApplication application = new LoanApplication(new Client("1234567890"),
+			99999);
+	// when:
+	LoanApplicationResult loanApplication = service.loanApplication(application);
+	// then:
+	assertThat(loanApplication.getLoanApplicationStatus())
+			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
+	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
+}

Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description.

Write the missing implementation.

At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the /fraudcheck url via the PUT method.

ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);

For simplicity, the port of the Fraud Detection service is set to 8080, and the +application runs on 8090.

If you start the test at this point, it breaks, because no service currently runs on port +8080.

Clone the Fraud Detection service repository locally.

You can start by playing around with the server side contract. To do so, you must first +clone it.

$ git clone https://your-git-server.com/server-side.git local-http-server-repo

Define the contract locally in the repo of Fraud Detection service.

As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract:

[Important]Important

Place the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important because the producer’s test base class name references that folder.

Groovy DSL.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */

+

YAML.  +

request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json;charset=UTF-8
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json;charset=UTF-8`

+

The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the Chapter 8, Contract DSL section for more information. We highly recommend using the map notation!

[Tip]Tip

You must understand the map notation in order to set up contracts. Please read the +Groovy docs regarding JSON.

The previously shown contract is an agreement between two sides that:

  • if an HTTP request is sent with all of

    • a PUT method on the /fraudcheck endpoint,
    • a JSON body with a client.id that matches the regular expression [0-9]{10} and +loanAmount equal to 99999,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json,
  • then an HTTP response is sent to the consumer that

    • has status 200,
    • contains a JSON body with the fraudCheckStatus field containing a value FRAUD and +the rejectionReason field having value Amount too high,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json.

Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally.

Add the Spring Cloud Contract Verifier plugin.

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the Spring Cloud Contract BOM.

<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

Next, add the Spring Cloud Contract Verifier Maven plugin

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>

Since the plugin was added, you get the Spring Cloud Contract Verifier features which, +from the provided contracts:

  • generate and run tests
  • produce and install stubs

You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute:

$ cd local-http-server-repo
+$ ./mvnw clean install -DskipTests

In the logs, you see something like this:

[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

The following line is extremely important:

[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

It confirms that the stubs of the http-server have been installed in the local +repository.

Run the integration tests.

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (Loan +Application service):

Add the Spring Cloud Contract BOM:

<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release-train.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

Add the dependency to Spring Cloud Contract Stub Runner:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>

Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the +group-id and artifact-id for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you’re playing with the collaborators offline, you +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {

Now, when you run your tests, you see something like this:

2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

This output means that Stub Runner has found your stubs and started a server for your app +with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of +the stubs and with stubs classifier on port 8080.

File a pull request.

What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish.

Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done.

2.5.3 Producer side (Fraud Detection server)

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

Create an initial implementation.

As a reminder, you can see the initial implementation here:

@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}

Take over the pull request.

$ git checkout -b contract-change-pr master
+$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr

You must add the dependencies needed by the autogenerated tests:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>

In the configuration of the Maven plugin, pass the packageWithBaseClasses property

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
[Important]Important

This example uses "convention based" naming by setting the +packageWithBaseClasses property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +src/test/resources/contracts/fraud. Since you do not have two packages starting from +the contracts folder, pick only one, which should be fraud. Add the Base suffix and +capitalize fraud. That gives you the FraudBase test class name.

All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use Rest Assured MVC to +start the server side FraudDetectionController.

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+
+public class FraudBase {
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(),
+				new FraudStatsController(stubbedStatsProvider()));
+	}
+
+	private StatsProvider stubbedStatsProvider() {
+		return fraudType -> {
+			switch (fraudType) {
+			case DRUNKS:
+				return 100;
+			case ALL:
+				return 200;
+			}
+			return 0;
+		};
+	}
+
+	public void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}

Now, if you run the ./mvnw clean install, you get something like this:

Results :
+
+Tests in error:
+  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...

This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}

If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the +value(consumer(…​), producer(…​)) blocks got injected into the test. +In case of using YAML, the same applied for the matchers sections of the response.

Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the red part of red, green, and +refactor. It is time to convert the red into the green.

Write the missing implementation.

Because you know the expected input and expected output, you can write the missing +implementation:

@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+if (amountGreaterThanThreshold(fraudCheck)) {
+	return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
+}
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}

When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud +Contract Verifier plugin adds the tests to the generated-test-sources, you can +actually run those tests from your IDE.

Deploy your app.

Once you finish your work, you can deploy your change. First, merge the branch:

$ git checkout master
+$ git merge --no-ff contract-change-pr
+$ git push origin master

Your CI might run something like ./mvnw clean deploy, which would publish both the +application and the stub artifacts.

2.5.4 Consumer Side (Loan Issuance) Final Step

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

Merge branch to master.

$ git checkout master
+$ git merge --no-ff contract-change-pr

Work online.

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +stubsMode to REMOTE. The following code shows an example of +achieving the same thing by changing the properties.

stubrunner:
+  ids: 'com.example:http-server-dsl:+:stubs:8080'
+  repositoryRoot: https://repo.spring.io/libs-snapshot

That’s it!

2.6 Dependencies

The best way to add dependencies is to use the proper starter dependency.

For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add +spring-cloud-starter-contract-verifier.

2.7 Additional Links

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development.

2.7.1 Spring Cloud Contract video

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

2.8 Samples

You can find some samples at +samples.

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_messaging.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_messaging.html new file mode 100644 index 00000000..46808027 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_messaging.html @@ -0,0 +1,260 @@ + + + 5. Spring Cloud Contract Verifier Messaging

5. Spring Cloud Contract Verifier Messaging

Spring Cloud Contract Verifier lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that.

5.1 Integrations

You can use one of the following four integration configurations:

  • Apache Camel
  • Spring Integration
  • Spring Cloud Stream
  • Spring AMQP

Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up.

[Important]Important

Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work.

[Important]Important

If you want to use Spring Cloud Stream, remember to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support, as shown here:

Maven.  +

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

+

5.2 Manual Integration Testing

The main interface used by the tests is +org.springframework.cloud.contract.verifier.messaging.MessageVerifier. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal.

In a test, you can inject a ContractVerifierMessageExchange to send and receive +messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. +Here’s an example:

@RunWith(SpringTestRunner.class)
+@SpringBootTest
+@AutoConfigureMessageVerifier
+public static class MessagingContractTests {
+
+  @Autowired
+  private MessageVerifier verifier;
+  ...
+}
[Note]Note

If your tests require stubs as well, then @AutoConfigureStubRunner includes the +messaging configuration, so you only need the one annotation.

5.3 Publisher-Side Test Generation

Having the input or outputMessage sections in your DSL results in creation of tests +on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5 or Spock tests.

There are 3 main scenarios that we should take into consideration:

  • Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler).
  • Scenario 2: The input message triggers an output message.
  • Scenario 3: The input message is consumed and there is no output message.
[Important]Important

The destination passed to messageFrom or sentTo can have different +meanings for different messaging implementations. For Stream and Integration it is +first resolved as a destination of a channel. Then, if there is no such destination +it is resolved as a channel name. For Camel, that’s a certain component (for example, +jms).

5.3.1 Scenario 1: No Input Message

For the given contract:

Groovy DSL.  +

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					triggeredBy('bookReturnedTriggered()')
+				}
+				outputMessage {
+					sentTo('activemq:output')
+					body('''{ "bookName" : "foo" }''')
+					headers {
+						header('BOOK-NAME', 'foo')
+						messagingContentType(applicationJson())
+					}
+				}
+			}

+

YAML.  +

label: some_label
+input:
+  triggeredBy: bookReturnedTriggered
+outputMessage:
+  sentTo: activemq:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+    contentType: application/json

+

The following JUnit test is created:

					'''
+ // when:
+  bookReturnedTriggered();
+
+ // then:
+  ContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
+  assertThat(response).isNotNull();
+  assertThat(response.getHeader("BOOK-NAME")).isNotNull();
+  assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+  assertThat(response.getHeader("contentType")).isNotNull();
+  assertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");
+ // and:
+  DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+  assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
+'''

And the following Spock test would be created:

					'''
+ when:
+  bookReturnedTriggered()
+
+ then:
+  ContractVerifierMessage response = contractVerifierMessaging.receive('activemq:output')
+  assert response != null
+  response.getHeader('BOOK-NAME')?.toString()  == 'foo'
+  response.getHeader('contentType')?.toString()  == 'application/json'
+ and:
+  DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
+  assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
+
+'''

5.3.2 Scenario 2: Output Triggered by Input

For the given contract:

Groovy DSL.  +

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					messageFrom('jms:input')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+				}
+				outputMessage {
+					sentTo('jms:output')
+					body([
+							bookName: 'foo'
+					])
+					headers {
+						header('BOOK-NAME', 'foo')
+					}
+				}
+			}

+

YAML.  +

label: some_label
+input:
+  messageFrom: jms:input
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+outputMessage:
+  sentTo: jms:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo

+

The following JUnit test is created:

					'''
+// given:
+ ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+  "{\\"bookName\\":\\"foo\\"}"
+, headers()
+  .header("sample", "header"));
+
+// when:
+ contractVerifierMessaging.send(inputMessage, "jms:input");
+
+// then:
+ ContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
+ assertThat(response).isNotNull();
+ assertThat(response.getHeader("BOOK-NAME")).isNotNull();
+ assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+ assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
+'''

And the following Spock test would be created:

					"""\
+given:
+   ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+    '''{"bookName":"foo"}''',
+    ['sample': 'header']
+  )
+
+when:
+   contractVerifierMessaging.send(inputMessage, 'jms:input')
+
+then:
+   ContractVerifierMessage response = contractVerifierMessaging.receive('jms:output')
+   assert response !- null
+   response.getHeader('BOOK-NAME')?.toString()  == 'foo'
+and:
+   DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
+   assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
+"""

5.3.3 Scenario 3: No Output Message

For the given contract:

Groovy DSL.  +

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}

+

YAML.  +

label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()

+

The following JUnit test is created:

					'''
+// given:
+ ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+	"{\\"bookName\\":\\"foo\\"}"
+, headers()
+	.header("sample", "header"));
+
+// when:
+ contractVerifierMessaging.send(inputMessage, "jms:delete");
+
+// then:
+ bookWasDeleted();
+'''

And the following Spock test would be created:

					'''
+given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()
+'''

5.4 Consumer Stub Generation

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

For more information, see Chapter 7, Stub Runner for Messaging section.

Maven.  +

<dependencies>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
+	</dependency>
+
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+		<scope>test</scope>
+	</dependency>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-stream-test-support</artifactId>
+		<scope>test</scope>
+	</dependency>
+</dependencies>
+
+<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>Greenwich.BUILD-SNAPSHOT</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

+

Gradle.  +

ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}

+

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_setup.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_setup.html new file mode 100644 index 00000000..c1792e1f --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_verifier_setup.html @@ -0,0 +1,694 @@ + + + 4. Spring Cloud Contract Verifier Setup

4. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in the following ways:

4.1 Gradle Project

To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections:

4.1.1 Prerequisites

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin.

[Warning]Warning

If you want to use Spock in your projects, you must add separately the +spock-core and spock-spring modules. Check Spock +docs for more information

4.1.2 Add Gradle Plugin with Dependencies

To add a Gradle plugin with dependencies, use code similar to this:

buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+	    classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+	}
+}
+
+apply plugin: 'groovy'
+apply plugin: 'spring-cloud-contract'
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
+	}
+}
+
+dependencies {
+	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
+	// example with adding Spock core and Spock Spring
+	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
+	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}

4.1.3 Gradle and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here:

buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+	    classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+		classpath "com.jayway.restassured:rest-assured:2.5.0"
+		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
+	}
+}
+
+depenendencies {
+    // all dependencies
+    // you can exclude rest-assured from spring-cloud-contract-verifier
+    testCompile "com.jayway.restassured:rest-assured:2.5.0"
+    testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
+}

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly.

4.1.4 Snapshot Versions for Gradle

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+}

4.1.5 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory.

The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure:

src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods:

  • shouldCreateUser()
  • shouldReturnUser()

4.1.6 Run the Plugin

The plugin registers itself to be invoked before a check task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the generateContractTests task.

4.1.7 Default Setup

The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode):

contracts {
+    testFramework ='JUNIT'
+    testMode = 'MockMvc'
+    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
+    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
+    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
+    basePackageForTests = 'org.springframework.cloud.verifier.tests'
+    stubsOutputDir = project.file("${project.buildDir}/stubs")
+
+    // the following properties are used when you want to provide where the JAR with contract lays
+    contractDependency {
+        stringNotation = ''
+    }
+    contractsPath = ''
+    contractsWorkOffline = false
+    contractRepository {
+        cacheDownloadedContracts(true)
+    }
+}
+
+tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
+    baseName = project.name
+    classifier = contracts.stubsSuffix
+    from contractVerifier.stubsOutputDir
+}
+
+project.artifacts {
+    archives task
+}
+
+tasks.create(type: Copy, name: 'copyContracts') {
+    from contracts.contractsDslDir
+    into contracts.stubsOutputDir
+}
+
+verifierStubsJar.dependsOn 'copyContracts'
+
+publishing {
+    publications {
+        stubs(MavenPublication) {
+            artifactId project.name
+            artifact verifierStubsJar
+        }
+    }
+}

4.1.8 Configure Plugin

To change the default configuration, add a contracts snippet to your Gradle config, as +shown here:

contracts {
+	testMode = 'MockMvc'
+	baseClassForTests = 'org.mycompany.tests'
+	generatedTestSourcesDir = project.file('src/generatedContract')
+}

4.1.9 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.
  • imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array.
  • staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests.
  • baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test +classes.
  • ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array.
  • contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts.
  • stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed.
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

The following properties are used when you want to specify the location of the JAR +containing the contracts:

  • contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up.
  • contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory.
  • contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.)
  • deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.1.10 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}

If you use Explicit mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this +base class should also contain a protected WebTarget webTarget field. Right now, the +only option to test the JAX-RS API is to start a web server.

4.1.11 Different Base Classes for Contracts

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

  • Follow a convention by providing the packageWithBaseClasses
  • Provide explicit mapping via baseClassMappings

By Convention

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

packageWithBaseClasses = 'com.example.base'

By Mapping

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

baseClassForTests = "com.example.FooBase"
+baseClassMappings {
+	baseClassMapping('.*/com/.*', 'com.example.ComBase')
+	baseClassMapping('.*/bar/.*': 'com.example.BarBase')
+}

Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

4.1.12 Invoking Generated Tests

To ensure that the provider side is compliant with defined contracts, you need to invoke:

./gradlew generateContractTests test

4.1.13 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example:

$ ./gradlew pushStubsToScm

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable.

4.1.14 Spring Cloud Contract Verifier on the Consumer Side

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in src/test/resources/contracts and generate +WireMock JSON stubs using:

./gradlew generateClientStubs
[Note]Note

The stubsOutputDir option has to be set for stub generation to work.

When present, JSON stubs can be used in automated tests of consuming a service.

@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
+class LoanApplicationServiceSpec extends Specification {
+
+ @ClassRule
+ @Shared
+ WireMockClassRule wireMockRule == new WireMockClassRule()
+
+ @Autowired
+ LoanApplicationService sut
+
+ def 'should successfully apply for loan'() {
+   given:
+ 	LoanApplication application =
+			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
+   when:
+	LoanApplicationResult loanApplication == sut.loanApplication(application)
+   then:
+	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
+	loanApplication.rejectionReason == null
+ }
+}

LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

4.2 Maven Project

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections:

4.2.1 Add maven plugin

Add the Spring Cloud Contract BOM in a fashion similar to this:

<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

Next, add the Spring Cloud Contract Verifier Maven plugin:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>

You can read more in the +Spring +Cloud Contract Maven Plugin Documentation (example for 2.0.0.RELEASE version).

4.2.2 Maven and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here:

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <packageWithBaseClasses>com.example</packageWithBaseClasses>
+    </configuration>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-verifier</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>rest-assured</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>spring-mock-mvc</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+    </dependencies>
+</plugin>
+
+<dependencies>
+    <!-- all dependencies -->
+    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>rest-assured</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>spring-mock-mvc</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+</dependencies>

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly.

4.2.3 Snapshot versions for Maven

For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here:

<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>

4.2.4 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure:

src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods

  • shouldCreateUser()
  • shouldReturnUser()

4.2.5 Run plugin

The plugin goal generateTests is assigned to be invoked in the phase called +generate-test-sources. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the generateTests goal.

4.2.6 Configure plugin

To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here:

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <executions>
+        <execution>
+            <goals>
+                <goal>convert</goal>
+                <goal>generateStubs</goal>
+                <goal>generateTests</goal>
+            </goals>
+        </execution>
+    </executions>
+    <configuration>
+        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
+        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
+    </configuration>
+</plugin>

4.2.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test +classes.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.
  • contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix.
  • baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

If you want to download your contract definitions from a Maven repository, you can use +the following options:

  • contractDependency: The contract dependency that contains all the packaged contracts.
  • contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated.
  • contractsMode: Picks the mode in which stubs will be found and registered
  • deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories
  • contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones.
  • contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.
  • contractsRepositoryPassword: The password to be used to connect to the repo with contracts.
  • contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.
  • contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

We cache only non-snapshot, explicitly provided versions (for example ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.2.8 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

package org.mycompany.tests
+
+import org.mycompany.ExampleSpringController
+import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
+import spock.lang.Specification
+
+class MvcSpec extends Specification {
+  def setup() {
+   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
+  }
+}

You can also setup the whole context if necessary.

import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@Autowired
+	WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.webAppContextSetup(this.context);
+	}
+}

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests.

import io.restassured.RestAssured;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@LocalServerPort
+	int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost:" + this.port;
+	}
+}

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right +now, the only option to test the JAX-RS API is to start a web server.

4.2.9 Different base classes for contracts

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

  • Follow a convention by providing the packageWithBaseClasses
  • provide explicit mapping via baseClassMappings

By Convention

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<packageWithBaseClasses>hello</packageWithBaseClasses>
+	</configuration>
+</plugin>

By Mapping

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<baseClassForTests>com.example.FooBase</baseClassForTests>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*com.*</contractPackageRegex>
+				<baseClassFQN>com.example.TestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+</plugin>

Assume that you have contracts under these two locations: +* src/test/resources/contract/com/ +* src/test/resources/contract/foo/

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

4.2.10 Invoking generated tests

The Spring Cloud Contract Maven Plugin generates verification code in a directory called +/generated-test-sources/contractVerifier and attaches this directory to testCompile +goal.

For Groovy Spock code, use the following:

<plugin>
+	<groupId>org.codehaus.gmavenplus</groupId>
+	<artifactId>gmavenplus-plugin</artifactId>
+	<version>1.5</version>
+	<executions>
+		<execution>
+			<goals>
+				<goal>testCompile</goal>
+			</goals>
+		</execution>
+	</executions>
+	<configuration>
+		<testSources>
+			<testSource>
+				<directory>${project.basedir}/src/test/groovy</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+			<testSource>
+				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+		</testSources>
+	</configuration>
+</plugin>

To ensure that provider side is compliant with defined contracts, you need to invoke +mvn generateTest test.

4.2.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example:

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable.

4.2.12 Maven Plugin and STS

If you see the following exception while using STS:

STS Exception

When you click on the error marker you should see something like this:

 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
+ cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
+ org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
+...
+ org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
+ org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
+ org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at

In order to fix this issue, provide the following section in your pom.xml:

<build>
+    <pluginManagement>
+        <plugins>
+            <!--This plugin's configuration is used to store Eclipse m2e settings
+                only. It has no influence on the Maven build itself. -->
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                             <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.springframework.cloud</groupId>
+                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                    <versionRange>[1.0,)</versionRange>
+                                    <goals>
+                                        <goal>convert</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <execute />
+                                </action>
+                             </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+        </plugins>
+    </pluginManagement>
+</build>

4.2.13 Maven Plugin with Spock Tests

You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly.

First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below:

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example:

4.3 Stubs and Transitive Dependencies

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom:

├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
+├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
+├── ...
+└── ...

There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies:

  • Mark all application dependencies as optional
  • Create a separate artifactid for the stubs
  • Exclude dependencies on the consumer side

Mark all application dependencies as optional

If, in the github-webhook application, you mark all of your dependencies as optional, +when you include the github-webhook stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded.

Create a separate artifactid for the stubs

If you create a separate artifactid, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all.

Exclude dependencies on the consumer side

As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies.

4.4 Scenarios

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example:

my_contracts_dir\
+  scenario1\
+    1_login.groovy
+    2_showCart.groovy
+    3_logout.groovy

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps:

  1. login marked as Started pointing to…​
  2. showCart marked as Step1 pointing to…​
  3. logout marked as Step2 which will close the scenario.

More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

4.5 Docker Project

We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application.

[Tip]Tip

The EXPLICIT mode means that the tests generated from contracts will send +real requests and not the mocked ones.

4.5.1 Short intro to Maven, JARs and Binary storage

Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults.

Part of the following definitions were taken from the Maven Glossary

  • Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects.
  • Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group.
  • JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file.
  • GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/.
  • Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier.
  • Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus.

4.5.2 How it works

The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes).

It’s enough for you to mount your contracts, pass the environment variables + and the image will:

  • generate the contract tests
  • execute the tests against the provided URL
  • generate the WireMock stubs
  • (optional - turned on by default) publish the stubs to a Artifact Manager

Environment Variables

The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc.

  • PROJECT_GROUP - your project’s group id. Defaults to com.example
  • PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT
  • PROJECT_NAME - artifact id. Defaults to example
  • REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally
  • REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured
  • REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured
  • PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

  • EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example
  • EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.
  • EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default
  • EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest
  • EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally
  • EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.
  • EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

These environment variables are used when tests are executed:

  • APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work)
  • APPLICATION_USERNAME - (optional) username for basic authentication to your application
  • APPLICATION_PASSWORD - (optional) password for basic authentication to your application

4.5.3 Example of usage

Let’s take a look at a simple MVC application

$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore

The contracts are available under /contracts folder.

4.5.4 Server side (nodejs)

Since we want to run tests, we could just execute:

$ npm test

however, for learning purposes, let’s split it into pieces:

# Stop docker infra (nodejs, artifactory)
+$ ./stop_infra.sh
+# Start docker infra (nodejs, artifactory)
+$ ./setup_infra.sh
+
+# Kill & Run app
+$ pkill -f "node app"
+$ nohup node app &
+
+# Prepare environment variables
+$ SC_CONTRACT_DOCKER_VERSION="..."
+$ APP_IP="192.168.0.100"
+$ APP_PORT="3000"
+$ ARTIFACTORY_PORT="8081"
+$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
+$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
+$ CURRENT_DIR="$( pwd )"
+$ CURRENT_FOLDER_NAME=${PWD##*/}
+$ PROJECT_VERSION="0.0.1.RELEASE"
+
+# Execute contract tests
+$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
+
+# Kill app
+$ pkill -f "node app"

What will happen is that via bash scripts:

  • infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time.
  • due to those constraints the contracts also represent the +stateful situation

    • first request is a POST that causes data to get inserted to the database
    • second request is a GET that returns a list of data with 1 previously inserted element
  • the NodeJS application will be started (on port 3000)
  • contract tests will be generated via Docker and tests +will be executed against the running application

    • the contracts will be taken from /contracts folder.
    • the output of the test execution is available under +node_modules/spring-cloud-contract/output.
  • the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

To see how the client side looks like check out the Section 6.9, “Stub Runner Docker” section.

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_wiremock.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_wiremock.html new file mode 100644 index 00000000..9f41cedc --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__spring_cloud_contract_wiremock.html @@ -0,0 +1,323 @@ + + + 11. Spring Cloud Contract WireMock

11. Spring Cloud Contract WireMock

The Spring Cloud Contract WireMock modules let you use WireMock in a +Spring Boot application. Check out the +samples +for more details.

If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with spring-boot-starter-web), you can add +spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public class WiremockForDocsTests {
+
+	// A service that calls out over HTTP
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:"
+				+ this.environment.getProperty("wiremock.server.port"));
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}

To start the stub server on a different port use (for example), +@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

11.1 Registering Stubs Automatically

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +system or classpath (by default, from file:src/test/resources/mappings). You can +customize the locations using the stubs attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, */.json is +appended. The following code shows an example:

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureWireMock(stubs="classpath:/stubs")
+public class WiremockImportApplicationTests {
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
[Note]Note

Actually, WireMock always loads mappings from src/test/resources/mappings as +well as the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document.

If you’re using Spring Cloud Contract’s default stub jars, then your +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")

11.2 Using Files to Specify the Stub Bodies

WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a bodyFileName instead of a +(literal) body. The files are resolved relative to a root directory (by default, +src/test/resources/__files). To customize this location you can set the files +attribute in the @AutoConfigureWireMock annotation to the location of the parent +directory (in other words, __files is a subdirectory). You can use Spring resource +notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body.

[Note]Note

When you configure the files root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of files has no +effect on the stubs loaded explicitly from the stubs attribute.

11.3 Alternative: Using JUnit Rules

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +the server. To do so, use the WireMockSpring convenience class to obtain an Options +instance, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class WiremockForDocsClassRuleTests {
+
+	// Start WireMock on some dynamic port
+	// for some reason `dynamicPort()` is not working properly
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().dynamicPort());
+
+	// A service that calls out over HTTP to wiremock's port
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:" + wiremock.port());
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}

The @ClassRule means that the server shuts down after all the methods in this class +have been run.

11.4 Relaxed SSL Validation for Rest Template

WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that’s not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course).

To make this work with minimum fuss, you need to be using the Spring Boot +RestTemplateBuilder in your app, as shown in the following example:

@Bean
+public RestTemplate restTemplate(RestTemplateBuilder builder) {
+	return builder.build();
+}

You need RestTemplateBuilder because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the @AutoConfigureWireMock +annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the +@AutoConfigureHttpClient annotation as well, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest("app.baseUrl=https://localhost:6443")
+@AutoConfigureHttpClient
+public class WiremockHttpsServerApplicationTests {
+
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().httpsPort(6443));
+...
+}

If you are using spring-boot-starter-test, you have the Apache HTTP client on the +classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL +errors. If you use the default java.net client, you do not need the annotation (but it +won’t do any harm). There is no support currently for other clients, but it may be added +in future releases.

To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled +property to false.

11.5 WireMock and Spring MVC Mocks

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring MockRestServiceServer. The following code shows an example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+public class WiremockForDocsMockServerApplicationTests {
+
+	@Autowired
+	private RestTemplate restTemplate;
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		// will read stubs classpath
+		MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
+				.baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
+				.build();
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World");
+		server.verify();
+	}
+
+}

The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to +visit https://example.org/, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +WireMock website.

Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one).

11.6 Customization of WireMock configuration

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +in order to customize the WireMock configuration (e.g. add custom transformers). +Example:

		@Bean
+		WireMockConfigurationCustomizer optionsCustomizer() {
+			return new WireMockConfigurationCustomizer() {
+				@Override
+				public void customize(WireMockConfiguration options) {
+// perform your customization here
+				}
+			};
+		}

11.7 Generating Stubs using REST Docs

Spring REST Docs can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc +or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example using MockMvc:

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(get("/resource"))
+				.andExpect(content().string("Hello World"))
+				.andDo(document("resource"));
+	}
+}

This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. The same example with WebTestClient (used +for testing Spring WebFlux applications) would look like this:

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureWebTestClient
+public class ApplicationTests {
+
+	@Autowired
+	private WebTestClient client;
+
+	@Test
+	public void contextLoads() throws Exception {
+		client.get().uri("/resource").exchange()
+				.expectBody(String.class).isEqualTo("Hello World")
+ 				.consumeWith(document("resource"));
+	}
+}

Without any additional configuration, these tests create a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects:

  • Creating a stub that matches only in the way you specify.
  • Asserting that the request in the test case also matches the same conditions.

The main entry point for this feature is WireMockRestDocs.verify(), which can be used +as a substitute for the document() convenience method, as shown in the following +example:

import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(post("/resource")
+                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+				.andExpect(status().isOk())
+				.andDo(verify().jsonPath("$.id")
+                        .stub("resource"));
+	}
+}

This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to .jsonPath() to add additional +matchers. If JSON Path is unfamiliar, The JayWay +documentation can help you get up to speed. The WebTestClient version of this test +has a similar verify() static helper that you insert in the same place.

Instead of the jsonPath and contentType convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example:

@Test
+public void contextLoads() throws Exception {
+	mockMvc.perform(post("/resource")
+               .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+			.andExpect(status().isOk())
+			.andDo(verify()
+					.wiremock(WireMock.post(
+						urlPathEquals("/resource"))
+						.withRequestBody(matchingJsonPath("$.id"))
+                       .stub("post-resource"));
+}

The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example:

post-resource.json.  +

{
+  "request" : {
+    "url" : "/resource",
+    "method" : "POST",
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.id"
+    }]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "Hello World",
+    "headers" : {
+      "X-Application-Context" : "application:-1",
+      "Content-Type" : "text/plain"
+    }
+  }
+}

+

[Note]Note

You can use either the wiremock() method or the jsonPath() and contentType() +methods to create request matchers, but you can’t use both approaches.

On the consumer side, you can make the resource.json generated earlier in this section +available on the classpath (by +<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this +document.

11.8 Generating Contracts by Using REST Docs

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs.

Why would you want to use this feature? Some people in the community asked questions +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them.

[Tip]Tip

You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs.

Consider the following test:

		this.mockMvc
+				.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
+						.accept(MediaType.APPLICATION_JSON)
+						.contentType(MediaType.APPLICATION_JSON)
+						.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
+				.andExpect(status().isOk()).andExpect(content().string("bar"))
+				// first WireMock
+				.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
+						.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
+						.contentType(MediaType.valueOf("application/json"))
+						.stub("shouldGrantABeerIfOldEnough"))
+				// then Contract DSL documentation
+				.andDo(document("index", SpringCloudContractRestDocs.dslContract()));

The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file.

The contract is called index.groovy and might look like the following example:

import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+    request {
+        method 'POST'
+        url '/foo'
+        body('''
+            {"foo": 23 }
+        ''')
+        headers {
+            header('''Accept''', '''application/json''')
+            header('''Content-Type''', '''application/json''')
+        }
+    }
+    response {
+        status OK()
+        body('''
+        bar
+        ''')
+        headers {
+            header('''Content-Type''', '''application/json;charset=UTF-8''')
+            header('''Content-Length''', '''3''')
+        }
+        testMatchers {
+            jsonPath('$[?(@.foo >= 20)]', byType())
+        }
+    }
+}

The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be index/dsl-contract.adoc.

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi__using_the_pluggable_architecture.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__using_the_pluggable_architecture.html new file mode 100644 index 00000000..77fcf95c --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi__using_the_pluggable_architecture.html @@ -0,0 +1,471 @@ + + + 10. Using the Pluggable Architecture

10. Using the Pluggable Architecture

You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations).

10.1 Custom Contract Converter

The ContractConverter interface lets you register your own implementation of a contract +structure converter. The following code listing shows the ContractConverter interface:

package org.springframework.cloud.contract.spec
+
+/**
+ * Converter to be used to convert FROM {@link File} TO {@link Contract}
+ * and from {@link Contract} to {@code T}
+ *
+ * @param <T >     - type to which we want to convert the contract
+ *
+ * @author Marcin Grzejszczak
+ * @since 1.1.0
+ */
+interface ContractConverter<T> extends ContractStorer<T> {
+
+	/**
+	 * Should this file be accepted by the converter. Can use the file extension
+	 * to check if the conversion is possible.
+	 *
+	 * @param file - file to be considered for conversion
+	 * @return - {@code true} if the given implementation can convert the file
+	 */
+	boolean isAccepted(File file)
+
+	/**
+	 * Converts the given {@link File} to its {@link Contract} representation
+	 *
+	 * @param file - file to convert
+	 * @return - {@link Contract} representation of the file
+	 */
+	Collection<Contract> convertFrom(File file)
+
+	/**
+	 * Converts the given {@link Contract} to a {@link T} representation
+	 *
+	 * @param contract - the parsed contract
+	 * @return - {@link T} the type to which we do the conversion
+	 */
+	T convertTo(Collection<Contract> contract)
+}

Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions.

[Important]Important

Once you create your implementation, you must create a +/META-INF/spring.factories file in which you provide the fully qualified name of your +implementation.

The following example shows a typical spring.factories file:

org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.verifier.converter.YamlContractConverter

10.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of +contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used.

In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

  • to define the destination to which a message gets sent, you have to +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

10.1.2 Pact Contract

Consider following example of a Pact contract, which is a file under the +src/test/resources/contracts folder.

{
+  "provider": {
+    "name": "Provider"
+  },
+  "consumer": {
+    "name": "Consumer"
+  },
+  "interactions": [
+    {
+      "description": "",
+      "request": {
+        "method": "PUT",
+        "path": "/fraudcheck",
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "clientId": "1234567890",
+          "loanAmount": 99999
+        },
+        "generators": {
+          "body": {
+            "$.clientId": {
+              "type": "Regex",
+              "regex": "[0-9]{10}"
+            }
+          }
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.clientId": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "[0-9]{10}"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      },
+      "response": {
+        "status": 200,
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json;charset=UTF-8"
+        },
+        "body": {
+          "fraudCheckStatus": "FRAUD",
+          "rejectionReason": "Amount too high"
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.fraudCheckStatus": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "FRAUD"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      }
+    }
+  ],
+  "metadata": {
+    "pact-specification": {
+      "version": "3.0.0"
+    },
+    "pact-jvm": {
+      "version": "3.5.13"
+    }
+  }
+}

The remainder of this section about using Pact refers to the preceding file.

10.1.3 Pact for Producers

On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use.

Maven.  +

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-contract-pact</artifactId>
+			<version>${spring-cloud-contract.version}</version>
+		</dependency>
+	</dependencies>
+</plugin>

+

Gradle.  +

classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"

+

When you execute the build of your application, a test will be generated. The generated +test might be as follows:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+	// given:
+		MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/vnd.fraud.v1+json")
+				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
+
+	// when:
+		ResponseOptions response = given().spec(request)
+				.put("/fraudcheck");
+
+	// then:
+		assertThat(response.statusCode()).isEqualTo(200);
+		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
+	// and:
+		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
+	// and:
+		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
+}

The corresponding generated stub might be as follows:

{
+  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "request" : {
+    "url" : "/fraudcheck",
+    "method" : "PUT",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
+    "headers" : {
+      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
+    },
+    "transformers" : [ "response-template" ]
+  },
+}

10.1.4 Pact for Consumers

On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use.

Maven.  +

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-pact</artifactId>
+	<scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile "org.springframework.cloud:spring-cloud-contract-pact"

+

10.2 Using the Custom Test Generator

If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation.

The SingleTestGenerator interface lets you register your own implementation. The +following code listing shows the SingleTestGenerator interface:

package org.springframework.cloud.contract.verifier.builder
+
+
+import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties
+import org.springframework.cloud.contract.verifier.file.ContractMetadata
+
+/**
+ * Builds a single test.
+ *
+ * @since 1.1.0
+ */
+trait SingleTestGenerator {
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from
+	 * the contract metadata should be placed.
+	 *
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param className - the name of the generated test class
+	 * @param classPackage - the name of the package in which the test class should be stored
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
+	 */
+	@Deprecated
+	abstract String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles, String className, String classPackage, String includedDirectoryRelativePath)
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from
+	 * the contract metadata should be placed.
+	 *
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param generatedClassData - information about the generated class
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 */
+	String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles, String includedDirectoryRelativePath, GeneratedClassData generatedClassData) {
+		String className = generatedClassData.className
+		String classPackage = generatedClassData.classPackage
+		String path = includedDirectoryRelativePath
+		return buildClass(properties, listOfFiles, className, classPackage, path)
+	}
+
+	/**
+	 * Extension that should be appended to the generated test class. E.g. {@code .java} or {@code .php}
+	 *
+	 * @param properties - properties passed to the plugin
+	 */
+	abstract String fileExtension(ContractVerifierConfigProperties properties)
+
+	static class GeneratedClassData {
+		public final String className
+		public final String classPackage
+		public final java.nio.file.Path testClassPath
+
+		GeneratedClassData(String className, String classPackage,
+				java.nio.file.Path testClassPath) {
+			this.className = className
+			this.classPackage = classPackage
+			this.testClassPath = testClassPath
+		}
+	}
+}

Again, you must provide a spring.factories file, such as the one shown in the following +example:

org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
+com.example.MyGenerator

10.3 Using the Custom Stub Generator

If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the StubGenerator interface. The following code listing shows the +StubGenerator interface:

package org.springframework.cloud.contract.verifier.converter
+
+import groovy.transform.CompileStatic
+
+import org.springframework.cloud.contract.spec.Contract
+import org.springframework.cloud.contract.verifier.file.ContractMetadata
+
+/**
+ * Converts contracts into their stub representation.
+ *
+ * @since 1.1.0
+ */
+@CompileStatic
+interface StubGenerator {
+
+	/**
+	 * @return {@code true} if the converter can handle the file to convert it into a stub.
+	 */
+	boolean canHandleFileName(String fileName)
+
+	/**
+	 * @return the collection of converted contracts into stubs. One contract can
+	 * result in multiple stubs.
+	 */
+	Map<Contract, String> convertContents(String rootName, ContractMetadata content)
+
+	/**
+	 * @return the name of the converted stub file. If you have multiple contracts
+	 * in a single file then a prefix will be added to the generated file. If you
+	 * provide the {@link Contract#name} field then that field will override the
+	 * generated file name.
+	 *
+	 * Example: name of file with 2 contracts is {@code foo.groovy}, it will be
+	 * converted by the implementation to {@code foo.json}. The recursive file
+	 * converter will create two files {@code 0_foo.json} and {@code 1_foo.json}
+	 */
+	String generateOutputFileNameForInput(String inputFileName)
+}

Again, you must provide a spring.factories file, such as the one shown in the following +example:

# Stub converters
+org.springframework.cloud.contract.verifier.converter.StubGenerator=\
+org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter

The default implementation is the WireMock stub generation.

[Tip]Tip

You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files.

10.4 Using the Custom Stub Runner

If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider.

Assume that you use Moco to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file.

In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example:

package org.springframework.cloud.contract.stubrunner.provider.moco
+
+import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
+import com.github.dreamhead.moco.runner.JsonRunner
+import com.github.dreamhead.moco.runner.RunnerSetting
+import groovy.util.logging.Commons
+
+import org.springframework.cloud.contract.stubrunner.HttpServerStub
+import org.springframework.util.SocketUtils
+
+@Commons
+class MocoHttpServerStub implements HttpServerStub {
+
+	private boolean started
+	private JsonRunner runner
+	private int port
+
+	@Override
+	int port() {
+		if (!isRunning()) {
+			return -1
+		}
+		return port
+	}
+
+	@Override
+	boolean isRunning() {
+		return started
+	}
+
+	@Override
+	HttpServerStub start() {
+		return start(SocketUtils.findAvailableTcpPort())
+	}
+
+	@Override
+	HttpServerStub start(int port) {
+		this.port = port
+		return this
+	}
+
+	@Override
+	HttpServerStub stop() {
+		if (!isRunning()) {
+			return this
+		}
+		this.runner.stop()
+		return this
+	}
+
+	@Override
+	HttpServerStub registerMappings(Collection<File> stubFiles) {
+		List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
+			.collect {
+			log.info("Trying to parse [${it.name}]")
+			try {
+				return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()).
+					build()
+			}
+			catch (Exception e) {
+				log.warn("Exception occurred while trying to parse file [${it.name}]", e)
+				return null
+			}
+		}.findAll { it }
+		this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
+			HttpArgs.httpArgs().withPort(this.port).build())
+		this.runner.run()
+		this.started = true
+		return this
+	}
+
+	@Override
+	String registeredMappings() {
+		return ""
+	}
+
+	@Override
+	boolean isAccepted(File file) {
+		return file.name.endsWith(".json")
+	}
+}

Then, you can register it in your spring.factories file, as shown in the following +example:

org.springframework.cloud.contract.stubrunner.HttpServerStub=\
+org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub

Now you can run stubs with Moco.

[Important]Important

If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used.

10.5 Using the Custom Stub Downloader

You can customize the way your stubs are downloaded by creating an implementation of the +StubDownloaderBuilder interface, as shown in the following example:

package com.example;
+
+class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
+
+	@Override
+	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
+		return new StubDownloader() {
+			@Override
+			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
+					StubConfiguration config) {
+				File unpackedStubs = retrieveStubs();
+				return new AbstractMap.SimpleEntry<>(
+						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
+								config.getClassifier()), unpackedStubs);
+			}
+
+			File retrieveStubs() {
+			    // here goes your custom logic to provide a folder where all the stubs reside
+			}
+}

Then you can register it in your spring.factories file, as shown in the following +example:

# Example of a custom Stub Downloader Provider
+org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
+com.example.CustomStubDownloaderBuilder

Now you can pick a folder with the source of your stubs.

[Important]Important

If you do not provide any implementation, then the default is used (scan classpath). +If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or +, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used +If you provide more than one, then the first one on the list is used.

10.6 Using the SCM Stub Downloader

Whenever the repositoryRoot starts with a SCM protocol +(currently we support only git://), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs.

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

Table 10.1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

* stubrunner.properties.git.branch (system prop)

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

* stubrunner.properties.git.username (system prop)

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

 

Git clone username

* git.password (plugin prop)

* stubrunner.properties.git.password (system prop)

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

 

Git clone password

* git.no-of-attempts (plugin prop)

* stubrunner.properties.git.no-of-attempts (system prop)

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

* stubrunner.properties.git.wait-between-attempts (system prop)

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin


10.7 Using the Pact Stub Downloader

Whenever the repositoryRoot starts with a Pact protocol +(starts with pact://), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after pact:// will be parsed as the Pact Broker URL.

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

Table 10.2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

* stubrunner.properties.pactbroker.host (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

* stubrunner.properties.pactbroker.port (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

* stubrunner.properties.pactbroker.protocol (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

* stubrunner.properties.pactbroker.tags (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

* stubrunner.properties.pactbroker.auth.scheme (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

* stubrunner.properties.pactbroker.auth.username (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

* stubrunner.properties.pactbroker.auth.password (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used


\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi_contract-dsl.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_contract-dsl.html new file mode 100644 index 00000000..57c00e4e --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_contract-dsl.html @@ -0,0 +1,2208 @@ + + + 8. Contract DSL

8. Contract DSL

Spring Cloud Contract supports out of the box 2 types of DSL. One written in +Groovy and one written in YAML.

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself.

[Important]Important

Remember that, inside the Groovy contract file, you have to provide the fully +qualified name to the Contract class and make static imports, such as +org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to +the Contract class: import org.springframework.cloud.spec.Contract and then call +Contract.make { …​ }.

[Tip]Tip

Spring Cloud Contract supports defining multiple contracts in a single file.

The following is a complete example of a Groovy contract definition:

The following is a complete example of a YAML contract definition:

description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
[Tip]Tip

You can compile contracts to stubs mapping using standalone maven command: +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert

8.1 Limitations

[Warning]Warning

Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature.

[Warning]Warning

The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to true: +spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. +You can also provide the assertJsonSize property in the plugin configuration.

[Warning]Warning

Because JSON structure can have any form, it can be impossible to parse it +properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That +is why you should use the Groovy Map notation.

8.2 Common Top-Level elements

The following sections describe the most common top-level elements:

8.2.1 Description

You can add a description to your contract. The description is arbitrary text. The +following code shows an example:

Groovy DSL.  +

			org.springframework.cloud.contract.spec.Contract.make {
+				description('''
+given:
+	An input
+when:
+	Sth happens
+then:
+	Output
+''')
+			}

+

YAML.  +

description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)

+

8.2.2 Name

You can provide a name for your contract. Assume that you provided the following name: +should register a user. If you do so, the name of the autogenerated test is +validate_should_register_a_user. Also, the name of the stub in a WireMock stub is +should_register_a_user.json.

[Important]Important

You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	name("some_special_name")
+}

+

YAML.  +

name: some name

+

8.2.3 Ignoring Contracts

If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the ignored property on the contract itself:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	ignored()
+}

+

YAML.  +

ignored: true

+

8.2.4 Passing Values from Files

Starting with version 1.2.0, you can pass values from files. Assume that you have the +following resources in our project.

└── src
+    └── test
+        └── resources
+            └── contracts
+                ├── readFromFile.groovy
+                ├── request.json
+                └── response.json

Further assume that your contract is as follows:

Groovy DSL.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		method('PUT')
+		headers {
+			contentType(applicationJson())
+		}
+		body(file("request.json"))
+		url("/1")
+	}
+	response {
+		status OK()
+		body(file("response.json"))
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}

+

YAML.  +

request:
+  method: GET
+  url: /foo
+  bodyFromFile: request.json
+response:
+  status: 200
+  bodyFromFile: response.json

+

Further assume that the JSON files is as follows:

request.json

{
+  "status": "REQUEST"
+}

response.json

{
+  "status": "RESPONSE"
+}

When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. The name of the file needs to be a file with location +relative to the folder in which the contract lays.

If you need to pass the contents of a file in a binary form +it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

Groovy DSL.  +

import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		url("/1")
+		method(PUT())
+		headers {
+			contentType(applicationOctetStream())
+		}
+		body(fileAsBytes("request.pdf"))
+	}
+	response {
+		status 200
+		body(fileAsBytes("response.pdf"))
+		headers {
+			contentType(applicationOctetStream())
+		}
+	}
+}

+

YAML.  +

request:
+  url: /1
+  method: PUT
+  headers:
+    Content-Type: application/octet-stream
+  bodyFromFileAsBytes: request.pdf
+response:
+  status: 200
+  bodyFromFileAsBytes: response.pdf
+  headers:
+    Content-Type: application/octet-stream

+

[Important]Important

You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.

8.2.5 HTTP Top-Level Elements

The following methods can be called in the top-level closure of a contract definition. +request and response are mandatory. priority is optional.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	// Definition of HTTP request part of the contract
+	// (this can be a valid request or invalid depending
+	// on type of contract being specified).
+	request {
+		method GET()
+		url "/foo"
+		//...
+	}
+
+	// Definition of HTTP response part of the contract
+	// (a service implementing this contract should respond
+	// with following response after receiving request
+	// specified in "request" part above).
+	response {
+		status 200
+		//...
+	}
+
+	// Contract priority, which can be used for overriding
+	// contracts (1 is highest). Priority is optional.
+	priority 1
+}

+

YAML.  +

priority: 8
+request:
+...
+response:
+...

+

[Important]Important

If you want to make your contract have a higher value of priority +you need to pass a lower number to the priority tag / method. E.g. priority with +value 5 has higher priority than priority with value 10.

8.3 Request

The HTTP protocol requires only method and url to be specified in a request. The +same information is mandatory in request definition of the Contract.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		// HTTP request method (GET/POST/PUT/DELETE).
+		method 'GET'
+
+		// Path component of request URL is specified as follows.
+		urlPath('/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

method: PUT
+url: /foo

+

It is possible to specify an absolute rather than relative url, but using urlPath is +the recommended way, as doing so makes the tests host-independent.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+
+		// Specifying `url` and `urlPath` in one contract is illegal.
+		url('http://localhost:8888/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+  method: PUT
+  urlPath: /foo

+

request may contain query parameters.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+
+		urlPath('/users') {
+
+			// Each parameter is specified in form
+			// `'paramName' : paramValue` where parameter value
+			// may be a simple literal or one of matcher functions,
+			// all of which are used in this example.
+			queryParameters {
+
+				// If a simple literal is used as value
+				// default matcher function is used (equalTo)
+				parameter 'limit': 100
+
+				// `equalTo` function simply compares passed value
+				// using identity operator (==).
+				parameter 'filter': equalTo("email")
+
+				// `containing` function matches strings
+				// that contains passed substring.
+				parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
+
+				// `matching` function tests parameter
+				// against passed regular expression.
+				parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
+
+				// `notMatching` functions tests if parameter
+				// does not match passed regular expression.
+				parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
+			}
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+  queryParameters:
+    a: b
+    b: c
+  headers:
+    foo: bar
+    fooReq: baz
+  cookies:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  fixedDelayMilliseconds: 1000
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+    cookies:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        predefined:

+

request may contain additional request headers, as shown in the following example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each header is added in form `'Header-Name' : 'Header-Value'`.
+		// there are also some helper methods
+		headers {
+			header 'key': 'value'
+			contentType(applicationJson())
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+headers:
+  foo: bar
+  fooReq: baz

+

request may contain additional request cookies, as shown in the following example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
+		// there are also some helper methods
+		cookies {
+			cookie 'key': 'value'
+			cookie('another_key', 'another_value')
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+cookies:
+  foo: bar
+  fooReq: baz

+

request may contain a request body:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Currently only JSON format of request body is supported.
+		// Format will be determined from a header or body's content.
+		body '''{ "login" : "john", "name": "John The Contract" }'''
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+body:
+  foo: bar

+

request may contain multipart elements. To include multipart elements, use the +multipart method/section, as shown in the following examples

Groovy DSL.  +

+

YAML.  +

request:
+  method: PUT
+  url: /multipart
+  headers:
+    Content-Type: multipart/form-data;boundary=AaB03x
+  multipart:
+    params:
+      # key (parameter name), value (parameter value) pair
+      formParameter: '"formParameterValue"'
+      someBooleanParameter: true
+    named:
+      - paramName: file
+        fileName: filename.csv
+        fileContent: file content
+  matchers:
+    multipart:
+      params:
+        - key: formParameter
+          regex: ".+"
+        - key: someBooleanParameter
+          predefined: any_boolean
+      named:
+        - paramName: file
+          fileName:
+            predefined: non_empty
+          fileContent:
+            predefined: non_empty
+response:
+  status: 200

+

In the preceding example, we define parameters in either of two ways:

Groovy DSL

  • Directly, by using the map notation, where the value can be a dynamic property (such as +formParameter: $(consumer(…​), producer(…​))).
  • By using the named(…​) method that lets you set a named parameter. A named parameter +can set a name and content. You can call it either via a method with two arguments, +such as named("fileName", "fileContent"), or via a map notation, such as +named(name: "fileName", content: "fileContent").

YAML

  • The multipart parameters are set via multipart.params section
  • The named parameters (the fileName and fileContent for a given parameter name) +can be set via the multipart.named section. That section contains +the paramName (name of the parameter), fileName (name of the file), +fileContent (content of the file) fields
  • The dynamic bits can be set via the matchers.multipart section

    • for parameters use the params section that can accept +regex or a predefined regular expression
    • for named params use the named section where first you +define the parameter name via paramName and then you can pass the +parametrization of either fileName or fileContent via +regex or a predefined regular expression

From this contract, the generated test is as follows:

// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
+   .param("formParameter", "\"formParameterValue\"")
+   .param("someBooleanParameter", "true")
+   .multiPart("file", "filename.csv", "file content".getBytes());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .put("/multipart");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);

The WireMock stub is as follows:

			'''
+{
+  "request" : {
+	"url" : "/multipart",
+	"method" : "PUT",
+	"headers" : {
+	  "Content-Type" : {
+		"matches" : "multipart/form-data;boundary=AaB03x.*"
+	  }
+	},
+	"bodyPatterns" : [ {
+		"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
+  		}, {
+    			"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
+  		}, {
+	  "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
+	} ]
+  },
+  "response" : {
+	"status" : 200,
+	"transformers" : [ "response-template", "foo-transformer" ]
+  }
+}
+	'''

8.4 Response

The response must contain an HTTP status code and may contain other information. The +following code shows an example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+	}
+	response {
+		// Status code sent by the server
+		// in response to request specified above.
+		status OK()
+	}
+}

+

YAML.  +

response:
+...
+status: 200

+

Besides status, the response may contain headers, cookies and a body, both of which are +specified the same way as in the request (see the previous paragraph).

[Tip]Tip

Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus +methods to provide a meaningful status instead of a digit. E.g. you can call +OK() for a status 200 or BAD_REQUEST() for 400.

8.5 Dynamic properties

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub.

For Groovy DSL you can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in a separate section called +bodyMatchers.

[Note]Note

Before 2.0.0 these were set using testMatchers and stubMatchers, +check out the migration guide for more information.

For YAML you can only use the matchers section.

8.5.1 Dynamic properties inside the body

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can set the properties inside the body either with the value method or, if you use +the Groovy map notation, with $(). The following example shows how to set dynamic +properties with the value method:

value(consumer(...), producer(...))
+value(c(...), p(...))
+value(stub(...), test(...))
+value(client(...), server(...))

The following example shows how to set dynamic properties with $():

$(consumer(...), producer(...))
+$(c(...), p(...))
+$(stub(...), test(...))
+$(client(...), server(...))

Both approaches work equally well. stub and client methods are aliases over the consumer +method. Subsequent sections take a closer look at what you can do with those values.

8.5.2 Regular expressions

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests.

The following example shows how to use regular expressions to write a request:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method('GET')
+		url $(consumer(~/\/[0-9]{2}/), producer('/12'))
+	}
+	response {
+		status OK()
+		body(
+				id: $(anyNumber()),
+				surname: $(
+						consumer('Kowalsky'),
+						producer(regex('[a-zA-Z]+'))
+				),
+				name: 'Jan',
+				created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
+				correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
+						producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'))
+				)
+		)
+		headers {
+			header 'Content-Type': 'text/plain'
+		}
+	}
+}

You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url value(consumer(regex('/foo/[0-9]{5}')))
+		body([
+				requestElement: $(consumer(regex('[0-9]{5}')))
+		])
+		headers {
+			header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
+		}
+	}
+	response {
+		status OK()
+		body([
+				responseElement: $(producer(regex('[0-9]{7}')))
+		])
+		headers {
+			contentType("application/vnd.fraud.v1+json")
+		}
+	}
+}

In the preceding example, the opposite side of the communication has the respective data +generated for request and response.

Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example:

protected static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/)
+protected static final Pattern ALPHA_NUMERIC = Pattern.compile('[a-zA-Z0-9]+')
+protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile(/[\p{L}]*/)
+protected static final Pattern NUMBER = Pattern.compile('-?(\\d*\\.\\d+|\\d+)')
+protected static final Pattern INTEGER = Pattern.compile('-?(\\d+)')
+protected static final Pattern POSITIVE_INT = Pattern.compile('([1-9]\\d*)')
+protected static final Pattern DOUBLE = Pattern.compile('-?(\\d*\\.\\d+)')
+protected static final Pattern HEX = Pattern.compile('[a-fA-F0-9]+')
+protected static final Pattern IP_ADDRESS = Pattern.
+		compile('([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])')
+protected static final Pattern HOSTNAME_PATTERN = Pattern.
+		compile('((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?')
+protected static final Pattern EMAIL = Pattern.
+		compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}')
+protected static final Pattern URL = UrlHelper.URL
+protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL
+protected static final Pattern UUID = Pattern.
+		compile('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}')
+protected static final Pattern ANY_DATE = Pattern.
+		compile('(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])')
+protected static final Pattern ANY_DATE_TIME = Pattern.
+		compile('([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])')
+protected static final Pattern ANY_TIME = Pattern.
+		compile('(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])')
+protected static final Pattern NON_EMPTY = Pattern.compile(/[\S\s]+/)
+protected static final Pattern NON_BLANK = Pattern.compile(/^\s*\S[\S\s]*/)
+protected static final Pattern ISO8601_WITH_OFFSET = Pattern.
+		compile(/([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.\d{3})?(Z|[+-][01]\d:[0-5]\d)/)
+
+protected static Pattern anyOf(String... values) {
+	return Pattern.compile(values.collect({ "^$it\$" }).join("|"))
+}
+
+RegexProperty onlyAlphaUnicode() {
+	return new RegexProperty(ONLY_ALPHA_UNICODE).asString()
+}
+
+RegexProperty alphaNumeric() {
+	return new RegexProperty(ALPHA_NUMERIC).asString()
+}
+
+RegexProperty number() {
+	return new RegexProperty(NUMBER).asDouble()
+}
+
+RegexProperty positiveInt() {
+	return new RegexProperty(POSITIVE_INT).asInteger()
+}
+
+RegexProperty anyBoolean() {
+	return new RegexProperty(TRUE_OR_FALSE).asBooleanType()
+}
+
+RegexProperty anInteger() {
+	return new RegexProperty(INTEGER).asInteger()
+}
+
+RegexProperty aDouble() {
+	return new RegexProperty(DOUBLE).asDouble()
+}
+
+RegexProperty ipAddress() {
+	return new RegexProperty(IP_ADDRESS).asString()
+}
+
+RegexProperty hostname() {
+	return new RegexProperty(HOSTNAME_PATTERN).asString()
+}
+
+RegexProperty email() {
+	return new RegexProperty(EMAIL).asString()
+}
+
+RegexProperty url() {
+	return new RegexProperty(URL).asString()
+}
+
+RegexProperty httpsUrl() {
+	return new RegexProperty(HTTPS_URL).asString()
+}
+
+RegexProperty uuid() {
+	return new RegexProperty(UUID).asString()
+}
+
+RegexProperty isoDate() {
+	return new RegexProperty(ANY_DATE).asString()
+}
+
+RegexProperty isoDateTime() {
+	return new RegexProperty(ANY_DATE_TIME).asString()
+}
+
+RegexProperty isoTime() {
+	return new RegexProperty(ANY_TIME).asString()
+}
+
+RegexProperty iso8601WithOffset() {
+	return new RegexProperty(ISO8601_WITH_OFFSET).asString()
+}
+
+RegexProperty nonEmpty() {
+	return new RegexProperty(NON_EMPTY).asString()
+}
+
+RegexProperty nonBlank() {
+	return new RegexProperty(NON_BLANK).asString()
+}

In your contract, you can use it as shown in the following example:

Contract dslWithOptionalsInString = Contract.make {
+	priority 1
+	request {
+		method POST()
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123"))),
+				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
+		)
+	}
+}

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. +All of those methods start with any prefix:

T anyAlphaUnicode()
+
+T anyAlphaNumeric()
+
+T anyNumber()
+
+T anyInteger()
+
+T anyPositiveInt()
+
+T anyDouble()
+
+T anyHex()
+
+T aBoolean()
+
+T anyIpAddress()
+
+T anyHostname()
+
+T anyEmail()
+
+T anyUrl()
+
+T anyHttpsUrl()
+
+T anyUuid()
+
+T anyDate()
+
+T anyDateTime()
+
+T anyTime()
+
+T anyIso8601WithOffset()
+
+T anyNonBlankString()
+
+T anyNonEmptyString()
+
+T anyOf(String... values)

and this is an example of how you can reference those methods:

Contract contractDsl = Contract.make {
+	label 'trigger_event'
+	input {
+		triggeredBy('toString()')
+	}
+	outputMessage {
+		sentTo 'topic.rateablequote'
+		body([
+				alpha            : $(anyAlphaUnicode()),
+				number           : $(anyNumber()),
+				anInteger        : $(anyInteger()),
+				positiveInt      : $(anyPositiveInt()),
+				aDouble          : $(anyDouble()),
+				aBoolean         : $(aBoolean()),
+				ip               : $(anyIpAddress()),
+				hostname         : $(anyHostname()),
+				email            : $(anyEmail()),
+				url              : $(anyUrl()),
+				httpsUrl         : $(anyHttpsUrl()),
+				uuid             : $(anyUuid()),
+				date             : $(anyDate()),
+				dateTime         : $(anyDateTime()),
+				time             : $(anyTime()),
+				iso8601WithOffset: $(anyIso8601WithOffset()),
+				nonBlankString   : $(anyNonBlankString()),
+				nonEmptyString   : $(anyNonEmptyString()),
+				anyOf            : $(anyOf('foo', 'bar'))
+		])
+	}
+}

8.5.3 Passing Optional Parameters

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following:

  • STUB side of the Request
  • TEST side of the Response

The following example shows how to provide optional parameters:

org.springframework.cloud.contract.spec.Contract.make {
+	priority 1
+	request {
+		method 'POST'
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			header 'Content-Type': 'application/json'
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123")))
+		)
+	}
+}

By wrapping a part of the body with the optional() method, you create a regular +expression that must be present 0 or more times.

If you use Spock for, the following test would be generated from the previous example:

					"""
+ given:
+  def request = given()
+    .header("Content-Type", "application/json")
+    .body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
+
+ when:
+  def response = given().spec(request)
+    .post("/users/password")
+
+ then:
+  response.statusCode == 404
+  response.header('Content-Type')  == 'application/json'
+ and:
+  DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+  assertThatJson(parsedJson).field("['code']").matches("(123123)?")
+"""

The following stub would also be generated:

					'''
+{
+  "request" : {
+	"url" : "/users/password",
+	"method" : "POST",
+	"bodyPatterns" : [ {
+	  "matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]"
+	}, {
+	  "matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
+	} ],
+	"headers" : {
+	  "Content-Type" : {
+		"equalTo" : "application/json"
+	  }
+	}
+  },
+  "response" : {
+	"status" : 404,
+	"body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}",
+	"headers" : {
+	  "Content-Type" : "application/json"
+	}
+  },
+  "priority" : 1
+}
+'''

8.5.4 Executing Custom Methods on the Server Side

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url $(consumer(regex('^/api/[0-9]{2}$')), producer('/api/12'))
+		headers {
+			header 'Content-Type': 'application/json'
+		}
+		body '''\
+			[{
+				"text": "Gonna see you at Warsaw"
+			}]
+		'''
+	}
+	response {
+		body(
+				path: $(consumer('/api/12'), producer(regex('^/api/[0-9]{2}$'))),
+				correlationId: $(consumer('1223456'), producer(execute('isProperCorrelationId($it)')))
+		)
+		status OK()
+	}
+}

The following code shows the base class portion of the test case:

abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
[Important]Important

You cannot use both a String and execute to perform concatenation. For +example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to +improper results. Instead, call header('Authorization', execute('authToken()')) and +ensure that the authToken() method returns everything you need.

The type of the object read from the JSON can be one of the following, depending on the +JSON path:

  • String: If you point to a String value in the JSON.
  • JSONArray: If you point to a List in the JSON.
  • Map: If you point to a Map in the JSON.
  • Number: If you point to Integer, Double etc. in the JSON.
  • Boolean: If you point to a Boolean in the JSON.

In the request part of the contract, you can specify that the body should be taken from +a method.

[Important]Important

You must provide both the consumer and the producer side. The execute part +is applied for the whole body - not for parts of it.

The following example shows how to read an object from JSON:

Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		url '/something'
+		body(
+				$(c('foo'), p(execute('hashCode()')))
+		)
+	}
+	response {
+		status OK()
+	}
+}

The preceding example results in calling the hashCode() method in the request body. +It should resemble the following code:

// given:
+ MockMvcRequestSpecification request = given()
+   .body(hashCode());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/something");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);

8.5.5 Referencing the Request from the Response

The best situation is to provide fixed values, but sometimes you need to reference a +request in your response.

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options:

  • fromRequest().url(): Returns the request URL and query parameters.
  • fromRequest().query(String key): Returns the first query parameter with a given name.
  • fromRequest().query(String key, int index): Returns the nth query parameter with a +given name.
  • fromRequest().path(): Returns the full path.
  • fromRequest().path(int index): Returns the nth path element.
  • fromRequest().header(String key): Returns the first header with a given name.
  • fromRequest().header(String key, int index): Returns the nth header with a given name.
  • fromRequest().body(): Returns the full request body.
  • fromRequest().body(String jsonPath): Returns the element from the request that +matches the JSON Path.

If you’re using the YAML contract definition you have to use the +Handlebars {{{ }}} notation with custom, Spring Cloud Contract + functions to achieve this.

  • {{{ request.url }}}: Returns the request URL and query parameters.
  • {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. +E.g. for key foo, first entry {{{ request.query.foo.[0] }}}
  • {{{ request.path }}}: Returns the full path.
  • {{{ request.path.[index] }}}: Returns the nth path element. E.g. +for first entry `{{{ request.path.[0] }}}
  • {{{ request.headers.key }}}: Returns the first header with a given name.
  • {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.
  • {{{ request.body }}}: Returns the full request body.
  • {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that +matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

Consider the following contract:

Groovy DSL.  +

+

YAML.  +

request:
+  method: GET
+  url: /api/v1/xxxx
+  queryParameters:
+    foo:
+      - bar
+      - bar2
+  headers:
+    Authorization:
+      - secret
+      - secret2
+  body:
+    foo: bar
+    baz: 5
+response:
+  status: 200
+  headers:
+    Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
+  body:
+    url: "{{{ request.url }}}"
+    path: "{{{ request.path }}}"
+    pathIndex: "{{{ request.path.1 }}}"
+    param: "{{{ request.query.foo }}}"
+    paramIndex: "{{{ request.query.foo.1 }}}"
+    authorization: "{{{ request.headers.Authorization.0 }}}"
+    authorization2: "{{{ request.headers.Authorization.1 }}"
+    fullBody: "{{{ request.body }}}"
+    responseFoo: "{{{ jsonpath this '$.foo' }}}"
+    responseBaz: "{{{ jsonpath this '$.baz' }}}"
+    responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"

+

Running a JUnit test generation leads to a test that resembles the following example:

// given:
+ MockMvcRequestSpecification request = given()
+   .header("Authorization", "secret")
+   .header("Authorization", "secret2")
+   .body("{\"foo\":\"bar\",\"baz\":5}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .queryParam("foo","bar")
+   .queryParam("foo","bar2")
+   .get("/api/v1/xxxx");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
+ assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
+ assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
+ assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
+ assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
+ assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
+ assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
+ assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
+ assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");

As you can see, elements from the request have been properly referenced in the response.

The generated WireMock stub should resemble the following example:

{
+  "request" : {
+    "urlPath" : "/api/v1/xxxx",
+    "method" : "POST",
+    "headers" : {
+      "Authorization" : {
+        "equalTo" : "secret2"
+      }
+    },
+    "queryParameters" : {
+      "foo" : {
+        "equalTo" : "bar2"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
+    "headers" : {
+      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}

Sending a request such as the one presented in the request part of the contract results +in sending the following response body:

{
+  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
+  "path" : "/api/v1/xxxx",
+  "pathIndex" : "v1",
+  "param" : "bar",
+  "paramIndex" : "bar2",
+  "authorization" : "secret",
+  "authorization2" : "secret2",
+  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
+  "responseFoo" : "bar",
+  "responseBaz" : 5,
+  "responseBaz2" : "Bla bla bar bla bla"
+}
[Important]Important

This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s +response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into +proper values. Additionally, it registers two helper functions:

  • escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.
  • jsonpath: For a given parameter, find an object in the request body.

8.5.6 Registering Your Own WireMock Extension

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. +Since we use the spring.factories extension approach, you can create an entry in +META-INF/spring.factories file similar to the following:

org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
+org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
+org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter

The following is an example of a custom extension:

TestWireMockExtensions.groovy.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package org.springframework.cloud.contract.verifier.dsl.wiremock
+
+import com.github.tomakehurst.wiremock.extension.Extension
+
+/**
+ * Extension that registers the default transformer and the custom one
+ */
+class TestWireMockExtensions implements WireMockExtensions {
+	@Override
+	List<Extension> extensions() {
+		return [
+				new DefaultResponseTransformer(),
+				new CustomExtension()
+		]
+	}
+}
+
+class CustomExtension implements Extension {
+
+	@Override
+	String getName() {
+		return "foo-transformer"
+	}
+}

+

[Important]Important

Remember to override the applyGlobally() method and set it to false if you +want the transformation to be applied only for a mapping that explicitly requires it.

8.5.7 Dynamic Properties in the Matchers Sections

If you work with Pact, the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract.

You can use the bodyMatchers section for two reasons:

  • Define the dynamic values that should end up in a stub. +You can set it in the request or inputMessage part of your contract.
  • Verify the result of your test. +This section is present in the response or outputMessage side of the +contract.

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities:

Groovy DSL

  • For the stubs(in tests on the Consumer’s side):

    • byEquality(): The value taken from the consumer’s request via the provided JSON Path must be +equal to the value provided in the contract.
    • byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must +match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)
    • byDate(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Date value.
    • byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO DateTime value.
    • byTime(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Time value.
  • For the verification(in generated tests on the Producer’s side):

    • byEquality(): The value taken from the producer’s response via the provided JSON Path must be +equal to the provided value in the contract.
    • byRegex(…​): The value taken from the producer’s response via the provided JSON Path must +match the regex.
    • byDate(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Date value.
    • byTimestamp(): The value taken from the producer’s response via the provided JSON Path must +match the regex for an ISO DateTime value.
    • byTime(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Time value.
    • byType(): The value taken from the producer’s response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the byCommand(…​) testMatcher.
    • byCommand(…​): The value taken from the producer’s response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +byCommand('foo($it)') results in calling a foo method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path:

      • String: If you point to a String value.
      • JSONArray: If you point to a List.
      • Map: If you point to a Map.
      • Number: If you point to Integer, Double, or other kind of number.
      • Boolean: If you point to a Boolean.
    • byNull(): The value taken from the response via the provided JSON Path must be null

YAML. Please read the Groovy section for detailed explanation of +what the types mean

For YAML the structure of a matcher looks like this

- path: $.foo
+  type: by_regex
+  value: bar
+  regexType: as_string

Or if you want to use one of the predefined regular expressions +[only_alpha_unicode, number, any_boolean, ip_address, hostname, +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

- path: $.foo
+  type: by_regex
+  predefined: only_alpha_unicode

Below you can find the allowed list of `type`s.

  • For stubMatchers:

    • by_equality
    • by_regex
    • by_date
    • by_timestamp
    • by_time
    • by_type

      • there are 2 additional fields accepted: minOccurrence and maxOccurrence.
  • For testMatchers:

    • by_equality
    • by_regex
    • by_date
    • by_timestamp
    • by_time
    • by_type

      • there are 2 additional fields accepted: minOccurrence and maxOccurrence.
    • by_command
    • by_null

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

  • as_integer
  • as_double
  • as_float,
  • as_long
  • as_short
  • as_boolean
  • as_string

Consider the following example:

Groovy DSL.  +

Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		urlPath '/get'
+		body([
+				duck                : 123,
+				alpha               : 'abc',
+				number              : 123,
+				aBoolean            : true,
+				date                : '2017-01-01',
+				dateTime            : '2017-01-01T01:23:45',
+				time                : '01:02:34',
+				valueWithoutAMatcher: 'foo',
+				valueWithTypeMatch  : 'string',
+				key                 : [
+						'complex.key': 'foo'
+				]
+		])
+		bodyMatchers {
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			jsonPath('$.duck', byEquality())
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+		}
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status OK()
+		body([
+				duck                 : 123,
+				alpha                : 'abc',
+				number               : 123,
+				positiveInteger      : 1234567890,
+				negativeInteger      : -1234567890,
+				positiveDecimalNumber: 123.4567890,
+				negativeDecimalNumber: -123.4567890,
+				aBoolean             : true,
+				date                 : '2017-01-01',
+				dateTime             : '2017-01-01T01:23:45',
+				time                 : "01:02:34",
+				valueWithoutAMatcher : 'foo',
+				valueWithTypeMatch   : 'string',
+				valueWithMin         : [
+						1, 2, 3
+				],
+				valueWithMax         : [
+						1, 2, 3
+				],
+				valueWithMinMax      : [
+						1, 2, 3
+				],
+				valueWithMinEmpty    : [],
+				valueWithMaxEmpty    : [],
+				key                  : [
+						'complex.key': 'foo'
+				],
+				nullValue            : null
+		])
+		bodyMatchers {
+			// asserts the jsonpath value against manual regex
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			// asserts the jsonpath value against the provided value
+			jsonPath('$.duck', byEquality())
+			// asserts the jsonpath value against some default regex
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			// asserts vs inbuilt time related regex
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			// asserts that the resulting type is the same as in response body
+			jsonPath('$.valueWithTypeMatch', byType())
+			jsonPath('$.valueWithMin', byType {
+				// results in verification of size of array (min 1)
+				minOccurrence(1)
+			})
+			jsonPath('$.valueWithMax', byType {
+				// results in verification of size of array (max 3)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinMax', byType {
+				// results in verification of size of array (min 1 & max 3)
+				minOccurrence(1)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinEmpty', byType {
+				// results in verification of size of array (min 0)
+				minOccurrence(0)
+			})
+			jsonPath('$.valueWithMaxEmpty', byType {
+				// results in verification of size of array (max 0)
+				maxOccurrence(0)
+			})
+			// will execute a method `assertThatValueIsANumber`
+			jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+			jsonPath('$.nullValue', byNull())
+		}
+		headers {
+			contentType(applicationJson())
+			header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
+		}
+	}
+}

+

YAML.  +

request:
+  method: GET
+  urlPath: /get/1
+  headers:
+    Content-Type: application/json
+  cookies:
+    foo: 2
+    bar: 3
+  queryParameters:
+    limit: 10
+    offset: 20
+    filter: 'email'
+    sort: name
+    search: 55
+    age: 99
+    name: John.Doe
+    email: 'bob@email.com'
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    key:
+      "complex.key": 'foo'
+    nullValue: null
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+  matchers:
+    url:
+      regex: /get/[0-9]
+      # predefined:
+      # execute a method
+      #command: 'equals($it)'
+    queryParameters:
+      - key: limit
+        type: equal_to
+        value: 20
+      - key: offset
+        type: containing
+        value: 20
+      - key: sort
+        type: equal_to
+        value: name
+      - key: search
+        type: not_matching
+        value: '^[0-9]{2}$'
+      - key: age
+        type: not_matching
+        value: '^\\w*$'
+      - key: name
+        type: matching
+        value: 'John.*'
+      - key: hello
+        type: absent
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: "$.['key'].['complex.key']"
+        type: by_equality
+      - path: $.nullvalue
+        type: by_null
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+response:
+  status: 200
+  cookies:
+    foo: 1
+    bar: 2
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+    key:
+      'complex.key': 'foo'
+    nulValue: null
+  matchers:
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: $.valueWithTypeMatch
+        type: by_type
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+      - path: $.valueWithMinEmpty
+        type: by_type
+        minOccurrence: 0
+      - path: $.valueWithMaxEmpty
+        type: by_type
+        maxOccurrence: 0
+      - path: $.duck
+        type: by_command
+        value: assertThatValueIsANumber($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+  headers:
+    Content-Type: application/json

+

In the preceding example, you can see the dynamic portions of the contract in the +matchers sections. For the request part, you can see that, for all fields but +valueWithoutAMatcher, the values of the regular expressions that the stub should +contain are explicitly set. For the valueWithoutAMatcher, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check.

For the response side in the bodyMatchers section, we define the dynamic parts in a +similar manner. The only difference is that the byType matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called):

  • For $.valueWithTypeMatch, the engine checks whether the type is the same.
  • For $.valueWithMin, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence.
  • For $.valueWithMax, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence.
  • For $.valueWithMinMax, the engine checks the type and asserts whether the size is +between the min and maximum occurrence.

The resulting test would resemble the following example (note that an and section +separates the autogenerated assertions and the assertion from matchers):

// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "application/json")
+   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/get");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Content-Type")).matches("application/json.*");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
+// and:
+ assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
+ assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
+ assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
+ assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
+ assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
+ assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
+ assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+ assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
+ assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
+ assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
+ assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
+ assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
+ assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
+ assertThatValueIsANumber(parsedJson.read("$.duck"));
+ assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
[Important]Important

Notice that, for the byCommand method, the example calls the +assertThatValueIsANumber. This method must be defined in the test base class or be +statically imported to your tests. Notice that the byCommand call was converted to +assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took +the method name and passed the proper JSON path as a parameter to it.

The resulting WireMock stub is in the following example:

					'''
+{
+  "request" : {
+    "urlPath" : "/get",
+    "method" : "POST",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck == 123)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha == 'abc')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}",
+    "headers" : {
+      "Content-Type" : "application/json"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+'''
[Important]Important

If you use a matcher, then the part of the request and response that the +matcher addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for all the elements of the +collection.

Consider the following example:

Contract.make {
+    request {
+        method 'GET'
+        url("/foo")
+    }
+    response {
+        status OK()
+        body(events: [[
+                                 operation          : 'EXPORT',
+                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
+                                 status             : 'OK'
+                         ], [
+                                 operation          : 'INPUT_PROCESSING',
+                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
+                                 status             : 'OK'
+                         ]
+                ]
+        )
+        bodyMatchers {
+            jsonPath('$.events[0].operation', byRegex('.+'))
+            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
+            jsonPath('$.events[0].status', byRegex('.+'))
+        }
+    }
+}

The preceding code leads to creating the following test (the code block shows only the assertion section):

and:
+	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
+	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
+and:
+	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
+	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
+	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")

As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole $.events +collection and assert it with the byCommand(…​) method.

8.6 JAX-RS Support

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define protected WebTarget webTarget and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of application/octet-stream gets used.

In order to use JAX-RS mode, use the following settings:

testMode == 'JAXRSCLIENT'

The following example shows a generated test API:

					'''
+ // when:
+  Response response = webTarget
+    .path("/users")
+    .queryParam("limit", "10")
+    .queryParam("offset", "20")
+    .queryParam("filter", "email")
+    .queryParam("sort", "name")
+    .queryParam("search", "55")
+    .queryParam("age", "99")
+    .queryParam("name", "Denis.Stepanov")
+    .queryParam("email", "bob@email.com")
+    .request()
+    .method("GET");
+
+  String responseAsString = response.readEntity(String.class);
+
+ // then:
+  assertThat(response.getStatus()).isEqualTo(200);
+ // and:
+  DocumentContext parsedJson = JsonPath.parse(responseAsString);
+  assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
+'''

8.7 Async Support

If you’re using asynchronous communication on the server side (your controllers are +returning Callable, DeferredResult, and so on), then, inside your contract, you must +provide an async() method in the response section. The following code shows an example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status OK()
+        body 'Passed'
+        async()
+    }
+}

+

YAML.  +

response:
+    async: true

+

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status 200
+        body 'Passed'
+        fixedDelayMilliseconds 1000
+    }
+}

+

YAML.  +

response:
+    fixedDelayMilliseconds: 1000

+

8.8 Working with Context Paths

Spring Cloud Contract supports context paths.

[Important]Important

The only change needed to fully support context paths is the switch on the +PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer +side remains untouched. In order for the generated test to pass, you must use EXPLICIT +mode.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>

+

Gradle.  +

contracts {
+		testMode = 'EXPLICIT'
+}

+

That way, you generate a test that DOES NOT use MockMvc. It means that you generate +real requests and you need to setup your generated test’s base class to work on a real +socket.

Consider the following contract:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+		url '/my-context-path/url'
+	}
+	response {
+		status OK()
+	}
+}

The following example shows how to set up a base class and Rest Assured:

import io.restassured.RestAssured;
+import org.junit.Before;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class ContextPathTestingBaseClass {
+
+	@LocalServerPort int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost";
+		RestAssured.port = this.port;
+	}
+}

If you do it this way:

  • All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, /my-context-path/url).
  • Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call /my-context-path/url).

8.9 Working with WebFlux

Spring Cloud Contract offers two ways of working with WebFlux.

8.9.1 WebFlux with WebTestClient

One of them is via the WebTestClient mode.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>WEBTESTCLIENT</testMode>
+    </configuration>
+</plugin>

+

Gradle.  +

contracts {
+		testMode = 'WEBTESTCLIENT'
+}

+

The following example shows how to set up a WebTestClient base class and RestAssured +for WebFlux:

import io.restassured.module.webtestclient.RestAssuredWebTestClient;
+import org.junit.Before;
+
+public abstract class BeerRestBase {
+
+	@Before
+	public void setup() {
+		RestAssuredWebTestClient.standaloneSetup(
+		new ProducerController(personToCheck -> personToCheck.age >= 20));
+	}
+}
+}

8.9.2 WebFlux with Explicit mode

Another way is with the EXPLICIT mode in your generated tests +to work with WebFlux.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>

+

Gradle.  +

contracts {
+		testMode = 'EXPLICIT'
+}

+

The following example shows how to set up a base class and Rest Assured for Web Flux:

@RunWith(SpringRunner.class)
+@SpringBootTest(classes = BeerRestBase.Config.class,
+		webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+		properties = "server.port=0")
+public abstract class BeerRestBase {
+
+    // your tests go here
+
+    // in this config class you define all controllers and mocked services
+@Configuration
+@EnableAutoConfiguration
+static class Config {
+
+	@Bean
+	PersonCheckingService personCheckingService()  {
+		return personToCheck -> personToCheck.age >= 20;
+	}
+
+	@Bean
+	ProducerController producerController() {
+		return new ProducerController(personCheckingService());
+	}
+}
+
+}

8.10 XML Support for REST

For REST contracts, we also support XML request and response body. +The XML body has to be passed within the body element +as a String or GString. Also body matchers can be provided for +both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath +method should be used, with the desired xPath provided as the first argument +and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

Here is an example of a Groovy DSL contract with XML response body:

					Contract.make {
+						request {
+							method GET()
+							urlPath '/get'
+							headers {
+								contentType(applicationXml())
+							}
+						}
+						response {
+							status(OK())
+							headers {
+								contentType(applicationXml())
+							}
+							body """
+<test>
+<duck type='xtype'>123</duck>
+<alpha>abc</alpha>
+<list>
+<elem>abc</elem>
+<elem>def</elem>
+<elem>ghi</elem>
+</list>
+<number>123</number>
+<aBoolean>true</aBoolean>
+<date>2017-01-01</date>
+<dateTime>2017-01-01T01:23:45</dateTime>
+<time>01:02:34</time>
+<valueWithoutAMatcher>foo</valueWithoutAMatcher>
+<key><complex>foo</complex></key>
+</test>"""
+							bodyMatchers {
+								xPath('/test/duck/text()', byRegex("[0-9]{3}"))
+								xPath('/test/duck/text()', byCommand('test($it)'))
+								xPath('/test/duck/xxx', byNull())
+								xPath('/test/duck/text()', byEquality())
+								xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
+								xPath('/test/alpha/text()', byEquality())
+								xPath('/test/number/text()', byRegex(number()))
+								xPath('/test/date/text()', byDate())
+								xPath('/test/dateTime/text()', byTimestamp())
+								xPath('/test/time/text()', byTime())
+								xPath('/test/*/complex/text()', byEquality())
+								xPath('/test/duck/@type', byEquality())
+							}
+						}
+					}

And below is an example of a YAML contract with XML request and response bodies:

include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml

Here is an example of an automatically generated test for XML response body:

@Test
+public void validate_xmlMatches() throws Exception {
+	// given:
+	MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/xml");
+
+	// when:
+	ResponseOptions response = given().spec(request).get("/get");
+
+	// then:
+	assertThat(response.statusCode()).isEqualTo(200);
+	// and:
+	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
+					.newDocumentBuilder();
+	Document parsedXml = documentBuilder.parse(new InputSource(
+				new StringReader(response.getBody().asString())));
+	// and:
+	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
+	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
+	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
+	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
+	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
+	}

8.11 Messaging Top-Level Elements

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

8.11.1 Output Triggered by a Method

The output message can be triggered by calling a method (such as a Scheduler when a was +started and a message was sent), as shown in the following example:

Groovy DSL.  +

def dsl = Contract.make {
+	// Human readable description
+	description 'Some description'
+	// Label by means of which the output message can be triggered
+	label 'some_label'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('bookReturnedTriggered()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo('output')
+		// the body of the output message
+		body('''{ "bookName" : "foo" }''')
+		// the headers of the output message
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

+

YAML.  +

# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+input:
+  # the contract will be triggered by a method
+  triggeredBy: bookReturnedTriggered()
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo

+

In the previous example case, the output message is sent to output if a method called +bookReturnedTriggered is executed. On the message publisher’s side, we generate a +test that calls that method to trigger the message. On the consumer side, you can use +the some_label to trigger the message.

8.11.2 Output Triggered by a Message

The output message can be triggered by receiving a message, as shown in the following +example:

Groovy DSL.  +

def dsl = Contract.make {
+	description 'Some Description'
+	label 'some_label'
+	// input is a message
+	input {
+		// the message was received from this destination
+		messageFrom('input')
+		// has the following body
+		messageBody([
+				bookName: 'foo'
+		])
+		// and the following headers
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

+

YAML.  +

# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+# input is a message
+input:
+  messageFrom: input
+  # has the following body
+  messageBody:
+    bookName: 'foo'
+  # and the following headers
+  messageHeaders:
+    sample: 'header'
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo

+

In the preceding example, the output message is sent to output if a proper message is +received on the input destination. On the message publisher’s side, the engine +generates a test that sends the input message to the defined destination. On the +consumer side, you can either send a message to the input destination or use a label +(some_label in the example) to trigger the message.

8.11.3 Consumer/Producer

[Important]Important

This section is valid only for Groovy DSL.

In HTTP, you have a notion of client/stub and `server/test notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the consumer and producer methods, as presented in the following example +(note that you can use either $ or value methods to provide consumer and producer +parts):

					Contract.make {
+						label 'some_label'
+						input {
+							messageFrom value(consumer('jms:output'), producer('jms:input'))
+							messageBody([
+									bookName: 'foo'
+							])
+							messageHeaders {
+								header('sample', 'header')
+							}
+						}
+						outputMessage {
+							sentTo $(consumer('jms:input'), producer('jms:output'))
+							body([
+									bookName: 'foo'
+							])
+						}
+					}

8.11.4 Common

In the input or outputMessage section you can call assertThat with the name +of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test.

8.12 Multiple Contracts in One File

You can define multiple contracts in one file. Such a contract might resemble the +following example:

Groovy DSL.  +

import org.springframework.cloud.contract.spec.Contract
+
+[
+	Contract.make {
+		name("should post a user")
+		request {
+			method 'POST'
+			url('/users/1')
+		}
+		response {
+			status OK()
+		}
+	},
+	Contract.make {
+		request {
+			method 'POST'
+			url('/users/2')
+		}
+		response {
+			status OK()
+		}
+	}
+]

+

YAML.  +

---
+name: should post a user
+request:
+  method: POST
+  url: /users/1
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/2
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/3
+response:
+  status: 200

+

In the preceding example, one contract has the name field and the other does not. This +leads to generation of two tests that look more or less like this:

package org.springframework.cloud.contract.verifier.tests.com.hello;
+
+import com.example.TestBase;
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
+import com.jayway.restassured.response.ResponseOptions;
+import org.junit.Test;
+
+import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class V1Test extends TestBase {
+
+	@Test
+	public void validate_should_post_a_user() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/1");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+	@Test
+	public void validate_withList_1() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/2");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+}

Notice that, for the contract that has the name field, the generated test method is named +validate_should_post_a_user. For the one that does not have the name, it is called +validate_withList_1. It corresponds to the name of the file WithList.groovy and the +index of the contract in the list.

The generated stubs is shown in the following example:

should post a user.json
+1_WithList.json

As you can see, the first file got the name parameter from the contract. The second +got the name of the contract file (WithList.groovy) prefixed with the index (in this +case, the contract had an index of 1 in the list of contracts in the file).

[Tip]Tip

As you can see, it is much better if you name your contracts because doing so makes +your tests far more meaningful.

8.13 Generating Spring REST Docs snippets from the contracts

When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven’t already.

Maven.  +

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+<dependency>
+	<groupId>org.springframework.restdocs</groupId>
+	<artifactId>spring-restdocs-mockmvc</artifactId>
+	<optional>true</optional>
+</dependency>

+

Gradle.  +

testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'

+

Next you need to make some changes to your base class like the following example.

package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
+public abstract class FraudBaseWithWebAppSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Autowired
+	private WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName()))
+				.build());
+	}
+
+	protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+public abstract class FraudBaseWithStandaloneSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
+				.standaloneSetup(new FraudDetectionController())
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName())));
+	}
+
+}
[Tip]Tip

You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs.

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi_pr01.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_pr01.html new file mode 100644 index 00000000..9910a586 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_pr01.html @@ -0,0 +1,4 @@ + + +

Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, +Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant

2.1.2.RELEASE

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi_spring-cloud-contract.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_spring-cloud-contract.html new file mode 100644 index 00000000..e046ea47 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_spring-cloud-contract.html @@ -0,0 +1,3 @@ + + + Spring Cloud Contract

Spring Cloud Contract


Table of Contents

1. Spring Cloud Contract
2. Spring Cloud Contract Verifier Introduction
2.1. History
2.2. Why a Contract Verifier?
2.2.1. Testing issues
2.3. Purposes
2.4. How It Works
2.4.1. A Three-second Tour
On the Producer Side
On the Consumer Side
2.4.2. A Three-minute Tour
On the Producer Side
On the Consumer Side
2.4.3. Defining the Contract
2.4.4. Client Side
2.4.5. Server Side
2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.5.1. Technical note
2.5.2. Consumer side (Loan Issuance)
2.5.3. Producer side (Fraud Detection server)
2.5.4. Consumer Side (Loan Issuance) Final Step
2.6. Dependencies
2.7. Additional Links
2.7.1. Spring Cloud Contract video
2.7.2. Readings
2.8. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. I don’t want to write a contract in Groovy!
3.3. What is this value(consumer(), producer()) ?
3.4. How to do Stubs versioning?
3.4.1. API Versioning
3.4.2. JAR versioning
3.4.3. Dev or prod stubs
3.5. Common repo with contracts
3.5.1. Repo structure
3.5.2. Workflow
3.5.3. Consumer
3.5.4. Producer
3.5.5. How can I define messaging contracts per topic not per producer?
For Maven Project
For Gradle Project
3.6. Do I need a Binary Storage? Can’t I use Git?
3.6.1. Protocol convention
3.6.2. Producer
3.6.3. Producer with contracts stored locally
Keeping contracts with the producer and stubs in an external repository
3.6.4. Consumer
3.7. Can I use the Pact Broker?
3.7.1. Pact Consumer
3.7.2. Producer
3.7.3. Pact Consumer (Producer Contract approach)
3.8. How can I debug the request/response being sent by the generated tests client?
3.8.1. How can I debug the mapping/request/response being sent by WireMock?
3.8.2. How can I see what got registered in the HTTP server stub?
3.8.3. Can I reference text from file?
4. Spring Cloud Contract Verifier Setup
4.1. Gradle Project
4.1.1. Prerequisites
4.1.2. Add Gradle Plugin with Dependencies
4.1.3. Gradle and Rest Assured 2.0
4.1.4. Snapshot Versions for Gradle
4.1.5. Add stubs
4.1.6. Run the Plugin
4.1.7. Default Setup
4.1.8. Configure Plugin
4.1.9. Configuration Options
4.1.10. Single Base Class for All Tests
4.1.11. Different Base Classes for Contracts
4.1.12. Invoking Generated Tests
4.1.13. Pushing stubs to SCM
4.1.14. Spring Cloud Contract Verifier on the Consumer Side
4.2. Maven Project
4.2.1. Add maven plugin
4.2.2. Maven and Rest Assured 2.0
4.2.3. Snapshot versions for Maven
4.2.4. Add stubs
4.2.5. Run plugin
4.2.6. Configure plugin
4.2.7. Configuration Options
4.2.8. Single Base Class for All Tests
4.2.9. Different base classes for contracts
4.2.10. Invoking generated tests
4.2.11. Pushing stubs to SCM
4.2.12. Maven Plugin and STS
4.2.13. Maven Plugin with Spock Tests
4.3. Stubs and Transitive Dependencies
4.4. Scenarios
4.5. Docker Project
4.5.1. Short intro to Maven, JARs and Binary storage
4.5.2. How it works
Environment Variables
4.5.3. Example of usage
4.5.4. Server side (nodejs)
5. Spring Cloud Contract Verifier Messaging
5.1. Integrations
5.2. Manual Integration Testing
5.3. Publisher-Side Test Generation
5.3.1. Scenario 1: No Input Message
5.3.2. Scenario 2: Output Triggered by Input
5.3.3. Scenario 3: No Output Message
5.4. Consumer Stub Generation
6. Spring Cloud Contract Stub Runner
6.1. Snapshot versions
6.2. Publishing Stubs as JARs
6.3. Stub Runner Core
6.3.1. Retrieving stubs
Stub downloading
Classpath scanning
Configuring HTTP Server Stubs
6.3.2. Running stubs
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
6.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
6.4.1. Maven settings
6.4.2. Providing fixed ports
6.4.3. Fluent API
6.4.4. Stub Runner with Spring
6.5. Stub Runner Spring Cloud
6.5.1. Stubbing Service Discovery
Test profiles and service discovery
6.5.2. Additional Configuration
6.6. Stub Runner Boot Application
6.6.1. How to use it?
Stub Runner Server
Stub Runner Server Fat Jar
Spring Cloud CLI
6.6.2. Endpoints
HTTP
Messaging
6.6.3. Example
6.6.4. Stub Runner Boot with Service Discovery
6.7. Stubs Per Consumer
6.8. Common
6.8.1. Common Properties for JUnit and Spring
6.8.2. Stub Runner Stubs IDs
6.9. Stub Runner Docker
6.9.1. How to use it
6.9.2. Example of client side usage in a non JVM project
7. Stub Runner for Messaging
7.1. Stub triggering
7.1.1. Trigger by Label
7.1.2. Trigger by Group and Artifact Ids
7.1.3. Trigger by Artifact Ids
7.1.4. Trigger All Messages
7.2. Stub Runner Camel
7.2.1. Adding it to the project
7.2.2. Disabling the functionality
7.2.3. Examples
Stubs structure
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.3. Stub Runner Integration
7.3.1. Adding the Runner to the Project
7.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.4. Stub Runner Stream
7.4.1. Adding the Runner to the Project
7.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.5. Stub Runner Spring AMQP
7.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
8. Contract DSL
8.1. Limitations
8.2. Common Top-Level elements
8.2.1. Description
8.2.2. Name
8.2.3. Ignoring Contracts
8.2.4. Passing Values from Files
8.2.5. HTTP Top-Level Elements
8.3. Request
8.4. Response
8.5. Dynamic properties
8.5.1. Dynamic properties inside the body
8.5.2. Regular expressions
8.5.3. Passing Optional Parameters
8.5.4. Executing Custom Methods on the Server Side
8.5.5. Referencing the Request from the Response
8.5.6. Registering Your Own WireMock Extension
8.5.7. Dynamic Properties in the Matchers Sections
8.6. JAX-RS Support
8.7. Async Support
8.8. Working with Context Paths
8.9. Working with WebFlux
8.9.1. WebFlux with WebTestClient
8.9.2. WebFlux with Explicit mode
8.10. XML Support for REST
8.11. Messaging Top-Level Elements
8.11.1. Output Triggered by a Method
8.11.2. Output Triggered by a Message
8.11.3. Consumer/Producer
8.11.4. Common
8.12. Multiple Contracts in One File
8.13. Generating Spring REST Docs snippets from the contracts
9. Customization
9.1. Extending the DSL
9.1.1. Common JAR
9.1.2. Adding the Dependency to the Project
9.1.3. Test the Dependency in the Project’s Dependencies
9.1.4. Test a Dependency in the Plugin’s Dependencies
9.1.5. Referencing classes in DSLs
10. Using the Pluggable Architecture
10.1. Custom Contract Converter
10.1.1. Pact Converter
10.1.2. Pact Contract
10.1.3. Pact for Producers
10.1.4. Pact for Consumers
10.2. Using the Custom Test Generator
10.3. Using the Custom Stub Generator
10.4. Using the Custom Stub Runner
10.5. Using the Custom Stub Downloader
10.6. Using the SCM Stub Downloader
10.7. Using the Pact Stub Downloader
11. Spring Cloud Contract WireMock
11.1. Registering Stubs Automatically
11.2. Using Files to Specify the Stub Bodies
11.3. Alternative: Using JUnit Rules
11.4. Relaxed SSL Validation for Rest Template
11.5. WireMock and Spring MVC Mocks
11.6. Customization of WireMock configuration
11.7. Generating Stubs using REST Docs
11.8. Generating Contracts by Using REST Docs
12. Migrations
12.1. 1.0.x → 1.1.x
12.1.1. New structure of generated stubs
12.2. 1.1.x → 1.2.x
12.2.1. Custom HttpServerStub
12.2.2. New packages for generated tests
12.2.3. New Methods in TemplateProcessor
12.2.4. RestAssured 3.0
12.3. 1.2.x → 2.0.x
13. Links
\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/multi/multi_stub-runner-for-messaging.html b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_stub-runner-for-messaging.html new file mode 100644 index 00000000..4ef2ba5f --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/multi/multi_stub-runner-for-messaging.html @@ -0,0 +1,360 @@ + + + 7. Stub Runner for Messaging

7. Stub Runner for Messaging

Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks:

  • Spring Integration
  • Spring Cloud Stream
  • Apache Camel
  • Spring AMQP

It also provides entry points to integrate with any other solution on the market.

[Important]Important

If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. +That way the only remaining framework is Spring AMQP.

7.1 Stub triggering

To trigger a message, use the StubTrigger interface:

package org.springframework.cloud.contract.stubrunner;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Contract for triggering stub messages.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubTrigger {
+
+	/**
+	 * Triggers an event by a given label for a given {@code groupid:artifactid} notation.
+	 * You can use only {@code artifactId} too.
+	 *
+	 * Feature related to messaging.
+	 * @param ivyNotation ivy notation of a stub
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String ivyNotation, String labelName);
+
+	/**
+	 * Triggers an event by a given label.
+	 *
+	 * Feature related to messaging.
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String labelName);
+
+	/**
+	 * Triggers all possible events.
+	 *
+	 * Feature related to messaging.
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger();
+
+	/**
+	 * Feature related to messaging.
+	 * @return a mapping of ivy notation of a dependency to all the labels it has.
+	 */
+	Map<String, Collection<String>> labels();
+
+}

For convenience, the StubFinder interface extends StubTrigger, so you only need one +or the other in your tests.

StubTrigger gives you the following options to trigger a message:

7.1.1 Trigger by Label

stubFinder.trigger('return_book_1')

7.1.2 Trigger by Group and Artifact Ids

stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')

7.1.3 Trigger by Artifact Ids

stubFinder.trigger('streamService', 'return_book_1')

7.1.4 Trigger All Messages

stubFinder.trigger()

7.2 Stub Runner Camel

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +For the provided artifacts it will automatically download the stubs and register the required +routes.

7.2.1 Adding it to the project

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner.

7.2.2 Disabling the functionality

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

7.2.3 Examples

Stubs structure

Let us assume that we have the following Maven repository with a deployed stubs for the +camelService application.

└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── camelService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── camelService-0.0.1-SNAPSHOT.pom
+                            │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml

And the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings

Let’s consider the following contracts (let' number it with 1):

Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

and number 2

Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('jms:input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

Scenario 1 (no input message)

So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

stubFinder.trigger('return_book_1')

Next we’ll want to listen to the output of the message sent to jms:output

Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)

And the received message would pass the following assertions

receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

Scenario 2 (output triggered by input)

Since the route is set for you it’s enough to just send a message to the jms:output destination.

producerTemplate.
+		sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])

Next we’ll want to listen to the output of the message sent to jms:output

Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)

And the received message would pass the following assertions

receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you it’s enough to just send a message to the jms:output destination.

producerTemplate.
+		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])

7.3 Stub Runner Integration

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes.

7.3.1 Adding the Runner to the Project

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

7.3.2 Disabling the functionality

If you need to disable this functionality, set the +stubrunner.integration.enabled=false property.

Assume that you have the following Maven repository with deployed stubs for the +integrationService application:

└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── integrationService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── integrationService-0.0.1-SNAPSHOT.pom
+                            │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml

Further assume the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings

Consider the following contracts (numbered 1):

Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

Now consider 2:

Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

and the following Spring Integration Route:

<?xml version="1.0" encoding="UTF-8"?>
+<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+			 xmlns:beans="http://www.springframework.org/schema/beans"
+			 xmlns="http://www.springframework.org/schema/integration"
+			 xsi:schemaLocation="http://www.springframework.org/schema/beans
+			https://www.springframework.org/schema/beans/spring-beans.xsd
+			http://www.springframework.org/schema/integration
+			http://www.springframework.org/schema/integration/spring-integration.xsd">
+
+
+	<!-- REQUIRED FOR TESTING -->
+	<bridge input-channel="output"
+			output-channel="outputTest"/>
+
+	<channel id="outputTest">
+		<queue/>
+	</channel>
+
+</beans:beans>

These examples lend themselves to three scenarios:

Scenario 1 (no input message)

To trigger a message via the return_book_1 label, use the StubTigger interface, as +follows:

stubFinder.trigger('return_book_1')

To listen to the output of the message sent to output:

Message<?> receivedMessage = messaging.receive('outputTest')

The received message would pass the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 2 (output triggered by input)

Since the route is set for you, you can send a message to the output +destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')

To listen to the output of the message sent to output:

Message<?> receivedMessage = messaging.receive('outputTest')

The received message passes the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you, you can send a message to the input destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

7.4 Stub Runner Stream

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes.

[Warning]Warning

If Stub Runner’s integration with Stream the messageFrom or sentTo Strings +are resolved first as a destination of a channel and no such destination exists, the +destination is resolved as a channel name.

[Important]Important

If you want to use Spring Cloud Stream remember, to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support.

Maven.  +

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

+

7.4.1 Adding the Runner to the Project

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

7.4.2 Disabling the functionality

If you need to disable this functionality, set the stubrunner.stream.enabled=false +property.

Assume that you have the following Maven repository with a deployed stubs for the +streamService application:

└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── streamService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── streamService-0.0.1-SNAPSHOT.pom
+                            │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml

Further assume the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings

Consider the following contracts (numbered 1):

Contract.make {
+	label 'return_book_1'
+	input { triggeredBy('bookReturnedTriggered()') }
+	outputMessage {
+		sentTo('returnBook')
+		body('''{ "bookName" : "foo" }''')
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}

Now consider 2:

Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('bookStorage')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders { header('sample', 'header') }
+	}
+	outputMessage {
+		sentTo('returnBook')
+		body([
+				bookName: 'foo'
+		])
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}

Now consider the following Spring configuration:

stubrunner.repositoryRoot: classpath:m2repo/repository/
+stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
+stubrunner.stubs-mode: remote
+spring:
+  cloud:
+    stream:
+      bindings:
+        output:
+          destination: returnBook
+        input:
+          destination: bookStorage
+
+server:
+  port: 0
+
+debug: true

These examples lend themselves to three scenarios:

Scenario 1 (no input message)

To trigger a message via the return_book_1 label, use the StubTrigger interface as +follows:

stubFinder.trigger('return_book_1')

To listen to the output of the message sent to a channel whose destination is +returnBook:

Message<?> receivedMessage = messaging.receive('returnBook')

The received message passes the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 2 (output triggered by input)

Since the route is set for you, you can send a message to the bookStorage +destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')

To listen to the output of the message sent to returnBook:

Message<?> receivedMessage = messaging.receive('returnBook')

The received message passes the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you, you can send a message to the output +destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

7.5 Stub Runner Spring AMQP

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes.

The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a RabbitTemplate on the application context and +uses it as a spring boot test named @SpyBean. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application.

On the message consumer side, the stub runner considers all @RabbitListener annotated +endpoints and all SimpleMessageListenerContainer objects on the application context.

As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners.

If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey +messaging header.

7.5.1 Adding the Runner to the Project

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property stubrunner.amqp.enabled=true. Remember to annotate your test class +with @AutoConfigureStubRunner.

[Important]Important

If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the stubrunner.stream.enabled=false and +stubrunner.integration.enabled=false properties.

Assume that you have the following Maven repository with a deployed stubs for the +spring-cloud-contract-amqp-test application.

└── .m2
+    └── repository
+        └── com
+            └── example
+                └── spring-cloud-contract-amqp-test
+                    ├── 0.4.0-SNAPSHOT
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
+                    │   └── maven-metadata-local.xml
+                    └── maven-metadata-local.xml

Further assume that the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── contracts
+    └── shouldProduceValidPersonData.groovy

Consider the following contract:

Contract.make {
+	// Human readable description
+	description 'Should produce valid person data'
+	// Label by means of which the output message can be triggered
+	label 'contract-test.person.created.event'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('createPerson()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo 'contract-test.exchange'
+		headers {
+			header('contentType': 'application/json')
+			header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
+		}
+		// the body of the output message
+		body([
+				id  : $(consumer(9), producer(regex("[0-9]+"))),
+				name: "me"
+		])
+	}
+}

Now consider the following Spring configuration:

stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs
+  stubs-mode: remote
+  amqp:
+    enabled: true
+server:
+  port: 0

Triggering the message

To trigger a message using the contract above, use the StubTrigger interface as +follows:

stubTrigger.trigger("contract-test.person.created.event")

The message has a destination of contract-test.exchange, so the Spring AMQP stub runner +integration looks for bindings related to this exchange.

@Bean
+public Binding binding() {
+	return BindingBuilder.bind(new Queue("test.queue"))
+			.to(new DirectExchange("contract-test.exchange")).with("#");
+}

The binding definition binds the queue test.queue. As a result, the following listener +definition is matched and invoked with the contract message.

@Bean
+public SimpleMessageListenerContainer simpleMessageListenerContainer(
+		ConnectionFactory connectionFactory,
+		MessageListenerAdapter listenerAdapter) {
+	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
+	container.setConnectionFactory(connectionFactory);
+	container.setQueueNames("test.queue");
+	container.setMessageListener(listenerAdapter);
+
+	return container;
+}

Also, the following annotated listener matches and is invoked:

@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"), exchange = @Exchange(value = "contract-test.exchange", ignoreDeclarationExceptions = "true")))
+public void handlePerson(Person person) {
+	this.person = person;
+}
[Note]Note

The message is directly handed over to the onMessage method of the +MessageListener associated with the matching SimpleMessageListenerContainer.

Spring AMQP Test Configuration

In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock ConnectionFactory.

To disable the mocked ConnectionFactory, set the following property: +stubrunner.amqp.mockConnection=false

stubrunner:
+  amqp:
+    mockConnection: false
\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/css/highlight.css b/spring-cloud-contract/2.1.2.RELEASE/single/css/highlight.css new file mode 100644 index 00000000..3850f8b9 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/single/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/css/manual-multipage.css b/spring-cloud-contract/2.1.2.RELEASE/single/css/manual-multipage.css new file mode 100644 index 00000000..b790654b --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/single/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/css/manual-singlepage.css b/spring-cloud-contract/2.1.2.RELEASE/single/css/manual-singlepage.css new file mode 100644 index 00000000..303192a8 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/single/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/css/manual.css b/spring-cloud-contract/2.1.2.RELEASE/single/css/manual.css new file mode 100644 index 00000000..20cf07da --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/single/css/manual.css @@ -0,0 +1,342 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a) > code { + color: #6D180B; +} + +:not(pre) > code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body > *:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1, h2, h3, h4, h5, h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1, h2, h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1, h1 code { + font-size: 32px; +} + +h2, h2 code { + font-size: 24px; +} + +h3, h3 code { + font-size: 20px; +} + +h4, h1 code, h5, h5 code, h6, h6 code { + font-size: 18px; +} + +div.book, div.chapter, div.appendix, div.part, div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage + p, div.titlepage + p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul, ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table, div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting, pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th, table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *, div.note *, div.tip *, div.warning *, div.navheader *, div.navfooter *, div.calloutlist * { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p, div.note p, div.tip p, div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code, div.note code, div.tip code, div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th, .tip th, .warning th { + display: none; +} + +.note tr:first-child td, .tip tr:first-child td, .warning tr:first-child td { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p, div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist > table > tbody > tr > td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important, div.note, div.tip, div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl, dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc > dl > dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc > dl > dd > dl > dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc > dl > dd > dl > dd > dl > dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title > a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title > a:before { + content: "\00A7"; +} + +.title:hover > a, .title > a:hover, .title:hover > a:hover { + visibility: visible; +} + +.title:focus > a, .title > a:focus, .title:focus > a:focus { + outline: 0; +} diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/background.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/background.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/1.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/1.png new file mode 100644 index 00000000..7d473430 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/1.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/2.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/2.png new file mode 100644 index 00000000..5d09341b Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/2.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/3.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/3.png new file mode 100644 index 00000000..ef7b7004 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/callouts/3.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/caution.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/caution.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/important.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/important.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/logo.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/logo.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/note.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/note.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/tip.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/tip.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/images/warning.png b/spring-cloud-contract/2.1.2.RELEASE/single/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/single/images/warning.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/single/spring-cloud-contract.html b/spring-cloud-contract/2.1.2.RELEASE/single/spring-cloud-contract.html new file mode 100644 index 00000000..c3ea6431 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/single/spring-cloud-contract.html @@ -0,0 +1,7020 @@ + + + Spring Cloud Contract

Spring Cloud Contract


Table of Contents

1. Spring Cloud Contract
2. Spring Cloud Contract Verifier Introduction
2.1. History
2.2. Why a Contract Verifier?
2.2.1. Testing issues
2.3. Purposes
2.4. How It Works
2.4.1. A Three-second Tour
On the Producer Side
On the Consumer Side
2.4.2. A Three-minute Tour
On the Producer Side
On the Consumer Side
2.4.3. Defining the Contract
2.4.4. Client Side
2.4.5. Server Side
2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.5.1. Technical note
2.5.2. Consumer side (Loan Issuance)
2.5.3. Producer side (Fraud Detection server)
2.5.4. Consumer Side (Loan Issuance) Final Step
2.6. Dependencies
2.7. Additional Links
2.7.1. Spring Cloud Contract video
2.7.2. Readings
2.8. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. I don’t want to write a contract in Groovy!
3.3. What is this value(consumer(), producer()) ?
3.4. How to do Stubs versioning?
3.4.1. API Versioning
3.4.2. JAR versioning
3.4.3. Dev or prod stubs
3.5. Common repo with contracts
3.5.1. Repo structure
3.5.2. Workflow
3.5.3. Consumer
3.5.4. Producer
3.5.5. How can I define messaging contracts per topic not per producer?
For Maven Project
For Gradle Project
3.6. Do I need a Binary Storage? Can’t I use Git?
3.6.1. Protocol convention
3.6.2. Producer
3.6.3. Producer with contracts stored locally
Keeping contracts with the producer and stubs in an external repository
3.6.4. Consumer
3.7. Can I use the Pact Broker?
3.7.1. Pact Consumer
3.7.2. Producer
3.7.3. Pact Consumer (Producer Contract approach)
3.8. How can I debug the request/response being sent by the generated tests client?
3.8.1. How can I debug the mapping/request/response being sent by WireMock?
3.8.2. How can I see what got registered in the HTTP server stub?
3.8.3. Can I reference text from file?
4. Spring Cloud Contract Verifier Setup
4.1. Gradle Project
4.1.1. Prerequisites
4.1.2. Add Gradle Plugin with Dependencies
4.1.3. Gradle and Rest Assured 2.0
4.1.4. Snapshot Versions for Gradle
4.1.5. Add stubs
4.1.6. Run the Plugin
4.1.7. Default Setup
4.1.8. Configure Plugin
4.1.9. Configuration Options
4.1.10. Single Base Class for All Tests
4.1.11. Different Base Classes for Contracts
4.1.12. Invoking Generated Tests
4.1.13. Pushing stubs to SCM
4.1.14. Spring Cloud Contract Verifier on the Consumer Side
4.2. Maven Project
4.2.1. Add maven plugin
4.2.2. Maven and Rest Assured 2.0
4.2.3. Snapshot versions for Maven
4.2.4. Add stubs
4.2.5. Run plugin
4.2.6. Configure plugin
4.2.7. Configuration Options
4.2.8. Single Base Class for All Tests
4.2.9. Different base classes for contracts
4.2.10. Invoking generated tests
4.2.11. Pushing stubs to SCM
4.2.12. Maven Plugin and STS
4.2.13. Maven Plugin with Spock Tests
4.3. Stubs and Transitive Dependencies
4.4. Scenarios
4.5. Docker Project
4.5.1. Short intro to Maven, JARs and Binary storage
4.5.2. How it works
Environment Variables
4.5.3. Example of usage
4.5.4. Server side (nodejs)
5. Spring Cloud Contract Verifier Messaging
5.1. Integrations
5.2. Manual Integration Testing
5.3. Publisher-Side Test Generation
5.3.1. Scenario 1: No Input Message
5.3.2. Scenario 2: Output Triggered by Input
5.3.3. Scenario 3: No Output Message
5.4. Consumer Stub Generation
6. Spring Cloud Contract Stub Runner
6.1. Snapshot versions
6.2. Publishing Stubs as JARs
6.3. Stub Runner Core
6.3.1. Retrieving stubs
Stub downloading
Classpath scanning
Configuring HTTP Server Stubs
6.3.2. Running stubs
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
6.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
6.4.1. Maven settings
6.4.2. Providing fixed ports
6.4.3. Fluent API
6.4.4. Stub Runner with Spring
6.5. Stub Runner Spring Cloud
6.5.1. Stubbing Service Discovery
Test profiles and service discovery
6.5.2. Additional Configuration
6.6. Stub Runner Boot Application
6.6.1. How to use it?
Stub Runner Server
Stub Runner Server Fat Jar
Spring Cloud CLI
6.6.2. Endpoints
HTTP
Messaging
6.6.3. Example
6.6.4. Stub Runner Boot with Service Discovery
6.7. Stubs Per Consumer
6.8. Common
6.8.1. Common Properties for JUnit and Spring
6.8.2. Stub Runner Stubs IDs
6.9. Stub Runner Docker
6.9.1. How to use it
6.9.2. Example of client side usage in a non JVM project
7. Stub Runner for Messaging
7.1. Stub triggering
7.1.1. Trigger by Label
7.1.2. Trigger by Group and Artifact Ids
7.1.3. Trigger by Artifact Ids
7.1.4. Trigger All Messages
7.2. Stub Runner Camel
7.2.1. Adding it to the project
7.2.2. Disabling the functionality
7.2.3. Examples
Stubs structure
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.3. Stub Runner Integration
7.3.1. Adding the Runner to the Project
7.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.4. Stub Runner Stream
7.4.1. Adding the Runner to the Project
7.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.5. Stub Runner Spring AMQP
7.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
8. Contract DSL
8.1. Limitations
8.2. Common Top-Level elements
8.2.1. Description
8.2.2. Name
8.2.3. Ignoring Contracts
8.2.4. Passing Values from Files
8.2.5. HTTP Top-Level Elements
8.3. Request
8.4. Response
8.5. Dynamic properties
8.5.1. Dynamic properties inside the body
8.5.2. Regular expressions
8.5.3. Passing Optional Parameters
8.5.4. Executing Custom Methods on the Server Side
8.5.5. Referencing the Request from the Response
8.5.6. Registering Your Own WireMock Extension
8.5.7. Dynamic Properties in the Matchers Sections
8.6. JAX-RS Support
8.7. Async Support
8.8. Working with Context Paths
8.9. Working with WebFlux
8.9.1. WebFlux with WebTestClient
8.9.2. WebFlux with Explicit mode
8.10. XML Support for REST
8.11. Messaging Top-Level Elements
8.11.1. Output Triggered by a Method
8.11.2. Output Triggered by a Message
8.11.3. Consumer/Producer
8.11.4. Common
8.12. Multiple Contracts in One File
8.13. Generating Spring REST Docs snippets from the contracts
9. Customization
9.1. Extending the DSL
9.1.1. Common JAR
9.1.2. Adding the Dependency to the Project
9.1.3. Test the Dependency in the Project’s Dependencies
9.1.4. Test a Dependency in the Plugin’s Dependencies
9.1.5. Referencing classes in DSLs
10. Using the Pluggable Architecture
10.1. Custom Contract Converter
10.1.1. Pact Converter
10.1.2. Pact Contract
10.1.3. Pact for Producers
10.1.4. Pact for Consumers
10.2. Using the Custom Test Generator
10.3. Using the Custom Stub Generator
10.4. Using the Custom Stub Runner
10.5. Using the Custom Stub Downloader
10.6. Using the SCM Stub Downloader
10.7. Using the Pact Stub Downloader
11. Spring Cloud Contract WireMock
11.1. Registering Stubs Automatically
11.2. Using Files to Specify the Stub Bodies
11.3. Alternative: Using JUnit Rules
11.4. Relaxed SSL Validation for Rest Template
11.5. WireMock and Spring MVC Mocks
11.6. Customization of WireMock configuration
11.7. Generating Stubs using REST Docs
11.8. Generating Contracts by Using REST Docs
12. Migrations
12.1. 1.0.x → 1.1.x
12.1.1. New structure of generated stubs
12.2. 1.1.x → 1.2.x
12.2.1. Custom HttpServerStub
12.2.2. New packages for generated tests
12.2.3. New Methods in TemplateProcessor
12.2.4. RestAssured 3.0
12.3. 1.2.x → 2.0.x
13. Links

Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, +Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant

2.1.2.RELEASE

1. Spring Cloud Contract

You need confidence when pushing new features to a new application or service in a +distributed system. This project provides support for Consumer Driven Contracts and +service schemas in Spring applications (for both HTTP and message-based interactions), +covering a range of options for writing tests, publishing them as assets, and asserting +that a contract is kept by producers and consumers.

2. Spring Cloud Contract Verifier Introduction

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture.

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract +definitions are used to produce the following resources:

  • JSON stub definitions to be used by WireMock when doing integration testing on the +client code (client tests). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier.
  • Messaging routes, if you’re using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations.
  • Acceptance tests (in JUnit 4, JUnit 5 or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (server tests). A full test is generated by +Spring Cloud Contract Verifier.

2.1 History

Before becoming Spring Cloud Contract, this project was called Accurest. +It was created by Marcin Grzejszczak and Jakub Kubrynski +from (Codearte.

The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016.

2.2 Why a Contract Verifier?

Assume that we have a system consisting of multiple microservices:

Microservices Architecture

2.2.1 Testing issues

If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things:

  • Deploy all microservices and perform end-to-end tests.
  • Mock other microservices in unit/integration tests.

Both have their advantages but also a lot of disadvantages.

Deploy all microservices and perform end to end tests

Advantages:

  • Simulates production.
  • Tests real communication between services.

Disadvantages:

  • To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc.
  • The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime).
  • They take a long time to run.
  • The feedback comes very late in the process.
  • They are extremely hard to debug.

Mock other microservices in unit/integration tests

Advantages:

  • They provide very fast feedback.
  • They have no infrastructure requirements.

Disadvantages:

  • The implementor of the service creates stubs that might have nothing to do with +reality.
  • You can go to production with passing tests and failing production.

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses.

Stubbed Services

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you’re calling. Also, if you can use them, it means that they +were tested against the producer’s side. In short, you can trust those stubs.

2.3 Purposes

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

  • To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does.
  • To promote ATDD method and Microservices architectural style.
  • To provide a way to publish changes in contracts that are immediately visible on both +sides.
  • To generate boilerplate test code to be used on the server side.
[Important]Important

Spring Cloud Contract Verifier’s purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior.

2.4 How It Works

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

2.4.1 A Three-second Tour

This very brief tour walks through using Spring Cloud Contract:

You can find a somewhat longer tour +here.

On the Producer Side

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +org.springframework.cloud.contract.verifier.tests..

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example RestAssuredMockMvc +controller setup or messaging test setup).

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository.

On the Consumer Side

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the +following example:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

  • By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands:

    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Tip]Tip

    The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail.

  • By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract +Stub Runner properties, as shown in the following example:

    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to +run the collaborators' stubs for you, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
[Tip]Tip

Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work.

Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service.

2.4.2 A Three-minute Tour

This brief tour walks through using Spring Cloud Contract:

You can find an even more brief tour +here.

On the Producer Side

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract in Groovy DSL:

package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url '/fraudcheck'
+		body([
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount: 99999
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+	response {
+		status OK()
+		body([
+			   fraudCheckStatus: "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+}

The same contract expressed in YAML would look like the following example:

request:
+  method: PUT
+  url: /fraudcheck
+  body:
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers:
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id']
+        type: by_regex
+        value: "[0-9]{10}"
+response:
+  status: 200
+  body:
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers:
+    Content-Type: application/json;charset=UTF-8

In the case of messaging, you can define:

  • The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header).
  • The methods that should be called after the message is received.
  • The methods that, when called, should trigger a message.

The following example shows a Camel messaging contract expressed in Groovy DSL:

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}

The following example shows the same contract expressed in YAML:

label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +org.springframework.cloud.contract.verifier.tests..

The following example shows a sample auto-generated test for an HTTP contract:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}

The preceding example uses Spring’s MockMvc to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, +respectively.)

Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient +run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. +In order to use WebTestClient set testMode to WEBTESTCLIENT.

Here is an example of a test generated in WEBTESTCLIENT test mode:

[source,java,indent=0]
@Test
+	public void validate_shouldRejectABeerIfTooYoung() throws Exception {
+		// given:
+			WebTestClientRequestSpecification request = given()
+					.header("Content-Type", "application/json")
+					.body("{\"age\":10}");
+
+		// when:
+			WebTestClientResponse response = given().spec(request)
+					.post("/check");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+			assertThat(response.header("Content-Type")).matches("application/json.*");
+		// and:
+			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+			assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
+	}

Apart from the default JUnit 4, you can instead use JUnit 5 or Spock tests, by setting the plugin +testFramework property to either JUNIT5 or Spock.

[Tip]Tip

You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names.

The following example shows an auto-generated test in Spock for a messaging stub contract:

[source,groovy,indent=0]
given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, RestAssuredMockMvc controller +setup or messaging test setup).

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example:

[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

You can now merge the changes and publish both the application and the stub artifacts +in an online repository.

Docker Project

In order to enable working with contracts while creating applications in non-JVM +technologies, the springcloud/spring-cloud-contract Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the /contracts directory and set a few environment variables.

On the Consumer Side

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

To get started, add the dependency to Spring Cloud Contract Stub Runner:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

  • By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands:

    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Note]Note

    The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail.

  • Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub +Runner properties, as shown in the following example:

    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run +the collaborators' stubs for you, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
[Tip]Tip

Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work.

In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs:

2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

2.4.3 Defining the Contract

As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts.

Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method.

Groovy DSL.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */

+

YAML.  +

request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json;charset=UTF-8
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json;charset=UTF-8`

+

2.4.4 Client Side

Spring Cloud Contract generates stubs, which you can use during client-side testing. +You get a running WireMock instance/Messaging route that simulates the service. +You would like to feed that instance with a proper stub definition.

At some point in time, you need to send a request to the Fraud Detection service.

ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);

Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {

After that, during the tests, Spring Cloud Contract automatically finds the stubs +(simulating the real service) in the Maven repository and exposes them on a configured +(or random) port.

2.4.5 Server Side

Since you are developing your stub, you need to be sure that it actually resembles your +concrete implementation. You cannot have a situation where your stub acts in one way and +your application behaves in a different way, especially in production.

To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide.

The autogenerated test looks, more or less, like this:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}

2.5 Step-by-step Guide to Consumer Driven Contracts (CDC)

Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody.

Assume that Loan Issuance is a client to the Fraud Detection server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud.

Technical remark - Fraud Detection has an artifact-id of http-server, while Loan +Issuance has an artifact-id of http-client, and both have a group-id of com.example.

Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication.

The server +side code is available here and the +client code here.

[Tip]Tip

In this case, the producer owns the contracts. Physically, all the contract are +in the producer’s repository.

2.5.1 Technical note

If using the SNAPSHOT / Milestone / Release Candidate versions please add the +following section to your build:

Maven.  +

<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>

+

Gradle.  +

repositories {
+	mavenCentral()
+	mavenLocal()
+	maven { url "https://repo.spring.io/snapshot" }
+	maven { url "https://repo.spring.io/milestone" }
+	maven { url "https://repo.spring.io/release" }
+}

+

2.5.2 Consumer side (Loan Issuance)

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

  1. Start doing TDD by writing a test for your feature.
  2. Write the missing implementation.
  3. Clone the Fraud Detection service repository locally.
  4. Define the contract locally in the repo of Fraud Detection service.
  5. Add the Spring Cloud Contract Verifier plugin.
  6. Run the integration tests.
  7. File a pull request.
  8. Create an initial implementation.
  9. Take over the pull request.
  10. Write the missing implementation.
  11. Deploy your app.
  12. Work online.

Start doing TDD by writing a test for your feature.

@Test
+public void shouldBeRejectedDueToAbnormalLoanAmount() {
+	// given:
+	LoanApplication application = new LoanApplication(new Client("1234567890"),
+			99999);
+	// when:
+	LoanApplicationResult loanApplication = service.loanApplication(application);
+	// then:
+	assertThat(loanApplication.getLoanApplicationStatus())
+			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
+	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
+}

Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description.

Write the missing implementation.

At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the /fraudcheck url via the PUT method.

ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);

For simplicity, the port of the Fraud Detection service is set to 8080, and the +application runs on 8090.

If you start the test at this point, it breaks, because no service currently runs on port +8080.

Clone the Fraud Detection service repository locally.

You can start by playing around with the server side contract. To do so, you must first +clone it.

$ git clone https://your-git-server.com/server-side.git local-http-server-repo

Define the contract locally in the repo of Fraud Detection service.

As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract:

[Important]Important

Place the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important because the producer’s test base class name references that folder.

Groovy DSL.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */

+

YAML.  +

request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json;charset=UTF-8
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json;charset=UTF-8`

+

The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the Chapter 8, Contract DSL section for more information. We highly recommend using the map notation!

[Tip]Tip

You must understand the map notation in order to set up contracts. Please read the +Groovy docs regarding JSON.

The previously shown contract is an agreement between two sides that:

  • if an HTTP request is sent with all of

    • a PUT method on the /fraudcheck endpoint,
    • a JSON body with a client.id that matches the regular expression [0-9]{10} and +loanAmount equal to 99999,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json,
  • then an HTTP response is sent to the consumer that

    • has status 200,
    • contains a JSON body with the fraudCheckStatus field containing a value FRAUD and +the rejectionReason field having value Amount too high,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json.

Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally.

Add the Spring Cloud Contract Verifier plugin.

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the Spring Cloud Contract BOM.

<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

Next, add the Spring Cloud Contract Verifier Maven plugin

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>

Since the plugin was added, you get the Spring Cloud Contract Verifier features which, +from the provided contracts:

  • generate and run tests
  • produce and install stubs

You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute:

$ cd local-http-server-repo
+$ ./mvnw clean install -DskipTests

In the logs, you see something like this:

[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

The following line is extremely important:

[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

It confirms that the stubs of the http-server have been installed in the local +repository.

Run the integration tests.

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (Loan +Application service):

Add the Spring Cloud Contract BOM:

<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release-train.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

Add the dependency to Spring Cloud Contract Stub Runner:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>

Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the +group-id and artifact-id for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you’re playing with the collaborators offline, you +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {

Now, when you run your tests, you see something like this:

2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

This output means that Stub Runner has found your stubs and started a server for your app +with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of +the stubs and with stubs classifier on port 8080.

File a pull request.

What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish.

Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done.

2.5.3 Producer side (Fraud Detection server)

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

Create an initial implementation.

As a reminder, you can see the initial implementation here:

@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}

Take over the pull request.

$ git checkout -b contract-change-pr master
+$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr

You must add the dependencies needed by the autogenerated tests:

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>

In the configuration of the Maven plugin, pass the packageWithBaseClasses property

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
[Important]Important

This example uses "convention based" naming by setting the +packageWithBaseClasses property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +src/test/resources/contracts/fraud. Since you do not have two packages starting from +the contracts folder, pick only one, which should be fraud. Add the Base suffix and +capitalize fraud. That gives you the FraudBase test class name.

All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use Rest Assured MVC to +start the server side FraudDetectionController.

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+
+public class FraudBase {
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(),
+				new FraudStatsController(stubbedStatsProvider()));
+	}
+
+	private StatsProvider stubbedStatsProvider() {
+		return fraudType -> {
+			switch (fraudType) {
+			case DRUNKS:
+				return 100;
+			case ALL:
+				return 200;
+			}
+			return 0;
+		};
+	}
+
+	public void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}

Now, if you run the ./mvnw clean install, you get something like this:

Results :
+
+Tests in error:
+  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...

This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}

If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the +value(consumer(…​), producer(…​)) blocks got injected into the test. +In case of using YAML, the same applied for the matchers sections of the response.

Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the red part of red, green, and +refactor. It is time to convert the red into the green.

Write the missing implementation.

Because you know the expected input and expected output, you can write the missing +implementation:

@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+if (amountGreaterThanThreshold(fraudCheck)) {
+	return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
+}
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}

When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud +Contract Verifier plugin adds the tests to the generated-test-sources, you can +actually run those tests from your IDE.

Deploy your app.

Once you finish your work, you can deploy your change. First, merge the branch:

$ git checkout master
+$ git merge --no-ff contract-change-pr
+$ git push origin master

Your CI might run something like ./mvnw clean deploy, which would publish both the +application and the stub artifacts.

2.5.4 Consumer Side (Loan Issuance) Final Step

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

Merge branch to master.

$ git checkout master
+$ git merge --no-ff contract-change-pr

Work online.

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +stubsMode to REMOTE. The following code shows an example of +achieving the same thing by changing the properties.

stubrunner:
+  ids: 'com.example:http-server-dsl:+:stubs:8080'
+  repositoryRoot: https://repo.spring.io/libs-snapshot

That’s it!

2.6 Dependencies

The best way to add dependencies is to use the proper starter dependency.

For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add +spring-cloud-starter-contract-verifier.

2.7 Additional Links

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development.

2.7.1 Spring Cloud Contract video

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

2.8 Samples

You can find some samples at +samples.

3. Spring Cloud Contract FAQ

3.1 Why use Spring Cloud Contract Verifier and not X ?

For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating +software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

  • Possibility to do CDC with messaging
  • Clear and easy to use, statically typed DSL
  • Possibility to copy paste your current JSON file to the contract and only edit its elements
  • Automatic generation of tests from the defined Contract
  • Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory
  • Spring Cloud integration - no discovery service is needed for integration tests
  • Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality
  • Via Docker adds support for any language & framework used

3.2 I don’t want to write a contract in Groovy!

No problem. You can write a contract in YAML!

3.3 What is this value(consumer(), producer()) ?

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. +What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. +Imagine the following JSON request

{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}

and JSON response

{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the +database) by changing the clock in the system or providing stub implementations of data providers. The same is related +to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system +will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned +JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words +you would like the stub to work like this:

{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "foo"
+}

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks +much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. +So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the +producer’s backend can work on. Such a JSON would be a valid one:

{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to +contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d +have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side +what you might want is the following response:

{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "bar"
+}

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? +In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both +sides of the communication. You can pass the values:

Either via the value method

value(consumer(...), producer(...))
+value(stub(...), test(...))
+value(client(...), server(...))

or using the $() method

$(consumer(...), producer(...))
+$(stub(...), test(...))
+$(client(...), server(...))

You can read more about this in the Chapter 8, Contract DSL section.

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). +Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

[Tip]Tip

If on one side you have passed the regular expression and you haven’t passed the other, then the +other side will get auto-generated.

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression +for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

org.springframework.cloud.contract.spec.Contract.make {
+				request {
+					method 'GET'
+					url '/someUrl'
+					body([
+					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "foo"
+					])
+				}
+			response {
+				status OK()
+				body([
+					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "bar"
+					])
+			}
+}
[Important]Important

Please read the Groovy docs related to JSON to understand how to +properly structure the request / response bodies.

3.4 How to do Stubs versioning?

3.4.1 API Versioning

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are +different approaches.

  • use Hypermedia, links and do not version your API by any means
  • pass versions through headers / urls

I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +business value should be picked.

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. +You can create a subfolder for every version or append it to the contract name - whatever suits you more.

3.4.2 JAR versioning

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of +the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version +looks like this (it got built on the 20.10.2016 at 20:15:21) :

1.0.0.20161020-201521-RELEASE

In that case your generated stub jar will look like this.

1.0.0.20161020-201521-RELEASE-stubs.jar

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the + latest version of the stubs. You can do that by passing the + sign. Example

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar +version. Example for 2.1.1.

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})

3.4.3 Dev or prod stubs

You can manipulate the classifier to run the tests against current development version of the stubs of other services + or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier + once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

Example of tests using development version of stubs

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})

Example of tests using production version of stubs

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})

You can pass those values also via properties from your deployment pipeline.

3.5 Common repo with contracts

Another way of storing contracts other than having them with the producer is keeping them in a common place. +It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep +contracts in a single place then you, as a producer, will know how many consumers you have and which +consumer you will break with your local changes.

3.5.1 Repo structure

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, +client2, client3. Then in the repository with common contracts you would have the following setup +(which you can checkout here):

├── com
+│   └── example
+│       └── server
+│           ├── client1
+│           │   └── expectation.groovy
+│           ├── client2
+│           │   └── expectation.groovy
+│           ├── client3
+│           │   └── expectation.groovy
+│           └── pom.xml
+├── mvnw
+├── mvnw.cmd
+├── pom.xml
+└── src
+    └── assembly
+        └── contracts.xml

As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have +expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL +contract files as described throughout this documentation. This repository has to produce a JAR file that maps +one to one to the contents of the repo.

Example of a pom.xml inside the server folder.

<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example</groupId>
+	<artifactId>server</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Server Stubs</name>
+	<description>POM used to install locally stubs for consumer side</description>
+
+	<parent>
+		<groupId>org.springframework.boot</groupId>
+		<artifactId>spring-boot-starter-parent</artifactId>
+		<version>2.1.3.RELEASE</version>
+		<relativePath/>
+	</parent>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+		<java.version>1.8</java.version>
+		<spring-cloud-contract.version>2.1.2.BUILD-SNAPSHOT</spring-cloud-contract.version>
+		<spring-cloud-release.version>Greenwich.BUILD-SNAPSHOT
+		</spring-cloud-release.version>
+		<excludeBuildFolders>true</excludeBuildFolders>
+	</properties>
+
+	<dependencyManagement>
+		<dependencies>
+			<dependency>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-dependencies</artifactId>
+				<version>${spring-cloud-release.version}</version>
+				<type>pom</type>
+				<scope>import</scope>
+			</dependency>
+		</dependencies>
+	</dependencyManagement>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+				<version>${spring-cloud-contract.version}</version>
+				<extensions>true</extensions>
+				<configuration>
+					<!-- By default it would search under src/test/resources/ -->
+					<contractsDirectory>${project.basedir}</contractsDirectory>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+	<repositories>
+		<repository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+	</repositories>
+	<pluginRepositories>
+		<pluginRepository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+	</pluginRepositories>
+
+</project>

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install + stubs of the producer project.

The pom.xml in the root folder can look like this:

<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example.standalone</groupId>
+	<artifactId>contracts</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Contracts</name>
+	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
+		producers to generate tests and stubs
+	</description>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+	</properties>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<executions>
+					<execution>
+						<id>contracts</id>
+						<phase>prepare-package</phase>
+						<goals>
+							<goal>single</goal>
+						</goals>
+						<configuration>
+							<attach>true</attach>
+							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
+							<!-- If you want an explicit classifier remove the following line -->
+							<appendAssemblyId>false</appendAssemblyId>
+						</configuration>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>project</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.basedir}</directory>
+			<outputDirectory>/</outputDirectory>
+			<useDefaultExcludes>true</useDefaultExcludes>
+			<excludes>
+				<exclude>**/${project.build.directory}/**</exclude>
+				<exclude>mvnw</exclude>
+				<exclude>mvnw.cmd</exclude>
+				<exclude>.mvn/**</exclude>
+				<exclude>src/**</exclude>
+			</excludes>
+		</fileSet>
+	</fileSets>
+</assembly>

3.5.2 Workflow

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference + is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on + common contracts in a common repository.

3.5.3 Consumer

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the +consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) +and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

[Tip]Tip

You need to have Maven installed locally

3.5.4 Producer

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency +of the JAR containing the contracts:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<contractsMode>REMOTE</contractsMode>
+		<contractsRepositoryUrl>
+			https://link/to/your/nexus/or/artifactory/or/sth
+		</contractsRepositoryUrl>
+		<contractDependency>
+			<groupId>com.example.standalone</groupId>
+			<artifactId>contracts</artifactId>
+		</contractDependency>
+	</configuration>
+</plugin>

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from http://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the +tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken +when some incompatible changes are done.

The rest of the flow looks the same.

3.5.5 How can I define messaging contracts per topic not per producer?

To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, +we could create the structure when the rest contracts would be placed in a folder per producer and messaging +contracts in the folder per topic.

For Maven Project

To make it possible to work on the producer side we should specify an inclusion pattern for +filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin +allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid.

<plugin>
+   <groupId>org.springframework.cloud</groupId>
+   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+   <version>${spring-cloud-contract.version}</version>
+   <configuration>
+      <contractsMode>REMOTE</contractsMode>
+      <contractsRepositoryUrl>http://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
+      <contractDependency>
+         <groupId>com.example</groupId>
+         <artifactId>common-repo-with-contracts</artifactId>
+         <version>+</version>
+      </contractDependency>
+      <contractsPath>/</contractsPath>
+      <baseClassMappings>
+         <baseClassMapping>
+            <contractPackageRegex>.*messaging.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
+         </baseClassMapping>
+         <baseClassMapping>
+            <contractPackageRegex>.*rest.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
+         </baseClassMapping>
+      </baseClassMappings>
+      <includedFiles>
+         <includedFile>**/${project.artifactId}/**</includedFile>
+         <includedFile>**/${first-topic}/**</includedFile>
+         <includedFile>**/${second-topic}/**</includedFile>
+      </includedFiles>
+   </configuration>
+</plugin>

For Gradle Project

  • Add a custom configuration for the common-repo dependency:
ext {
+    conractsGroupId = "com.example"
+    contractsArtifactId = "common-repo"
+    contractsVersion = "1.2.3"
+}
+
+configurations {
+    contracts {
+        transitive = false
+    }
+}
  • Add the common-repo dependency to your classpath:
dependencies {
+    contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+    testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+}
  • Download the dependency to an appropriate folder:
task getContracts(type: Copy) {
+    from configurations.contracts
+    into new File(project.buildDir, "downloadedContracts")
+}
  • Unzip JAR:
task unzipContracts(type: Copy) {
+    def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
+    def outputDir = file("${buildDir}/unpackedContracts")
+
+    from zipTree(zipFile)
+    into outputDir
+}
  • Cleanup unused contracts:
task deleteUnwantedContracts(type: Delete) {
+    delete fileTree(dir: "${buildDir}/unpackedContracts",
+        include: "**/*",
+        excludes: [
+            "**/${project.name}/**"",
+            "**/${first-topic}/**",
+            "**/${second-topic}/**"])
+}
  • Create task dependencies:
unzipContracts.dependsOn("getContracts")
+deleteUnwantedContracts.dependsOn("unzipContracts")
+build.dependsOn("deleteUnwantedContracts")
  • Configure plugin by specifying the directory containing contracts using contractsDslDir property
contracts {
+    contractsDslDir = new File("${buildDir}/unpackedContracts")
+}

3.6 Do I need a Binary Storage? Can’t I use Git?

In the polyglot world, there are languages that don’t use binary storages like +Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide +mechanisms to store contracts and stubs in a SCM repository. Currently the +only supported SCM is Git.

The repository would have to the following setup +(which you can checkout here):

.
+└── META-INF
+    └── com.example
+        └── beer-api-producer-git
+            └── 0.0.1-SNAPSHOT
+                ├── contracts
+                │   └── beer-api-consumer
+                │       ├── messaging
+                │       │   ├── shouldSendAcceptedVerification.groovy
+                │       │   └── shouldSendRejectedVerification.groovy
+                │       └── rest
+                │           ├── shouldGrantABeerIfOldEnough.groovy
+                │           └── shouldRejectABeerIfTooYoung.groovy
+                └── mappings
+                    └── beer-api-consumer
+                        └── rest
+                            ├── shouldGrantABeerIfOldEnough.json
+                            └── shouldRejectABeerIfTooYoung.json

Under META-INF folder:

  • we group applications via groupId (e.g. com.example)
  • then each application is represented via the artifactId (e.g. beer-api-producer-git)
  • next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning)

    • + or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:

      • if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT
      • if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE
      • if you have a version called latest or + we will pick that folder
    • release - to find the latest release version of your stubs. That means:

      • if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE
      • if you have a version called release we will pick that folder
  • finally, there are two folders:

    • contracts - the good practice is to store the contracts required by each +consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you +can use the stubs-per-consumer feature. Further directory structure is arbitrary.
    • mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push +the stub server mappings. On the consumer side, Stub Runner will scan this folder +to start stub servers with stub definitions. The folder structure will be a copy +of the one created in the contracts subfolder.

3.6.1 Protocol convention

In order to control the type and location of the source of contracts (whether it’s +a binary storage or an SCM repository), you can use the protocol in the URL of +the repository. Spring Cloud Contract iterates over registered protocol resolvers +and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).

For the SCM functionality, currently, we support the Git repository. To use it, +in the property, where the repository URL needs to be placed you just have to prefix +the connection URL with git://. Here you can find a couple of examples:

git://file:///foo/bar
+git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git

3.6.2 Producer

For the producer, to use the SCM approach, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the SCM implementation via the URL that contains +the git:// protocol.

[Important]Important

You have to manually add the pushStubsToScm +goal in Maven or execute (bind) the pushStubsToScm task in +Gradle. We don’t push stubs to origin of your git +repository out of the box.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>

+

Gradle.  +

contracts {
+	// We want to pick contracts from a Git repository
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:${project.version}"
+	}
+	/*
+	We reuse the contract dependency section to set up the path
+	to the folder that contains the contract definitions. In our case the
+	path will be /groupId/artifactId/version/contracts
+	 */
+	contractRepository {
+		repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publish.dependsOn("publishStubsToScm")

+

With such a setup:

  • Git project will be cloned to a temporary directory
  • The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder +to find contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/contracts
  • Tests will be generated from the contracts
  • Stubs will be created from the contracts
  • Once the tests pass, the stubs will be committed in the cloned repository
  • Finally, a push will be done to that repo’s origin

3.6.3 Producer with contracts stored locally

Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.

Maven.  +

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<!-- In the default configuration, we want to use the contracts stored locally -->
+	<configuration>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*messaging.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerMessagingBase</baseClassFQN>
+			</baseClassMapping>
+			<baseClassMapping>
+				<contractPackageRegex>.*rest.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerRestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+		<basePackageForTests>com.example</basePackageForTests>
+	</configuration>
+	<executions>
+		<execution>
+			<phase>package</phase>
+			<goals>
+				<!-- By default we will not push the stubs back to SCM,
+				you have to explicitly add it as a goal -->
+				<goal>pushStubsToScm</goal>
+			</goals>
+			<configuration>
+				<!-- We want to pick contracts from a Git repository -->
+				<contractsRepositoryUrl>git://file://${env.ROOT}/target/contract_empty_git/
+				</contractsRepositoryUrl>
+				<!-- Example of URL via git protocol -->
+				<!--<contractsRepositoryUrl>git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- Example of URL via http protocol -->
+				<!--<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- We reuse the contract dependency section to set up the path
+				to the folder that contains the contract definitions. In our case the
+				path will be /groupId/artifactId/version/contracts -->
+				<contractDependency>
+					<groupId>${project.groupId}</groupId>
+					<artifactId>${project.artifactId}</artifactId>
+					<version>${project.version}</version>
+				</contractDependency>
+				<!-- The mode can't be classpath -->
+				<contractsMode>LOCAL</contractsMode>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>

+

Gradle.  +

contracts {
+		// Base package for generated tests
+	basePackageForTests = "com.example"
+	baseClassMappings {
+		baseClassMapping(".*messaging.*", "com.example.BeerMessagingBase")
+		baseClassMapping(".*rest.*", "com.example.BeerRestBase")
+	}
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publishStubsToScm {
+	// We want to modify the default set up of the plugin when publish stubs to scm is called
+	customize {
+		// We want to pick contracts from a Git repository
+		contractDependency {
+			stringNotation = "${project.group}:${project.name}:${project.version}"
+		}
+		/*
+		We reuse the contract dependency section to set up the path
+		to the folder that contains the contract definitions. In our case the
+		path will be /groupId/artifactId/version/contracts
+		 */
+		contractRepository {
+			repositoryUrl = "git://file://${System.getenv("ROOT")}/target/contract_empty_git/"
+		}
+		// The mode can't be classpath
+		contractsMode = "LOCAL"
+	}
+}
+
+publish.dependsOn("publishStubsToScm")
+publishToMavenLocal.dependsOn("publishStubsToScm")

+

With such a setup:

  • Contracts from the default src/test/resources/contracts directory will be picked
  • Tests will be generated from the contracts
  • Stubs will be created from the contracts
  • Once the tests pass

    • Git project will be cloned to a temporary directory
    • The stubs and contracts will be committed in the cloned repository
  • Finally, a push will be done to that repo’s origin

Keeping contracts with the producer and stubs in an external repository

It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. +This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to +use an artifact repository for storing the stubs.

In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set +contractsRepositoryUrl to the repository where you want to keep the stubs.

3.6.4 Consumer

On the consumer side when passing the repositoryRoot parameter, +either from the @AutoConfigureStubRunner annotation, the +JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the +SCM repository, prefixed with the protocol. For example

@AutoConfigureStubRunner(
+    stubsMode="REMOTE",
+    repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
+    ids="com.example:bookstore:0.0.1.RELEASE"
+)

With such a setup:

  • Git project will be cloned to a temporary directory
  • The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder +to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/
  • Stub servers will be started and fed with mappings
  • Messaging definitions will be read and used in the messaging tests

3.7 Can I use the Pact Broker?

When using Pact you can use the Pact Broker +to store and share Pact definitions. Starting from Spring Cloud Contract +2.0.0 one can fetch Pact files from the Pact Broker to generate +tests and stubs.

As a prerequisite the Pact Converter and Pact Stub Downloader +are required. You have to add them via the spring-cloud-contract-pact dependency. +You can read more about it in the Section 10.1.1, “Pact Converter” section.

[Important]Important

Pact follows the Consumer Contract convention. That means +that the Consumer creates the Pact definitions first, then +shares the files with the Producer. Those expectations are generated +from the Consumer’s code and can break the Producer if the expectations +are not met.

3.7.1 Pact Consumer

The consumer uses Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. An example of such +setup can be found here.

3.7.2 Producer

For the producer, to use the Pact files from the Pact Broker, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the Pact implementation via the URL that contains +the pact:// protocol. It’s enough to pass the URL to the +Pact Broker. An example of such setup can be found here.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <!-- When + is passed, a latest tag will be applied when fetching pacts -->
+            <version>+</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-pact</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+    </dependencies>
+</plugin>

+

Gradle.  +

buildscript {
+	repositories {
+		//...
+	}
+
+	dependencies {
+		// ...
+		// Don't forget to add spring-cloud-contract-pact to the classpath!
+		classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
+	}
+}
+
+contracts {
+	// When + is passed, a latest tag will be applied when fetching pacts
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:+"
+	}
+	contractRepository {
+		repositoryUrl = "pact://http://localhost:8085"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}

+

With such a setup:

  • Pact files will be downloaded from the Pact Broker
  • Spring Cloud Contract will convert the Pact files into tests and stubs
  • The JAR with the stubs gets automatically created as usual

3.7.3 Pact Consumer (Producer Contract approach)

In the scenario where you don’t want to do Consumer Contract approach +(for every single consumer define the expectations) but you’d prefer +to do Producer Contracts (the producer provides the contracts and +publishes stubs), it’s enough to use Spring Cloud Contract with +Stub Runner option. An example of such setup can be found here.

First, remember to add Stub Runner and Spring Cloud Contract Pact module +as test dependencies.

Maven.  +

<dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-dependencies</artifactId>
+            <version>${spring-cloud.version}</version>
+            <type>pom</type>
+            <scope>import</scope>
+        </dependency>
+    </dependencies>
+</dependencyManagement>
+
+<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+<dependencies>
+    <!-- ... -->
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+        <scope>test</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-contract-pact</artifactId>
+        <scope>test</scope>
+    </dependency>
+</dependencies>

+

Gradle.  +

dependencyManagement {
+    imports {
+        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
+    }
+}
+
+dependencies {
+    //...
+    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
+    // Don't forget to add spring-cloud-contract-pact to the classpath!
+    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
+}

+

Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed +with pact:// protocol. E.g. pact://http://localhost:8085

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		ids = "com.example:beer-api-producer-pact",
+		repositoryRoot = "pact://http://localhost:8085")
+public class BeerControllerTest {
+    //Inject the port of the running stub
+    @StubRunnerPort("beer-api-producer-pact") int producerPort;
+    //...
+}

With such a setup:

  • Pact files will be downloaded from the Pact Broker
  • Spring Cloud Contract will convert the Pact files into stub definitions
  • The stub servers will be started and fed with stubs

For more information about Pact support you can go to +the Section 10.7, “Using the Pact Stub Downloader” section.

3.8 How can I debug the request/response being sent by the generated tests client?

The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

logging.level.org.apache.http.wire=DEBUG

3.8.1 How can I debug the mapping/request/response being sent by WireMock?

Starting from version 1.2.0 we turn on WireMock logging to +info and the WireMock notifier to being verbose. Now you will +exactly know what request was received by WireMock server and which +matching response definition was picked.

To turn off this feature just bump WireMock logging to ERROR

logging.level.com.github.tomakehurst.wiremock=ERROR

3.8.2 How can I see what got registered in the HTTP server stub?

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or +`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server +was started will be attached.

3.8.3 Can I reference text from file?

Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays. +If you’re using YAML just use the bodyFromFile property.

4. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in the following ways:

4.1 Gradle Project

To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections:

4.1.1 Prerequisites

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin.

[Warning]Warning

If you want to use Spock in your projects, you must add separately the +spock-core and spock-spring modules. Check Spock +docs for more information

4.1.2 Add Gradle Plugin with Dependencies

To add a Gradle plugin with dependencies, use code similar to this:

buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+	    classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+	}
+}
+
+apply plugin: 'groovy'
+apply plugin: 'spring-cloud-contract'
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
+	}
+}
+
+dependencies {
+	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
+	// example with adding Spock core and Spock Spring
+	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
+	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}

4.1.3 Gradle and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here:

buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+	    classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+		classpath "com.jayway.restassured:rest-assured:2.5.0"
+		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
+	}
+}
+
+depenendencies {
+    // all dependencies
+    // you can exclude rest-assured from spring-cloud-contract-verifier
+    testCompile "com.jayway.restassured:rest-assured:2.5.0"
+    testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
+}

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly.

4.1.4 Snapshot Versions for Gradle

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+}

4.1.5 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory.

The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure:

src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods:

  • shouldCreateUser()
  • shouldReturnUser()

4.1.6 Run the Plugin

The plugin registers itself to be invoked before a check task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the generateContractTests task.

4.1.7 Default Setup

The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode):

contracts {
+    testFramework ='JUNIT'
+    testMode = 'MockMvc'
+    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
+    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
+    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
+    basePackageForTests = 'org.springframework.cloud.verifier.tests'
+    stubsOutputDir = project.file("${project.buildDir}/stubs")
+
+    // the following properties are used when you want to provide where the JAR with contract lays
+    contractDependency {
+        stringNotation = ''
+    }
+    contractsPath = ''
+    contractsWorkOffline = false
+    contractRepository {
+        cacheDownloadedContracts(true)
+    }
+}
+
+tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
+    baseName = project.name
+    classifier = contracts.stubsSuffix
+    from contractVerifier.stubsOutputDir
+}
+
+project.artifacts {
+    archives task
+}
+
+tasks.create(type: Copy, name: 'copyContracts') {
+    from contracts.contractsDslDir
+    into contracts.stubsOutputDir
+}
+
+verifierStubsJar.dependsOn 'copyContracts'
+
+publishing {
+    publications {
+        stubs(MavenPublication) {
+            artifactId project.name
+            artifact verifierStubsJar
+        }
+    }
+}

4.1.8 Configure Plugin

To change the default configuration, add a contracts snippet to your Gradle config, as +shown here:

contracts {
+	testMode = 'MockMvc'
+	baseClassForTests = 'org.mycompany.tests'
+	generatedTestSourcesDir = project.file('src/generatedContract')
+}

4.1.9 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.
  • imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array.
  • staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests.
  • baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test +classes.
  • ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array.
  • contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts.
  • stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed.
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

The following properties are used when you want to specify the location of the JAR +containing the contracts:

  • contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up.
  • contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory.
  • contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.)
  • deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.1.10 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}

If you use Explicit mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this +base class should also contain a protected WebTarget webTarget field. Right now, the +only option to test the JAX-RS API is to start a web server.

4.1.11 Different Base Classes for Contracts

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

  • Follow a convention by providing the packageWithBaseClasses
  • Provide explicit mapping via baseClassMappings

By Convention

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

packageWithBaseClasses = 'com.example.base'

By Mapping

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

baseClassForTests = "com.example.FooBase"
+baseClassMappings {
+	baseClassMapping('.*/com/.*', 'com.example.ComBase')
+	baseClassMapping('.*/bar/.*': 'com.example.BarBase')
+}

Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

4.1.12 Invoking Generated Tests

To ensure that the provider side is compliant with defined contracts, you need to invoke:

./gradlew generateContractTests test

4.1.13 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example:

$ ./gradlew pushStubsToScm

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable.

4.1.14 Spring Cloud Contract Verifier on the Consumer Side

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in src/test/resources/contracts and generate +WireMock JSON stubs using:

./gradlew generateClientStubs
[Note]Note

The stubsOutputDir option has to be set for stub generation to work.

When present, JSON stubs can be used in automated tests of consuming a service.

@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
+class LoanApplicationServiceSpec extends Specification {
+
+ @ClassRule
+ @Shared
+ WireMockClassRule wireMockRule == new WireMockClassRule()
+
+ @Autowired
+ LoanApplicationService sut
+
+ def 'should successfully apply for loan'() {
+   given:
+ 	LoanApplication application =
+			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
+   when:
+	LoanApplicationResult loanApplication == sut.loanApplication(application)
+   then:
+	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
+	loanApplication.rejectionReason == null
+ }
+}

LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

4.2 Maven Project

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections:

4.2.1 Add maven plugin

Add the Spring Cloud Contract BOM in a fashion similar to this:

<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

Next, add the Spring Cloud Contract Verifier Maven plugin:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>

You can read more in the +Spring +Cloud Contract Maven Plugin Documentation (example for 2.0.0.RELEASE version).

4.2.2 Maven and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here:

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <packageWithBaseClasses>com.example</packageWithBaseClasses>
+    </configuration>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-verifier</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>rest-assured</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>spring-mock-mvc</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+    </dependencies>
+</plugin>
+
+<dependencies>
+    <!-- all dependencies -->
+    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>rest-assured</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>spring-mock-mvc</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+</dependencies>

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly.

4.2.3 Snapshot versions for Maven

For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here:

<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>

4.2.4 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure:

src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods

  • shouldCreateUser()
  • shouldReturnUser()

4.2.5 Run plugin

The plugin goal generateTests is assigned to be invoked in the phase called +generate-test-sources. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the generateTests goal.

4.2.6 Configure plugin

To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here:

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <executions>
+        <execution>
+            <goals>
+                <goal>convert</goal>
+                <goal>generateStubs</goal>
+                <goal>generateTests</goal>
+            </goals>
+        </execution>
+    </executions>
+    <configuration>
+        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
+        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
+    </configuration>
+</plugin>

4.2.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test +classes.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.
  • contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix.
  • baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

If you want to download your contract definitions from a Maven repository, you can use +the following options:

  • contractDependency: The contract dependency that contains all the packaged contracts.
  • contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated.
  • contractsMode: Picks the mode in which stubs will be found and registered
  • deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories
  • contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones.
  • contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.
  • contractsRepositoryPassword: The password to be used to connect to the repo with contracts.
  • contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.
  • contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

We cache only non-snapshot, explicitly provided versions (for example ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.2.8 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

package org.mycompany.tests
+
+import org.mycompany.ExampleSpringController
+import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
+import spock.lang.Specification
+
+class MvcSpec extends Specification {
+  def setup() {
+   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
+  }
+}

You can also setup the whole context if necessary.

import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@Autowired
+	WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.webAppContextSetup(this.context);
+	}
+}

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests.

import io.restassured.RestAssured;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@LocalServerPort
+	int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost:" + this.port;
+	}
+}

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right +now, the only option to test the JAX-RS API is to start a web server.

4.2.9 Different base classes for contracts

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

  • Follow a convention by providing the packageWithBaseClasses
  • provide explicit mapping via baseClassMappings

By Convention

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<packageWithBaseClasses>hello</packageWithBaseClasses>
+	</configuration>
+</plugin>

By Mapping

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<baseClassForTests>com.example.FooBase</baseClassForTests>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*com.*</contractPackageRegex>
+				<baseClassFQN>com.example.TestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+</plugin>

Assume that you have contracts under these two locations: +* src/test/resources/contract/com/ +* src/test/resources/contract/foo/

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

4.2.10 Invoking generated tests

The Spring Cloud Contract Maven Plugin generates verification code in a directory called +/generated-test-sources/contractVerifier and attaches this directory to testCompile +goal.

For Groovy Spock code, use the following:

<plugin>
+	<groupId>org.codehaus.gmavenplus</groupId>
+	<artifactId>gmavenplus-plugin</artifactId>
+	<version>1.5</version>
+	<executions>
+		<execution>
+			<goals>
+				<goal>testCompile</goal>
+			</goals>
+		</execution>
+	</executions>
+	<configuration>
+		<testSources>
+			<testSource>
+				<directory>${project.basedir}/src/test/groovy</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+			<testSource>
+				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+		</testSources>
+	</configuration>
+</plugin>

To ensure that provider side is compliant with defined contracts, you need to invoke +mvn generateTest test.

4.2.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example:

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable.

4.2.12 Maven Plugin and STS

If you see the following exception while using STS:

STS Exception

When you click on the error marker you should see something like this:

 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
+ cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
+ org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
+...
+ org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
+ org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
+ org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at

In order to fix this issue, provide the following section in your pom.xml:

<build>
+    <pluginManagement>
+        <plugins>
+            <!--This plugin's configuration is used to store Eclipse m2e settings
+                only. It has no influence on the Maven build itself. -->
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                             <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.springframework.cloud</groupId>
+                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                    <versionRange>[1.0,)</versionRange>
+                                    <goals>
+                                        <goal>convert</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <execute />
+                                </action>
+                             </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+        </plugins>
+    </pluginManagement>
+</build>

4.2.13 Maven Plugin with Spock Tests

You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly.

First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below:

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example:

4.3 Stubs and Transitive Dependencies

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom:

├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
+├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
+├── ...
+└── ...

There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies:

  • Mark all application dependencies as optional
  • Create a separate artifactid for the stubs
  • Exclude dependencies on the consumer side

Mark all application dependencies as optional

If, in the github-webhook application, you mark all of your dependencies as optional, +when you include the github-webhook stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded.

Create a separate artifactid for the stubs

If you create a separate artifactid, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all.

Exclude dependencies on the consumer side

As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies.

4.4 Scenarios

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example:

my_contracts_dir\
+  scenario1\
+    1_login.groovy
+    2_showCart.groovy
+    3_logout.groovy

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps:

  1. login marked as Started pointing to…​
  2. showCart marked as Step1 pointing to…​
  3. logout marked as Step2 which will close the scenario.

More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

4.5 Docker Project

We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application.

[Tip]Tip

The EXPLICIT mode means that the tests generated from contracts will send +real requests and not the mocked ones.

4.5.1 Short intro to Maven, JARs and Binary storage

Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults.

Part of the following definitions were taken from the Maven Glossary

  • Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects.
  • Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group.
  • JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file.
  • GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/.
  • Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier.
  • Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus.

4.5.2 How it works

The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes).

It’s enough for you to mount your contracts, pass the environment variables + and the image will:

  • generate the contract tests
  • execute the tests against the provided URL
  • generate the WireMock stubs
  • (optional - turned on by default) publish the stubs to a Artifact Manager

Environment Variables

The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc.

  • PROJECT_GROUP - your project’s group id. Defaults to com.example
  • PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT
  • PROJECT_NAME - artifact id. Defaults to example
  • REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally
  • REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured
  • REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured
  • PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

  • EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example
  • EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.
  • EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default
  • EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest
  • EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally
  • EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.
  • EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

These environment variables are used when tests are executed:

  • APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work)
  • APPLICATION_USERNAME - (optional) username for basic authentication to your application
  • APPLICATION_PASSWORD - (optional) password for basic authentication to your application

4.5.3 Example of usage

Let’s take a look at a simple MVC application

$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore

The contracts are available under /contracts folder.

4.5.4 Server side (nodejs)

Since we want to run tests, we could just execute:

$ npm test

however, for learning purposes, let’s split it into pieces:

# Stop docker infra (nodejs, artifactory)
+$ ./stop_infra.sh
+# Start docker infra (nodejs, artifactory)
+$ ./setup_infra.sh
+
+# Kill & Run app
+$ pkill -f "node app"
+$ nohup node app &
+
+# Prepare environment variables
+$ SC_CONTRACT_DOCKER_VERSION="..."
+$ APP_IP="192.168.0.100"
+$ APP_PORT="3000"
+$ ARTIFACTORY_PORT="8081"
+$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
+$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
+$ CURRENT_DIR="$( pwd )"
+$ CURRENT_FOLDER_NAME=${PWD##*/}
+$ PROJECT_VERSION="0.0.1.RELEASE"
+
+# Execute contract tests
+$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
+
+# Kill app
+$ pkill -f "node app"

What will happen is that via bash scripts:

  • infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time.
  • due to those constraints the contracts also represent the +stateful situation

    • first request is a POST that causes data to get inserted to the database
    • second request is a GET that returns a list of data with 1 previously inserted element
  • the NodeJS application will be started (on port 3000)
  • contract tests will be generated via Docker and tests +will be executed against the running application

    • the contracts will be taken from /contracts folder.
    • the output of the test execution is available under +node_modules/spring-cloud-contract/output.
  • the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

To see how the client side looks like check out the Section 6.9, “Stub Runner Docker” section.

5. Spring Cloud Contract Verifier Messaging

Spring Cloud Contract Verifier lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that.

5.1 Integrations

You can use one of the following four integration configurations:

  • Apache Camel
  • Spring Integration
  • Spring Cloud Stream
  • Spring AMQP

Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up.

[Important]Important

Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work.

[Important]Important

If you want to use Spring Cloud Stream, remember to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support, as shown here:

Maven.  +

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

+

5.2 Manual Integration Testing

The main interface used by the tests is +org.springframework.cloud.contract.verifier.messaging.MessageVerifier. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal.

In a test, you can inject a ContractVerifierMessageExchange to send and receive +messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. +Here’s an example:

@RunWith(SpringTestRunner.class)
+@SpringBootTest
+@AutoConfigureMessageVerifier
+public static class MessagingContractTests {
+
+  @Autowired
+  private MessageVerifier verifier;
+  ...
+}
[Note]Note

If your tests require stubs as well, then @AutoConfigureStubRunner includes the +messaging configuration, so you only need the one annotation.

5.3 Publisher-Side Test Generation

Having the input or outputMessage sections in your DSL results in creation of tests +on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5 or Spock tests.

There are 3 main scenarios that we should take into consideration:

  • Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler).
  • Scenario 2: The input message triggers an output message.
  • Scenario 3: The input message is consumed and there is no output message.
[Important]Important

The destination passed to messageFrom or sentTo can have different +meanings for different messaging implementations. For Stream and Integration it is +first resolved as a destination of a channel. Then, if there is no such destination +it is resolved as a channel name. For Camel, that’s a certain component (for example, +jms).

5.3.1 Scenario 1: No Input Message

For the given contract:

Groovy DSL.  +

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					triggeredBy('bookReturnedTriggered()')
+				}
+				outputMessage {
+					sentTo('activemq:output')
+					body('''{ "bookName" : "foo" }''')
+					headers {
+						header('BOOK-NAME', 'foo')
+						messagingContentType(applicationJson())
+					}
+				}
+			}

+

YAML.  +

label: some_label
+input:
+  triggeredBy: bookReturnedTriggered
+outputMessage:
+  sentTo: activemq:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+    contentType: application/json

+

The following JUnit test is created:

					'''
+ // when:
+  bookReturnedTriggered();
+
+ // then:
+  ContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
+  assertThat(response).isNotNull();
+  assertThat(response.getHeader("BOOK-NAME")).isNotNull();
+  assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+  assertThat(response.getHeader("contentType")).isNotNull();
+  assertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");
+ // and:
+  DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+  assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
+'''

And the following Spock test would be created:

					'''
+ when:
+  bookReturnedTriggered()
+
+ then:
+  ContractVerifierMessage response = contractVerifierMessaging.receive('activemq:output')
+  assert response != null
+  response.getHeader('BOOK-NAME')?.toString()  == 'foo'
+  response.getHeader('contentType')?.toString()  == 'application/json'
+ and:
+  DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
+  assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
+
+'''

5.3.2 Scenario 2: Output Triggered by Input

For the given contract:

Groovy DSL.  +

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					messageFrom('jms:input')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+				}
+				outputMessage {
+					sentTo('jms:output')
+					body([
+							bookName: 'foo'
+					])
+					headers {
+						header('BOOK-NAME', 'foo')
+					}
+				}
+			}

+

YAML.  +

label: some_label
+input:
+  messageFrom: jms:input
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+outputMessage:
+  sentTo: jms:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo

+

The following JUnit test is created:

					'''
+// given:
+ ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+  "{\\"bookName\\":\\"foo\\"}"
+, headers()
+  .header("sample", "header"));
+
+// when:
+ contractVerifierMessaging.send(inputMessage, "jms:input");
+
+// then:
+ ContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
+ assertThat(response).isNotNull();
+ assertThat(response.getHeader("BOOK-NAME")).isNotNull();
+ assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+ assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
+'''

And the following Spock test would be created:

					"""\
+given:
+   ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+    '''{"bookName":"foo"}''',
+    ['sample': 'header']
+  )
+
+when:
+   contractVerifierMessaging.send(inputMessage, 'jms:input')
+
+then:
+   ContractVerifierMessage response = contractVerifierMessaging.receive('jms:output')
+   assert response !- null
+   response.getHeader('BOOK-NAME')?.toString()  == 'foo'
+and:
+   DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
+   assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
+"""

5.3.3 Scenario 3: No Output Message

For the given contract:

Groovy DSL.  +

			def contractDsl = Contract.make {
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}

+

YAML.  +

label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()

+

The following JUnit test is created:

					'''
+// given:
+ ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+	"{\\"bookName\\":\\"foo\\"}"
+, headers()
+	.header("sample", "header"));
+
+// when:
+ contractVerifierMessaging.send(inputMessage, "jms:delete");
+
+// then:
+ bookWasDeleted();
+'''

And the following Spock test would be created:

					'''
+given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()
+'''

5.4 Consumer Stub Generation

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

For more information, see Chapter 7, Stub Runner for Messaging section.

Maven.  +

<dependencies>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
+	</dependency>
+
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+		<scope>test</scope>
+	</dependency>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-stream-test-support</artifactId>
+		<scope>test</scope>
+	</dependency>
+</dependencies>
+
+<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>Greenwich.BUILD-SNAPSHOT</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>

+

Gradle.  +

ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}

+

6. Spring Cloud Contract Stub Runner

One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging.

Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you.

6.1 Snapshot versions

Add the additional snapshot repository to your build.gradle file to use snapshot +versions, which are automatically uploaded after every successful build:

Maven.  +

<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>

+

Gradle.  +

buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}

+

6.2 Publishing Stubs as JARs

The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository.

[Tip]Tip

For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to.

Maven.  +

<!-- First disable the default jar setup in the properties section -->
+<!-- we don't want the verifier to do a jar for us -->
+<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+
+<!-- Next add the assembly plugin to your build -->
+<!-- we want the assembly plugin to generate the JAR -->
+<plugin>
+	<groupId>org.apache.maven.plugins</groupId>
+	<artifactId>maven-assembly-plugin</artifactId>
+	<executions>
+		<execution>
+			<id>stub</id>
+			<phase>prepare-package</phase>
+			<goals>
+				<goal>single</goal>
+			</goals>
+			<inherited>false</inherited>
+			<configuration>
+				<attach>true</attach>
+				<descriptors>
+					${basedir}/src/assembly/stub.xml
+				</descriptors>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>src/main/java</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/classes</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>

+

Gradle.  +

ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}

+

6.3 Stub Runner Core

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +Consumer Driven Contracts.

Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. +For messaging, special stub routes are defined.

6.3.1 Retrieving stubs

You can pick the following options of acquiring stubs

  • Aether based solution that downloads JARs with stubs from Artifactory / Nexus
  • Classpath scanning solution that searches classpath via pattern to retrieve stubs
  • Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

The latter example is described in the Custom Stub Runner section.

Stub downloading

You can control the stub downloading via the stubsMode switch. It picks value from the +StubRunnerProperties.StubsMode enum. You can use the following options

  • StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath
  • StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)
  • StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

Example:

@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)

Classpath scanning

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH +(or set nothing since CLASSPATH is the default value) then classpath will get scanned. +Let’s look at the following example:

@AutoConfigureStubRunner(ids = {
+    "com.example:beer-api-producer:+:stubs:8095",
+    "com.example.foo:bar:1.0.0:superstubs:8096"
+})

If you’ve added the dependencies to your classpath

Maven.  +

<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>beer-api-producer-restdocs</artifactId>
+    <classifier>stubs</classifier>
+    <version>0.0.1-SNAPSHOT</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+<dependency>
+    <groupId>com.example.foo</groupId>
+    <artifactId>bar</artifactId>
+    <classifier>superstubs</classifier>
+    <version>1.0.0</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>

+

Gradle.  +

testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
+    transitive = false
+}
+testCompile("com.example.foo:bar:1.0.0:superstubs") {
+    transitive = false
+}

+

Then the following locations on your classpath will get scanned. For com.example:beer-api-producer-restdocs

  • /META-INF/com.example/beer-api-producer-restdocs/*/.*
  • /contracts/com.example/beer-api-producer-restdocs/*/.*
  • /mappings/com.example/beer-api-producer-restdocs/*/.*

and com.example.foo:bar

  • /META-INF/com.example.foo/bar/*/.*
  • /contracts/com.example.foo/bar/*/.*
  • /mappings/com.example.foo/bar/*/.*
[Tip]Tip

As you can see you have to explicitly provide the group and artifact ids when packaging the +producer stubs.

The producer would setup the contracts like this:

└── src
+    └── test
+        └── resources
+            └── contracts
+                └── com.example
+                    └── beer-api-producer-restdocs
+                        └── nested
+                            └── contract3.groovy

To achieve proper stub packaging.

Or using the Maven assembly plugin or +Gradle Jar task you have to create the following +structure in your stubs jar.

└── META-INF
+    └── com.example
+        └── beer-api-producer-restdocs
+            └── 2.0.0
+                ├── contracts
+                │   └── nested
+                │       └── contract2.groovy
+                └── mappings
+                    └── mapping.json

By maintaining this structure classpath gets scanned and you can profit from the messaging / +HTTP stubs without the need to download artifacts.

Configuring HTTP Server Stubs

Stub Runner has a notion of a HttpServerStub that abstracts the underlaying +concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). +Sometimes, you need to perform some additional tuning of the stub servers, +that is concrete for the given implementation. To do that, Stub Runner gives you +the httpServerStubConfigurer property that is available in the annotation, +JUnit rule, and is accessible via system properties, where you can provide +your implementation of the org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer interface. The implementations can alter +the configuration files for the given HTTP server stub.

Spring Cloud Contract Stub Runner comes with an implementation that you +can extend, for WireMock - org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. In the configure method +you can provide your own, custom configuration for the given stub. The use +case might be starting WireMock for the given artifact id, on an HTTPs port. Example:

WireMockHttpServerStubConfigurer implementation.  +

@CompileStatic
+static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+	private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+	@Override
+	WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+		if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+			int httpsPort = SocketUtils.findAvailableTcpPort()
+			log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+			return httpStubConfiguration
+					.httpsPort(httpsPort)
+		}
+		return httpStubConfiguration
+	}
+}

+

You can then reuse it via the annotation

@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)

Whenever an https port is found, it will take precedence over the http one.

6.3.2 Running stubs

Running using main app

You can set the following options to the main class:

-c, --classifier                Suffix for the jar containing stubs (e.
+                                  g. 'stubs' if the stub jar would
+                                  have a 'stubs' classifier for stubs:
+                                  foobar-stubs ). Defaults to 'stubs'
+                                  (default: stubs)
+--maxPort, --maxp <Integer>     Maximum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  15000 (default: 15000)
+--minPort, --minp <Integer>     Minimum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  10000 (default: 10000)
+-p, --password                  Password to user when connecting to
+                                  repository
+--phost, --proxyHost            Proxy host to use for repository
+                                  requests
+--pport, --proxyPort [Integer]  Proxy port to use for repository
+                                  requests
+-r, --root                      Location of a Jar containing server
+                                  where you keep your stubs (e.g. http:
+                                  //nexus.
+                                  net/content/repositories/repository)
+-s, --stubs                     Comma separated list of Ivy
+                                  representation of jars with stubs.
+                                  Eg. groupid:artifactid1,groupid2:
+                                  artifactid2:classifier
+--sm, --stubsMode               Stubs mode to be used. Acceptable values
+                                  [CLASSPATH, LOCAL, REMOTE]
+-u, --username                  Username to user when connecting to
+                                  repository

HTTP Stubs

Stubs are defined in JSON documents, whose syntax is defined in WireMock documentation

Example:

{
+    "request": {
+        "method": "GET",
+        "url": "/ping"
+    },
+    "response": {
+        "status": 200,
+        "body": "pong",
+        "headers": {
+            "Content-Type": "text/plain"
+        }
+    }
+}

Viewing registered mappings

Every stubbed collaborator exposes list of defined mappings under __/admin/ endpoint.

You can also use the mappingsOutputFolder property to dump the mappings to files. + For annotation based approach it would look like this

@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
+mappingsOutputFolder = "target/outputmappings/")

and for the JUnit approach like this:

@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
+			.repoRoot("http://some_url")
+			.downloadStub("a.b.c", "loanIssuance")
+			.downloadStub("a.b.c:fraudDetectionServer")
+			.withMappingsOutputFolder("target/outputmappings")

Then if you check out the folder target/outputmappings you would see the following structure

.
+├── fraudDetectionServer_13705
+└── loanIssuance_12255

That means that there were two stubs registered. fraudDetectionServer was registered at port 13705 +and loanIssuance at port 12255. If we take a look at one of the files we would see (for WireMock) +mappings available for the given server:

[{
+  "id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
+  "request" : {
+    "url" : "/name",
+    "method" : "GET"
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "fraudDetectionServer"
+  },
+  "uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
+},
+...
+]

Messaging Stubs

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

6.4 Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}

There’s also a StubRunnerExtension available for JUnit 5. StubRunnerRule and StubRunnerExtension work in a very +similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

  • download them
  • cache them locally
  • unzip them to a temporary folder
  • start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port
  • feed the WireMock server with all JSON files that are valid WireMock definitions
  • can also send messages (remember to pass an implementation of MessageVerifier interface)

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. +Check their docs for more information.

Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they allow you to find the started stubs:

package org.springframework.cloud.contract.stubrunner;
+
+import java.net.URL;
+import java.util.Collection;
+import java.util.Map;
+
+import org.springframework.cloud.contract.spec.Contract;
+
+/**
+ * Contract for finding registered stubs.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubFinder extends StubTrigger {
+
+	/**
+	 * For the given groupId and artifactId tries to find the matching URL of the running
+	 * stub.
+	 * @param groupId - might be null. In that case a search only via artifactId takes
+	 * place
+	 * @param artifactId - artifact id of the stub
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;
+
+	/**
+	 * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
+	 * tries to find the matching URL of the running stub. You can also pass only
+	 * {@code artifactId}.
+	 * @param ivyNotation - Ivy representation of the Maven artifact
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String ivyNotation) throws StubNotFoundException;
+
+	/**
+	 * @return all running stubs
+	 */
+	RunningStubs findAllRunningStubs();
+
+	/**
+	 * @return the list of Contracts
+	 */
+	Map<StubConfiguration, Collection<Contract>> getContracts();
+
+}

Example of usage in Spock tests:

@ClassRule
+@Shared
+StubRunnerRule rule = new StubRunnerRule()
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule")
+
+
+def 'should start WireMock servers'() {
+	expect: 'WireMocks are running'
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+		rule.findStubUrl('loanIssuance') != null
+		rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+	and:
+		rule.findAllRunningStubs().isPresent('loanIssuance')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+	and: 'Stubs were registered'
+		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+}
+
+def 'should output mappings to output folder'() {
+	when:
+		def url = rule.findStubUrl('fraudDetectionServer')
+	then:
+		new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
+}

Example of usage in JUnit tests:

	@Test
+	public void should_start_wiremock_servers() throws Exception {
+		// expect: 'WireMocks are running'
+		then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
+		then(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isNotNull();
+		// and:
+		then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs",
+				"fraudDetectionServer")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isTrue();
+		// and: 'Stubs were registered'
+		then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
+				.isEqualTo("loanIssuance");
+		then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
+				.isEqualTo("fraudDetectionServer");
+	}
+
+	private String httpGet(String url) throws Exception {
+		try (InputStream stream = URI.create(url).toURL().openStream()) {
+			return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
+		}
+	}
+
+}

JUnit 5 Extension example:

// Visible for Junit
+@RegisterExtension
+static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
+		.repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule");
+
+@BeforeAll
+@AfterAll
+static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+private static String repoRoot() {
+	try {
+		return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
+				.toURI().toString();
+	}
+	catch (Exception e) {
+		return "";
+	}
+}

Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

[Important]Important

To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the +MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). +If you don’t do this, then whenever you try to send a message an exception will be thrown.

6.4.1 Maven settings

The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

6.4.2 Providing fixed ports

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule.

6.4.3 Fluent API

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.withPort(12345).downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}

You can see that for this example the following test is valid:

then(rule.findStubUrl("loanIssuance"))
+		.isEqualTo(URI.create("http://localhost:12345").toURL());
+then(rule.findStubUrl("fraudDetectionServer"))
+		.isEqualTo(URI.create("http://localhost:12346").toURL());

6.4.4 Stub Runner with Spring

Sets up Spring configuration of the Stub Runner project.

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +and registers in WireMock the selected stubs.

If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use +its methods as presented below:

@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
+		'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
+		'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
+@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+@ActiveProfiles("test")
+class StubRunnerConfigurationSpec extends Specification {
+
+	@Autowired
+	StubFinder stubFinder
+	@Autowired
+	Environment environment
+	@StubRunnerPort("fraudDetectionServer")
+	int fraudDetectionServerPort
+	@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+	int fraudDetectionServerPortWithGroupId
+	@Value('${foo}')
+	Integer foo
+
+	@BeforeClass
+	@AfterClass
+	void setupProps() {
+		System.clearProperty("stubrunner.repository.root")
+		System.clearProperty("stubrunner.classifier")
+	}
+
+	def 'should start WireMock servers'() {
+		expect: 'WireMocks are running'
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+		and:
+			stubFinder.findAllRunningStubs().isPresent('loanIssuance')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+		and: 'Stubs were registered'
+			"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+			"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+		and: 'Fraud Detection is an HTTPS endpoint'
+			stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
+	}
+
+	def 'should throw an exception when stub is not found'() {
+		when:
+			stubFinder.findStubUrl('nonExistingService')
+		then:
+			thrown(StubNotFoundException)
+		when:
+			stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId')
+		then:
+			thrown(StubNotFoundException)
+	}
+
+	def 'should register started servers as environment variables'() {
+		expect:
+			environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
+			stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
+	}
+
+	def 'should be able to interpolate a running stub in the passed test property'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			environment.getProperty("foo", Integer) == fraudPort
+			environment.getProperty("fooWithGroup", Integer) == fraudPort
+			foo == fraudPort
+	}
+
+	@Issue("#573")
+	def 'should be able to retrieve the port of a running stub via an annotation'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			fraudDetectionServerPort == fraudPort
+			fraudDetectionServerPortWithGroupId == fraudPort
+	}
+
+	def 'should dump all mappings to a file'() {
+		when:
+			def url = stubFinder.findStubUrl("fraudDetectionServer")
+		then:
+			new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
+	}
+
+	@Configuration
+	@EnableAutoConfiguration
+	static class Config {}
+
+	@CompileStatic
+	static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+		private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+		@Override
+		WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+			if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+				int httpsPort = SocketUtils.findAvailableTcpPort()
+				log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+				return httpStubConfiguration
+						.httpsPort(httpsPort)
+			}
+			return httpStubConfiguration
+		}
+	}
+}

for the following configuration file:

stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids:
+    - org.springframework.cloud.contract.verifier.stubs:loanIssuance
+    - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
+    - org.springframework.cloud.contract.verifier.stubs:bootService
+  stubs-mode: remote

Instead of using the properties you can also use the properties inside the @AutoConfigureStubRunner. +Below you can find an example of achieving the same result by setting values on the annotation.

@AutoConfigureStubRunner(
+		ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
+				"org.springframework.cloud.contract.verifier.stubs:bootService"],
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		repositoryRoot = "classpath:m2repo/repository/")

Stub Runner Spring registers environment variables in the following manner +for every registered WireMock server. Example for Stub Runner ids + com.example:foo, com.example:bar.

  • stubrunner.runningstubs.foo.port
  • stubrunner.runningstubs.com.example.foo.port
  • stubrunner.runningstubs.bar.port
  • stubrunner.runningstubs.com.example.bar.port

Which you can reference in your code.

You can also use the @StubRunnerPort annotation to inject the port of a running stub. +Value of the annotation can be the groupid:artifactid or just the artifactid. Example for Stub Runner ids +com.example:foo, com.example:bar.

@StubRunnerPort("foo")
+int fooPort;
+@StubRunnerPort("com.example:bar")
+int barPort;

6.5 Stub Runner Spring Cloud

Stub Runner can integrate with Spring Cloud.

For real life examples you can check the

6.5.1 Stubbing Service Discovery

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

  • DiscoveryClient
  • Ribbon ServerList

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate +or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

For example this test will pass

def 'should make service discovery work'() {
+	expect: 'WireMocks are running'
+		"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+	and: 'Stubs can be reached via load service discovery'
+		restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance'
+		restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer'
+}

for the following configuration file

stubrunner:
+  idsToServiceIds:
+    ivyNotation: someValueInsideYourCode
+    fraudDetectionServer: someNameThatShouldMapFraudDetectionServer

Test profiles and service discovery

In your integration tests you typically don’t want to call neither a discovery service (e.g. Eureka) +or Config Server. That’s why you create an additional test configuration in which you want to disable +these features.

Due to certain limitations of spring-cloud-commons to achieve this you have disable these properties +via a static block like presented below (example for Eureka)

    //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
+    static {
+        System.setProperty("eureka.client.enabled", "false");
+        System.setProperty("spring.cloud.config.failFast", "false");
+    }

6.5.2 Additional Configuration

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. +You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false +You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

[Tip]Tip

By default all service discovery will be stubbed. That means that regardless of the fact if you have +an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set + stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be + merged with the stubbed ones.

The default Maven configuration used by Stub Runner can be tweaked either +via the following system properties or environment variables

  • maven.repo.local - path to the custom maven local repository location
  • org.apache.maven.user-settings - path to custom maven user settings location
  • org.apache.maven.global-settings - path to maven global settings location

6.6 Stub Runner Boot Application

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +trigger the messaging labels and to access started WireMock servers.

One of the use-cases is to run some smoke (end to end) tests on a deployed application. +You can check out the Spring Cloud Pipelines +project for more information.

6.6.1 How to use it?

Stub Runner Server

Just add the

compile "org.springframework.cloud:spring-cloud-starter-stub-runner"

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

For the properties check the Stub Runner Spring section.

Stub Runner Server Fat Jar

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
+$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...

Spring Cloud CLI

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project you can start Stub Runner Boot by executing spring cloud stubrunner.

In order to pass the configuration just create a stubrunner.yml file in the current working directory +or a subdirectory called config or in ~/.spring-cloud. The file could look like this +(example for running stubs installed locally)

stubrunner.yml.  +

stubrunner:
+  stubsMode: LOCAL
+  ids:
+    - com.example:beer-api-producer:+:9876

+

and then just call spring cloud stubrunner from your terminal window to start +the Stub Runner server. It will be available at port 8750.

6.6.2 Endpoints

HTTP

  • GET /stubs - returns a list of all running stubs in ivy:integer notation
  • GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

Messaging

For Messaging

  • GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation
  • POST /triggers/{label} - executes a trigger with label
  • POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

6.6.3 Example

@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
+@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
+@ActiveProfiles("test")
+class StubRunnerBootSpec extends Specification {
+
+	@Autowired
+	StubRunning stubRunning
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
+				new TriggerController(stubRunning))
+	}
+
+	def 'should return a list of running stub servers in "full ivy:port" notation'() {
+		when:
+			String response = RestAssuredMockMvc.get('/stubs').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
+	}
+
+	def 'should return a port on which a [#stubId] stub is running'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/${stubId}")
+		then:
+			response.statusCode == 200
+			Integer.valueOf(response.body.asString()) > 0
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:+',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService',
+					   'bootService']
+	}
+
+	def 'should return 404 when missing stub was called'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
+		then:
+			response.statusCode == 404
+	}
+
+	def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
+		when:
+			String response = RestAssuredMockMvc.get('/triggers').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"])
+	}
+
+	def 'should trigger a messaging label'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger('delete_book')
+	}
+
+	def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger(stubId, 'delete_book')
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
+	}
+
+	def 'should throw exception when trigger is missing'() {
+		when:
+			RestAssuredMockMvc.post("/triggers/missing_label")
+		then:
+			Exception e = thrown(Exception)
+			e.message.contains("Exception occurred while trying to return [missing_label] label.")
+			e.message.contains("Available labels are")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
+	}
+
+}

6.6.4 Stub Runner Boot with Service Discovery

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? + Let’s assume that you don’t want to deploy 50 microservice to a test environment in order + to check if your application is working fine. You’ve already executed a suite of tests during the build process + but you would also like to ensure that the packaging of your application is fine. What you can do + is to deploy your application to an environment, start it and run a couple of tests on it to see if + it’s working fine. We can call those tests smoke-tests since their idea is to check only a handful + of testing scenarios.

The problem with this approach is such that if you’re doing microservices most likely you’re + using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the + required stubs and register them in a service discovery tool. Let’s take a look at an example of + such a setup with Eureka. Let’s assume that Eureka was already running.

@SpringBootApplication
+@EnableStubRunnerServer
+@EnableEurekaClient
+@AutoConfigureStubRunner
+public class StubRunnerBootEurekaExample {
+
+	public static void main(String[] args) {
+		SpringApplication.run(StubRunnerBootEurekaExample.class, args);
+	}
+
+}

As you can see we want to start a Stub Runner Boot server @EnableStubRunnerServer, enable Eureka client @EnableEurekaClient +and we want to have the stub runner feature turned on @AutoConfigureStubRunner.

Now let’s assume that we want to start this application so that the stubs get automatically registered. + We can do it by running the app java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar where + ${SYSTEM_PROPS} would contain the following list of properties

* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1)
+* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2)
+* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.
+* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework.
+* cloud.contract.verifier.stubs:bootService (3)
+* -Dstubrunner.idsToServiceIds.fraudDetectionServer=
+* someNameThatShouldMapFraudDetectionServer (4)
+*
+* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default
+* behaviour where the discovery service is stubbed. That's why the stub registration will
+* be picked (3) - we provide a list of stubs to download (4) - we provide a list of

That way your deployed application can send requests to started WireMock servers via the service +discovery. Most likely points 1-3 could be set by default in application.yml cause they are not +likely to change. That way you can provide only the list of stubs to download whenever you start +the Stub Runner Boot.

6.7 Stubs Per Consumer

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

[Tip]Tip

This approach also allows you to immediately know which consumer is using which part of your API. +You can remove part of a response that your API produces and you can see which of your autogenerated tests +fails. If none fails then you can safely delete that part of the response cause nobody is using it.

Let’s look at the following example for contract defined for the producer called producer. +There are 2 consumers: foo-consumer and bar-consumer.

Consumer foo-service

request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       foo: "foo"
+    }
+}

Consumer bar-service

request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       bar: "bar"
+    }
+}

You can’t produce for the same request 2 different responses. That’s why you can properly package the +contracts and then profit from the stubsPerConsumer feature.

On the producer side the consumers can have a folder that contains contracts related only to them. +By setting the stubrunner.stubs-per-consumer flag to true we no longer register all stubs but only those that +correspond to the consumer application’s name. In other words we’ll scan the path of every stub and +if it contains the subfolder with name of the consumer in the path only then will it get registered.

On the foo producer side the contracts would look like this

.
+└── contracts
+    ├── bar-consumer
+    │   ├── bookReturnedForBar.groovy
+    │   └── shouldCallBar.groovy
+    └── foo-consumer
+        ├── bookReturnedForFoo.groovy
+        └── shouldCallFoo.groovy

Being the bar-consumer consumer you can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer +Or set the test as follows:

@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = ["spring.application.name=bar-consumer"])
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerSpec extends Specification {
+...
+}

Then only the stubs registered under a path that contains the bar-consumer in its name (i.e. those from the +src/test/resources/contracts/bar-consumer/some/contracts/…​ folder) will be allowed to be referenced.

Or set the consumer name explicitly

@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		consumerName = "foo-consumer",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification {
+...
+}

Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the +src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

You can check out issue 224 for more +information about the reasons behind this change.

6.8 Common

This section briefly describes common properties, including:

6.8.1 Common Properties for JUnit and Spring

You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values:

Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

 

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

 

Array of Ivy notation stubs to download.

stubrunner.username

 

Optional username to access the tool that stores the JARs with +stubs.

stubrunner.password

 

Optional password to access the tool that stores the JARs with +stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for +each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

 

If you want to use a stub for each consumer and want to +override the consumer name just change this value.

6.8.2 Stub Runner Stubs IDs

You can provide the stubs to download via the stubrunner.ids system property. They +follow this pattern:

groupId:artifactId:version:classifier:port

Note that version, classifier and port are optional.

  • If you do not provide the port, a random one will be picked.
  • If you do not provide the classifier, the default is used. (Note that you can +pass an empty classifier this way: groupId:artifactId:version:).
  • If you do not provide the version, then the + will be passed and the latest one is +downloaded.

port means the port of the WireMock server.

[Important]Important

Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +Aether versioning +ranges here.

6.9 Stub Runner Docker

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +that will start the standalone version of Stub Runner.

If you want to learn more about the basics of Maven, artifact ids, +group ids, classifiers and Artifact Managers, just click here Section 4.5, “Docker Project”.

6.9.1 How to use it

Just execute the docker image. You can pass any of the Section 6.8.1, “Common Properties for JUnit and Spring” +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (.) should be separated via underscore (_). E.g. + the stubrunner.repositoryRoot property should be represented + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

6.9.2 Example of client side usage in a non JVM project

We’d like to use the stubs created in this Section 4.5.4, “Server side (nodejs)” step. +Let’s assume that we want to run the stubs on port 9876. The NodeJS code +is available here:

$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore

Let’s run the Stub Runner Boot application with the stubs.

# Provide the Spring Cloud Contract Docker version
+$ SC_CONTRACT_DOCKER_VERSION="..."
+# The IP at which the app is running and Docker container can reach it
+$ APP_IP="192.168.0.100"
+# Spring Cloud Contract Stub Runner properties
+$ STUBRUNNER_PORT="8083"
+# Stub coordinates 'groupId:artifactId:version:classifier:port'
+$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
+$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
+# Run the docker with Stub Runner Boot
+$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"

What’s happening is that

  • a standalone Stub Runner application got started
  • it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876
  • it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local
  • after a while Stub Runner will be running on port 8083
  • and the stubs will be running at port 9876

On the server side we built a stateful stub. Let’s use curl to assert +that the stubs are setup properly.

# let's execute the first request (no response is returned)
+$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
+# Now time for the second request
+$ curl -X GET http://localhost:9876/api/books
+# You will receive contents of the JSON
[Important]Important

If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro"

7. Stub Runner for Messaging

Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks:

  • Spring Integration
  • Spring Cloud Stream
  • Apache Camel
  • Spring AMQP

It also provides entry points to integrate with any other solution on the market.

[Important]Important

If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. +That way the only remaining framework is Spring AMQP.

7.1 Stub triggering

To trigger a message, use the StubTrigger interface:

package org.springframework.cloud.contract.stubrunner;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Contract for triggering stub messages.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubTrigger {
+
+	/**
+	 * Triggers an event by a given label for a given {@code groupid:artifactid} notation.
+	 * You can use only {@code artifactId} too.
+	 *
+	 * Feature related to messaging.
+	 * @param ivyNotation ivy notation of a stub
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String ivyNotation, String labelName);
+
+	/**
+	 * Triggers an event by a given label.
+	 *
+	 * Feature related to messaging.
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String labelName);
+
+	/**
+	 * Triggers all possible events.
+	 *
+	 * Feature related to messaging.
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger();
+
+	/**
+	 * Feature related to messaging.
+	 * @return a mapping of ivy notation of a dependency to all the labels it has.
+	 */
+	Map<String, Collection<String>> labels();
+
+}

For convenience, the StubFinder interface extends StubTrigger, so you only need one +or the other in your tests.

StubTrigger gives you the following options to trigger a message:

7.1.1 Trigger by Label

stubFinder.trigger('return_book_1')

7.1.2 Trigger by Group and Artifact Ids

stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')

7.1.3 Trigger by Artifact Ids

stubFinder.trigger('streamService', 'return_book_1')

7.1.4 Trigger All Messages

stubFinder.trigger()

7.2 Stub Runner Camel

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +For the provided artifacts it will automatically download the stubs and register the required +routes.

7.2.1 Adding it to the project

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner.

7.2.2 Disabling the functionality

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

7.2.3 Examples

Stubs structure

Let us assume that we have the following Maven repository with a deployed stubs for the +camelService application.

└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── camelService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── camelService-0.0.1-SNAPSHOT.pom
+                            │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml

And the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings

Let’s consider the following contracts (let' number it with 1):

Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

and number 2

Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('jms:input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

Scenario 1 (no input message)

So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

stubFinder.trigger('return_book_1')

Next we’ll want to listen to the output of the message sent to jms:output

Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)

And the received message would pass the following assertions

receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

Scenario 2 (output triggered by input)

Since the route is set for you it’s enough to just send a message to the jms:output destination.

producerTemplate.
+		sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])

Next we’ll want to listen to the output of the message sent to jms:output

Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)

And the received message would pass the following assertions

receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you it’s enough to just send a message to the jms:output destination.

producerTemplate.
+		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])

7.3 Stub Runner Integration

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes.

7.3.1 Adding the Runner to the Project

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

7.3.2 Disabling the functionality

If you need to disable this functionality, set the +stubrunner.integration.enabled=false property.

Assume that you have the following Maven repository with deployed stubs for the +integrationService application:

└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── integrationService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── integrationService-0.0.1-SNAPSHOT.pom
+                            │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml

Further assume the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings

Consider the following contracts (numbered 1):

Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

Now consider 2:

Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

and the following Spring Integration Route:

<?xml version="1.0" encoding="UTF-8"?>
+<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+			 xmlns:beans="http://www.springframework.org/schema/beans"
+			 xmlns="http://www.springframework.org/schema/integration"
+			 xsi:schemaLocation="http://www.springframework.org/schema/beans
+			https://www.springframework.org/schema/beans/spring-beans.xsd
+			http://www.springframework.org/schema/integration
+			http://www.springframework.org/schema/integration/spring-integration.xsd">
+
+
+	<!-- REQUIRED FOR TESTING -->
+	<bridge input-channel="output"
+			output-channel="outputTest"/>
+
+	<channel id="outputTest">
+		<queue/>
+	</channel>
+
+</beans:beans>

These examples lend themselves to three scenarios:

Scenario 1 (no input message)

To trigger a message via the return_book_1 label, use the StubTigger interface, as +follows:

stubFinder.trigger('return_book_1')

To listen to the output of the message sent to output:

Message<?> receivedMessage = messaging.receive('outputTest')

The received message would pass the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 2 (output triggered by input)

Since the route is set for you, you can send a message to the output +destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')

To listen to the output of the message sent to output:

Message<?> receivedMessage = messaging.receive('outputTest')

The received message passes the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you, you can send a message to the input destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

7.4 Stub Runner Stream

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes.

[Warning]Warning

If Stub Runner’s integration with Stream the messageFrom or sentTo Strings +are resolved first as a destination of a channel and no such destination exists, the +destination is resolved as a channel name.

[Important]Important

If you want to use Spring Cloud Stream remember, to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support.

Maven.  +

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

+

7.4.1 Adding the Runner to the Project

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

7.4.2 Disabling the functionality

If you need to disable this functionality, set the stubrunner.stream.enabled=false +property.

Assume that you have the following Maven repository with a deployed stubs for the +streamService application:

└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── streamService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── streamService-0.0.1-SNAPSHOT.pom
+                            │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml

Further assume the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings

Consider the following contracts (numbered 1):

Contract.make {
+	label 'return_book_1'
+	input { triggeredBy('bookReturnedTriggered()') }
+	outputMessage {
+		sentTo('returnBook')
+		body('''{ "bookName" : "foo" }''')
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}

Now consider 2:

Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('bookStorage')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders { header('sample', 'header') }
+	}
+	outputMessage {
+		sentTo('returnBook')
+		body([
+				bookName: 'foo'
+		])
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}

Now consider the following Spring configuration:

stubrunner.repositoryRoot: classpath:m2repo/repository/
+stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
+stubrunner.stubs-mode: remote
+spring:
+  cloud:
+    stream:
+      bindings:
+        output:
+          destination: returnBook
+        input:
+          destination: bookStorage
+
+server:
+  port: 0
+
+debug: true

These examples lend themselves to three scenarios:

Scenario 1 (no input message)

To trigger a message via the return_book_1 label, use the StubTrigger interface as +follows:

stubFinder.trigger('return_book_1')

To listen to the output of the message sent to a channel whose destination is +returnBook:

Message<?> receivedMessage = messaging.receive('returnBook')

The received message passes the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 2 (output triggered by input)

Since the route is set for you, you can send a message to the bookStorage +destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')

To listen to the output of the message sent to returnBook:

Message<?> receivedMessage = messaging.receive('returnBook')

The received message passes the following assertions:

receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you, you can send a message to the output +destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

7.5 Stub Runner Spring AMQP

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes.

The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a RabbitTemplate on the application context and +uses it as a spring boot test named @SpyBean. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application.

On the message consumer side, the stub runner considers all @RabbitListener annotated +endpoints and all SimpleMessageListenerContainer objects on the application context.

As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners.

If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey +messaging header.

7.5.1 Adding the Runner to the Project

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property stubrunner.amqp.enabled=true. Remember to annotate your test class +with @AutoConfigureStubRunner.

[Important]Important

If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the stubrunner.stream.enabled=false and +stubrunner.integration.enabled=false properties.

Assume that you have the following Maven repository with a deployed stubs for the +spring-cloud-contract-amqp-test application.

└── .m2
+    └── repository
+        └── com
+            └── example
+                └── spring-cloud-contract-amqp-test
+                    ├── 0.4.0-SNAPSHOT
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
+                    │   └── maven-metadata-local.xml
+                    └── maven-metadata-local.xml

Further assume that the stubs contain the following structure:

├── META-INF
+│   └── MANIFEST.MF
+└── contracts
+    └── shouldProduceValidPersonData.groovy

Consider the following contract:

Contract.make {
+	// Human readable description
+	description 'Should produce valid person data'
+	// Label by means of which the output message can be triggered
+	label 'contract-test.person.created.event'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('createPerson()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo 'contract-test.exchange'
+		headers {
+			header('contentType': 'application/json')
+			header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
+		}
+		// the body of the output message
+		body([
+				id  : $(consumer(9), producer(regex("[0-9]+"))),
+				name: "me"
+		])
+	}
+}

Now consider the following Spring configuration:

stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs
+  stubs-mode: remote
+  amqp:
+    enabled: true
+server:
+  port: 0

Triggering the message

To trigger a message using the contract above, use the StubTrigger interface as +follows:

stubTrigger.trigger("contract-test.person.created.event")

The message has a destination of contract-test.exchange, so the Spring AMQP stub runner +integration looks for bindings related to this exchange.

@Bean
+public Binding binding() {
+	return BindingBuilder.bind(new Queue("test.queue"))
+			.to(new DirectExchange("contract-test.exchange")).with("#");
+}

The binding definition binds the queue test.queue. As a result, the following listener +definition is matched and invoked with the contract message.

@Bean
+public SimpleMessageListenerContainer simpleMessageListenerContainer(
+		ConnectionFactory connectionFactory,
+		MessageListenerAdapter listenerAdapter) {
+	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
+	container.setConnectionFactory(connectionFactory);
+	container.setQueueNames("test.queue");
+	container.setMessageListener(listenerAdapter);
+
+	return container;
+}

Also, the following annotated listener matches and is invoked:

@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"), exchange = @Exchange(value = "contract-test.exchange", ignoreDeclarationExceptions = "true")))
+public void handlePerson(Person person) {
+	this.person = person;
+}
[Note]Note

The message is directly handed over to the onMessage method of the +MessageListener associated with the matching SimpleMessageListenerContainer.

Spring AMQP Test Configuration

In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock ConnectionFactory.

To disable the mocked ConnectionFactory, set the following property: +stubrunner.amqp.mockConnection=false

stubrunner:
+  amqp:
+    mockConnection: false

8. Contract DSL

Spring Cloud Contract supports out of the box 2 types of DSL. One written in +Groovy and one written in YAML.

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself.

[Important]Important

Remember that, inside the Groovy contract file, you have to provide the fully +qualified name to the Contract class and make static imports, such as +org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to +the Contract class: import org.springframework.cloud.spec.Contract and then call +Contract.make { …​ }.

[Tip]Tip

Spring Cloud Contract supports defining multiple contracts in a single file.

The following is a complete example of a Groovy contract definition:

The following is a complete example of a YAML contract definition:

description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
[Tip]Tip

You can compile contracts to stubs mapping using standalone maven command: +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert

8.1 Limitations

[Warning]Warning

Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature.

[Warning]Warning

The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to true: +spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. +You can also provide the assertJsonSize property in the plugin configuration.

[Warning]Warning

Because JSON structure can have any form, it can be impossible to parse it +properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That +is why you should use the Groovy Map notation.

8.2 Common Top-Level elements

The following sections describe the most common top-level elements:

8.2.1 Description

You can add a description to your contract. The description is arbitrary text. The +following code shows an example:

Groovy DSL.  +

			org.springframework.cloud.contract.spec.Contract.make {
+				description('''
+given:
+	An input
+when:
+	Sth happens
+then:
+	Output
+''')
+			}

+

YAML.  +

description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)

+

8.2.2 Name

You can provide a name for your contract. Assume that you provided the following name: +should register a user. If you do so, the name of the autogenerated test is +validate_should_register_a_user. Also, the name of the stub in a WireMock stub is +should_register_a_user.json.

[Important]Important

You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	name("some_special_name")
+}

+

YAML.  +

name: some name

+

8.2.3 Ignoring Contracts

If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the ignored property on the contract itself:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	ignored()
+}

+

YAML.  +

ignored: true

+

8.2.4 Passing Values from Files

Starting with version 1.2.0, you can pass values from files. Assume that you have the +following resources in our project.

└── src
+    └── test
+        └── resources
+            └── contracts
+                ├── readFromFile.groovy
+                ├── request.json
+                └── response.json

Further assume that your contract is as follows:

Groovy DSL.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		method('PUT')
+		headers {
+			contentType(applicationJson())
+		}
+		body(file("request.json"))
+		url("/1")
+	}
+	response {
+		status OK()
+		body(file("response.json"))
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}

+

YAML.  +

request:
+  method: GET
+  url: /foo
+  bodyFromFile: request.json
+response:
+  status: 200
+  bodyFromFile: response.json

+

Further assume that the JSON files is as follows:

request.json

{
+  "status": "REQUEST"
+}

response.json

{
+  "status": "RESPONSE"
+}

When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. The name of the file needs to be a file with location +relative to the folder in which the contract lays.

If you need to pass the contents of a file in a binary form +it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

Groovy DSL.  +

import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		url("/1")
+		method(PUT())
+		headers {
+			contentType(applicationOctetStream())
+		}
+		body(fileAsBytes("request.pdf"))
+	}
+	response {
+		status 200
+		body(fileAsBytes("response.pdf"))
+		headers {
+			contentType(applicationOctetStream())
+		}
+	}
+}

+

YAML.  +

request:
+  url: /1
+  method: PUT
+  headers:
+    Content-Type: application/octet-stream
+  bodyFromFileAsBytes: request.pdf
+response:
+  status: 200
+  bodyFromFileAsBytes: response.pdf
+  headers:
+    Content-Type: application/octet-stream

+

[Important]Important

You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.

8.2.5 HTTP Top-Level Elements

The following methods can be called in the top-level closure of a contract definition. +request and response are mandatory. priority is optional.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	// Definition of HTTP request part of the contract
+	// (this can be a valid request or invalid depending
+	// on type of contract being specified).
+	request {
+		method GET()
+		url "/foo"
+		//...
+	}
+
+	// Definition of HTTP response part of the contract
+	// (a service implementing this contract should respond
+	// with following response after receiving request
+	// specified in "request" part above).
+	response {
+		status 200
+		//...
+	}
+
+	// Contract priority, which can be used for overriding
+	// contracts (1 is highest). Priority is optional.
+	priority 1
+}

+

YAML.  +

priority: 8
+request:
+...
+response:
+...

+

[Important]Important

If you want to make your contract have a higher value of priority +you need to pass a lower number to the priority tag / method. E.g. priority with +value 5 has higher priority than priority with value 10.

8.3 Request

The HTTP protocol requires only method and url to be specified in a request. The +same information is mandatory in request definition of the Contract.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		// HTTP request method (GET/POST/PUT/DELETE).
+		method 'GET'
+
+		// Path component of request URL is specified as follows.
+		urlPath('/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

method: PUT
+url: /foo

+

It is possible to specify an absolute rather than relative url, but using urlPath is +the recommended way, as doing so makes the tests host-independent.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+
+		// Specifying `url` and `urlPath` in one contract is illegal.
+		url('http://localhost:8888/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+  method: PUT
+  urlPath: /foo

+

request may contain query parameters.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+
+		urlPath('/users') {
+
+			// Each parameter is specified in form
+			// `'paramName' : paramValue` where parameter value
+			// may be a simple literal or one of matcher functions,
+			// all of which are used in this example.
+			queryParameters {
+
+				// If a simple literal is used as value
+				// default matcher function is used (equalTo)
+				parameter 'limit': 100
+
+				// `equalTo` function simply compares passed value
+				// using identity operator (==).
+				parameter 'filter': equalTo("email")
+
+				// `containing` function matches strings
+				// that contains passed substring.
+				parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
+
+				// `matching` function tests parameter
+				// against passed regular expression.
+				parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
+
+				// `notMatching` functions tests if parameter
+				// does not match passed regular expression.
+				parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
+			}
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+  queryParameters:
+    a: b
+    b: c
+  headers:
+    foo: bar
+    fooReq: baz
+  cookies:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  fixedDelayMilliseconds: 1000
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+    cookies:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        predefined:

+

request may contain additional request headers, as shown in the following example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each header is added in form `'Header-Name' : 'Header-Value'`.
+		// there are also some helper methods
+		headers {
+			header 'key': 'value'
+			contentType(applicationJson())
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+headers:
+  foo: bar
+  fooReq: baz

+

request may contain additional request cookies, as shown in the following example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
+		// there are also some helper methods
+		cookies {
+			cookie 'key': 'value'
+			cookie('another_key', 'another_value')
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+cookies:
+  foo: bar
+  fooReq: baz

+

request may contain a request body:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Currently only JSON format of request body is supported.
+		// Format will be determined from a header or body's content.
+		body '''{ "login" : "john", "name": "John The Contract" }'''
+	}
+
+	response {
+		//...
+		status 200
+	}
+}

+

YAML.  +

request:
+...
+body:
+  foo: bar

+

request may contain multipart elements. To include multipart elements, use the +multipart method/section, as shown in the following examples

Groovy DSL.  +

+

YAML.  +

request:
+  method: PUT
+  url: /multipart
+  headers:
+    Content-Type: multipart/form-data;boundary=AaB03x
+  multipart:
+    params:
+      # key (parameter name), value (parameter value) pair
+      formParameter: '"formParameterValue"'
+      someBooleanParameter: true
+    named:
+      - paramName: file
+        fileName: filename.csv
+        fileContent: file content
+  matchers:
+    multipart:
+      params:
+        - key: formParameter
+          regex: ".+"
+        - key: someBooleanParameter
+          predefined: any_boolean
+      named:
+        - paramName: file
+          fileName:
+            predefined: non_empty
+          fileContent:
+            predefined: non_empty
+response:
+  status: 200

+

In the preceding example, we define parameters in either of two ways:

Groovy DSL

  • Directly, by using the map notation, where the value can be a dynamic property (such as +formParameter: $(consumer(…​), producer(…​))).
  • By using the named(…​) method that lets you set a named parameter. A named parameter +can set a name and content. You can call it either via a method with two arguments, +such as named("fileName", "fileContent"), or via a map notation, such as +named(name: "fileName", content: "fileContent").

YAML

  • The multipart parameters are set via multipart.params section
  • The named parameters (the fileName and fileContent for a given parameter name) +can be set via the multipart.named section. That section contains +the paramName (name of the parameter), fileName (name of the file), +fileContent (content of the file) fields
  • The dynamic bits can be set via the matchers.multipart section

    • for parameters use the params section that can accept +regex or a predefined regular expression
    • for named params use the named section where first you +define the parameter name via paramName and then you can pass the +parametrization of either fileName or fileContent via +regex or a predefined regular expression

From this contract, the generated test is as follows:

// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
+   .param("formParameter", "\"formParameterValue\"")
+   .param("someBooleanParameter", "true")
+   .multiPart("file", "filename.csv", "file content".getBytes());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .put("/multipart");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);

The WireMock stub is as follows:

			'''
+{
+  "request" : {
+	"url" : "/multipart",
+	"method" : "PUT",
+	"headers" : {
+	  "Content-Type" : {
+		"matches" : "multipart/form-data;boundary=AaB03x.*"
+	  }
+	},
+	"bodyPatterns" : [ {
+		"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
+  		}, {
+    			"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
+  		}, {
+	  "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
+	} ]
+  },
+  "response" : {
+	"status" : 200,
+	"transformers" : [ "response-template", "foo-transformer" ]
+  }
+}
+	'''

8.4 Response

The response must contain an HTTP status code and may contain other information. The +following code shows an example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+	}
+	response {
+		// Status code sent by the server
+		// in response to request specified above.
+		status OK()
+	}
+}

+

YAML.  +

response:
+...
+status: 200

+

Besides status, the response may contain headers, cookies and a body, both of which are +specified the same way as in the request (see the previous paragraph).

[Tip]Tip

Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus +methods to provide a meaningful status instead of a digit. E.g. you can call +OK() for a status 200 or BAD_REQUEST() for 400.

8.5 Dynamic properties

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub.

For Groovy DSL you can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in a separate section called +bodyMatchers.

[Note]Note

Before 2.0.0 these were set using testMatchers and stubMatchers, +check out the migration guide for more information.

For YAML you can only use the matchers section.

8.5.1 Dynamic properties inside the body

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can set the properties inside the body either with the value method or, if you use +the Groovy map notation, with $(). The following example shows how to set dynamic +properties with the value method:

value(consumer(...), producer(...))
+value(c(...), p(...))
+value(stub(...), test(...))
+value(client(...), server(...))

The following example shows how to set dynamic properties with $():

$(consumer(...), producer(...))
+$(c(...), p(...))
+$(stub(...), test(...))
+$(client(...), server(...))

Both approaches work equally well. stub and client methods are aliases over the consumer +method. Subsequent sections take a closer look at what you can do with those values.

8.5.2 Regular expressions

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests.

The following example shows how to use regular expressions to write a request:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method('GET')
+		url $(consumer(~/\/[0-9]{2}/), producer('/12'))
+	}
+	response {
+		status OK()
+		body(
+				id: $(anyNumber()),
+				surname: $(
+						consumer('Kowalsky'),
+						producer(regex('[a-zA-Z]+'))
+				),
+				name: 'Jan',
+				created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
+				correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
+						producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'))
+				)
+		)
+		headers {
+			header 'Content-Type': 'text/plain'
+		}
+	}
+}

You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url value(consumer(regex('/foo/[0-9]{5}')))
+		body([
+				requestElement: $(consumer(regex('[0-9]{5}')))
+		])
+		headers {
+			header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
+		}
+	}
+	response {
+		status OK()
+		body([
+				responseElement: $(producer(regex('[0-9]{7}')))
+		])
+		headers {
+			contentType("application/vnd.fraud.v1+json")
+		}
+	}
+}

In the preceding example, the opposite side of the communication has the respective data +generated for request and response.

Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example:

protected static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/)
+protected static final Pattern ALPHA_NUMERIC = Pattern.compile('[a-zA-Z0-9]+')
+protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile(/[\p{L}]*/)
+protected static final Pattern NUMBER = Pattern.compile('-?(\\d*\\.\\d+|\\d+)')
+protected static final Pattern INTEGER = Pattern.compile('-?(\\d+)')
+protected static final Pattern POSITIVE_INT = Pattern.compile('([1-9]\\d*)')
+protected static final Pattern DOUBLE = Pattern.compile('-?(\\d*\\.\\d+)')
+protected static final Pattern HEX = Pattern.compile('[a-fA-F0-9]+')
+protected static final Pattern IP_ADDRESS = Pattern.
+		compile('([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])')
+protected static final Pattern HOSTNAME_PATTERN = Pattern.
+		compile('((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?')
+protected static final Pattern EMAIL = Pattern.
+		compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}')
+protected static final Pattern URL = UrlHelper.URL
+protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL
+protected static final Pattern UUID = Pattern.
+		compile('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}')
+protected static final Pattern ANY_DATE = Pattern.
+		compile('(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])')
+protected static final Pattern ANY_DATE_TIME = Pattern.
+		compile('([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])')
+protected static final Pattern ANY_TIME = Pattern.
+		compile('(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])')
+protected static final Pattern NON_EMPTY = Pattern.compile(/[\S\s]+/)
+protected static final Pattern NON_BLANK = Pattern.compile(/^\s*\S[\S\s]*/)
+protected static final Pattern ISO8601_WITH_OFFSET = Pattern.
+		compile(/([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.\d{3})?(Z|[+-][01]\d:[0-5]\d)/)
+
+protected static Pattern anyOf(String... values) {
+	return Pattern.compile(values.collect({ "^$it\$" }).join("|"))
+}
+
+RegexProperty onlyAlphaUnicode() {
+	return new RegexProperty(ONLY_ALPHA_UNICODE).asString()
+}
+
+RegexProperty alphaNumeric() {
+	return new RegexProperty(ALPHA_NUMERIC).asString()
+}
+
+RegexProperty number() {
+	return new RegexProperty(NUMBER).asDouble()
+}
+
+RegexProperty positiveInt() {
+	return new RegexProperty(POSITIVE_INT).asInteger()
+}
+
+RegexProperty anyBoolean() {
+	return new RegexProperty(TRUE_OR_FALSE).asBooleanType()
+}
+
+RegexProperty anInteger() {
+	return new RegexProperty(INTEGER).asInteger()
+}
+
+RegexProperty aDouble() {
+	return new RegexProperty(DOUBLE).asDouble()
+}
+
+RegexProperty ipAddress() {
+	return new RegexProperty(IP_ADDRESS).asString()
+}
+
+RegexProperty hostname() {
+	return new RegexProperty(HOSTNAME_PATTERN).asString()
+}
+
+RegexProperty email() {
+	return new RegexProperty(EMAIL).asString()
+}
+
+RegexProperty url() {
+	return new RegexProperty(URL).asString()
+}
+
+RegexProperty httpsUrl() {
+	return new RegexProperty(HTTPS_URL).asString()
+}
+
+RegexProperty uuid() {
+	return new RegexProperty(UUID).asString()
+}
+
+RegexProperty isoDate() {
+	return new RegexProperty(ANY_DATE).asString()
+}
+
+RegexProperty isoDateTime() {
+	return new RegexProperty(ANY_DATE_TIME).asString()
+}
+
+RegexProperty isoTime() {
+	return new RegexProperty(ANY_TIME).asString()
+}
+
+RegexProperty iso8601WithOffset() {
+	return new RegexProperty(ISO8601_WITH_OFFSET).asString()
+}
+
+RegexProperty nonEmpty() {
+	return new RegexProperty(NON_EMPTY).asString()
+}
+
+RegexProperty nonBlank() {
+	return new RegexProperty(NON_BLANK).asString()
+}

In your contract, you can use it as shown in the following example:

Contract dslWithOptionalsInString = Contract.make {
+	priority 1
+	request {
+		method POST()
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123"))),
+				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
+		)
+	}
+}

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. +All of those methods start with any prefix:

T anyAlphaUnicode()
+
+T anyAlphaNumeric()
+
+T anyNumber()
+
+T anyInteger()
+
+T anyPositiveInt()
+
+T anyDouble()
+
+T anyHex()
+
+T aBoolean()
+
+T anyIpAddress()
+
+T anyHostname()
+
+T anyEmail()
+
+T anyUrl()
+
+T anyHttpsUrl()
+
+T anyUuid()
+
+T anyDate()
+
+T anyDateTime()
+
+T anyTime()
+
+T anyIso8601WithOffset()
+
+T anyNonBlankString()
+
+T anyNonEmptyString()
+
+T anyOf(String... values)

and this is an example of how you can reference those methods:

Contract contractDsl = Contract.make {
+	label 'trigger_event'
+	input {
+		triggeredBy('toString()')
+	}
+	outputMessage {
+		sentTo 'topic.rateablequote'
+		body([
+				alpha            : $(anyAlphaUnicode()),
+				number           : $(anyNumber()),
+				anInteger        : $(anyInteger()),
+				positiveInt      : $(anyPositiveInt()),
+				aDouble          : $(anyDouble()),
+				aBoolean         : $(aBoolean()),
+				ip               : $(anyIpAddress()),
+				hostname         : $(anyHostname()),
+				email            : $(anyEmail()),
+				url              : $(anyUrl()),
+				httpsUrl         : $(anyHttpsUrl()),
+				uuid             : $(anyUuid()),
+				date             : $(anyDate()),
+				dateTime         : $(anyDateTime()),
+				time             : $(anyTime()),
+				iso8601WithOffset: $(anyIso8601WithOffset()),
+				nonBlankString   : $(anyNonBlankString()),
+				nonEmptyString   : $(anyNonEmptyString()),
+				anyOf            : $(anyOf('foo', 'bar'))
+		])
+	}
+}

8.5.3 Passing Optional Parameters

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following:

  • STUB side of the Request
  • TEST side of the Response

The following example shows how to provide optional parameters:

org.springframework.cloud.contract.spec.Contract.make {
+	priority 1
+	request {
+		method 'POST'
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			header 'Content-Type': 'application/json'
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123")))
+		)
+	}
+}

By wrapping a part of the body with the optional() method, you create a regular +expression that must be present 0 or more times.

If you use Spock for, the following test would be generated from the previous example:

					"""
+ given:
+  def request = given()
+    .header("Content-Type", "application/json")
+    .body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
+
+ when:
+  def response = given().spec(request)
+    .post("/users/password")
+
+ then:
+  response.statusCode == 404
+  response.header('Content-Type')  == 'application/json'
+ and:
+  DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+  assertThatJson(parsedJson).field("['code']").matches("(123123)?")
+"""

The following stub would also be generated:

					'''
+{
+  "request" : {
+	"url" : "/users/password",
+	"method" : "POST",
+	"bodyPatterns" : [ {
+	  "matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]"
+	}, {
+	  "matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
+	} ],
+	"headers" : {
+	  "Content-Type" : {
+		"equalTo" : "application/json"
+	  }
+	}
+  },
+  "response" : {
+	"status" : 404,
+	"body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}",
+	"headers" : {
+	  "Content-Type" : "application/json"
+	}
+  },
+  "priority" : 1
+}
+'''

8.5.4 Executing Custom Methods on the Server Side

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url $(consumer(regex('^/api/[0-9]{2}$')), producer('/api/12'))
+		headers {
+			header 'Content-Type': 'application/json'
+		}
+		body '''\
+			[{
+				"text": "Gonna see you at Warsaw"
+			}]
+		'''
+	}
+	response {
+		body(
+				path: $(consumer('/api/12'), producer(regex('^/api/[0-9]{2}$'))),
+				correlationId: $(consumer('1223456'), producer(execute('isProperCorrelationId($it)')))
+		)
+		status OK()
+	}
+}

The following code shows the base class portion of the test case:

abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
[Important]Important

You cannot use both a String and execute to perform concatenation. For +example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to +improper results. Instead, call header('Authorization', execute('authToken()')) and +ensure that the authToken() method returns everything you need.

The type of the object read from the JSON can be one of the following, depending on the +JSON path:

  • String: If you point to a String value in the JSON.
  • JSONArray: If you point to a List in the JSON.
  • Map: If you point to a Map in the JSON.
  • Number: If you point to Integer, Double etc. in the JSON.
  • Boolean: If you point to a Boolean in the JSON.

In the request part of the contract, you can specify that the body should be taken from +a method.

[Important]Important

You must provide both the consumer and the producer side. The execute part +is applied for the whole body - not for parts of it.

The following example shows how to read an object from JSON:

Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		url '/something'
+		body(
+				$(c('foo'), p(execute('hashCode()')))
+		)
+	}
+	response {
+		status OK()
+	}
+}

The preceding example results in calling the hashCode() method in the request body. +It should resemble the following code:

// given:
+ MockMvcRequestSpecification request = given()
+   .body(hashCode());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/something");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);

8.5.5 Referencing the Request from the Response

The best situation is to provide fixed values, but sometimes you need to reference a +request in your response.

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options:

  • fromRequest().url(): Returns the request URL and query parameters.
  • fromRequest().query(String key): Returns the first query parameter with a given name.
  • fromRequest().query(String key, int index): Returns the nth query parameter with a +given name.
  • fromRequest().path(): Returns the full path.
  • fromRequest().path(int index): Returns the nth path element.
  • fromRequest().header(String key): Returns the first header with a given name.
  • fromRequest().header(String key, int index): Returns the nth header with a given name.
  • fromRequest().body(): Returns the full request body.
  • fromRequest().body(String jsonPath): Returns the element from the request that +matches the JSON Path.

If you’re using the YAML contract definition you have to use the +Handlebars {{{ }}} notation with custom, Spring Cloud Contract + functions to achieve this.

  • {{{ request.url }}}: Returns the request URL and query parameters.
  • {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. +E.g. for key foo, first entry {{{ request.query.foo.[0] }}}
  • {{{ request.path }}}: Returns the full path.
  • {{{ request.path.[index] }}}: Returns the nth path element. E.g. +for first entry `{{{ request.path.[0] }}}
  • {{{ request.headers.key }}}: Returns the first header with a given name.
  • {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.
  • {{{ request.body }}}: Returns the full request body.
  • {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that +matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

Consider the following contract:

Groovy DSL.  +

+

YAML.  +

request:
+  method: GET
+  url: /api/v1/xxxx
+  queryParameters:
+    foo:
+      - bar
+      - bar2
+  headers:
+    Authorization:
+      - secret
+      - secret2
+  body:
+    foo: bar
+    baz: 5
+response:
+  status: 200
+  headers:
+    Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
+  body:
+    url: "{{{ request.url }}}"
+    path: "{{{ request.path }}}"
+    pathIndex: "{{{ request.path.1 }}}"
+    param: "{{{ request.query.foo }}}"
+    paramIndex: "{{{ request.query.foo.1 }}}"
+    authorization: "{{{ request.headers.Authorization.0 }}}"
+    authorization2: "{{{ request.headers.Authorization.1 }}"
+    fullBody: "{{{ request.body }}}"
+    responseFoo: "{{{ jsonpath this '$.foo' }}}"
+    responseBaz: "{{{ jsonpath this '$.baz' }}}"
+    responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"

+

Running a JUnit test generation leads to a test that resembles the following example:

// given:
+ MockMvcRequestSpecification request = given()
+   .header("Authorization", "secret")
+   .header("Authorization", "secret2")
+   .body("{\"foo\":\"bar\",\"baz\":5}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .queryParam("foo","bar")
+   .queryParam("foo","bar2")
+   .get("/api/v1/xxxx");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
+ assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
+ assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
+ assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
+ assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
+ assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
+ assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
+ assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
+ assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");

As you can see, elements from the request have been properly referenced in the response.

The generated WireMock stub should resemble the following example:

{
+  "request" : {
+    "urlPath" : "/api/v1/xxxx",
+    "method" : "POST",
+    "headers" : {
+      "Authorization" : {
+        "equalTo" : "secret2"
+      }
+    },
+    "queryParameters" : {
+      "foo" : {
+        "equalTo" : "bar2"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
+    "headers" : {
+      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}

Sending a request such as the one presented in the request part of the contract results +in sending the following response body:

{
+  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
+  "path" : "/api/v1/xxxx",
+  "pathIndex" : "v1",
+  "param" : "bar",
+  "paramIndex" : "bar2",
+  "authorization" : "secret",
+  "authorization2" : "secret2",
+  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
+  "responseFoo" : "bar",
+  "responseBaz" : 5,
+  "responseBaz2" : "Bla bla bar bla bla"
+}
[Important]Important

This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s +response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into +proper values. Additionally, it registers two helper functions:

  • escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.
  • jsonpath: For a given parameter, find an object in the request body.

8.5.6 Registering Your Own WireMock Extension

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. +Since we use the spring.factories extension approach, you can create an entry in +META-INF/spring.factories file similar to the following:

org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
+org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
+org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter

The following is an example of a custom extension:

TestWireMockExtensions.groovy.  +

/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+
+package org.springframework.cloud.contract.verifier.dsl.wiremock
+
+import com.github.tomakehurst.wiremock.extension.Extension
+
+/**
+ * Extension that registers the default transformer and the custom one
+ */
+class TestWireMockExtensions implements WireMockExtensions {
+	@Override
+	List<Extension> extensions() {
+		return [
+				new DefaultResponseTransformer(),
+				new CustomExtension()
+		]
+	}
+}
+
+class CustomExtension implements Extension {
+
+	@Override
+	String getName() {
+		return "foo-transformer"
+	}
+}

+

[Important]Important

Remember to override the applyGlobally() method and set it to false if you +want the transformation to be applied only for a mapping that explicitly requires it.

8.5.7 Dynamic Properties in the Matchers Sections

If you work with Pact, the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract.

You can use the bodyMatchers section for two reasons:

  • Define the dynamic values that should end up in a stub. +You can set it in the request or inputMessage part of your contract.
  • Verify the result of your test. +This section is present in the response or outputMessage side of the +contract.

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities:

Groovy DSL

  • For the stubs(in tests on the Consumer’s side):

    • byEquality(): The value taken from the consumer’s request via the provided JSON Path must be +equal to the value provided in the contract.
    • byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must +match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)
    • byDate(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Date value.
    • byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO DateTime value.
    • byTime(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Time value.
  • For the verification(in generated tests on the Producer’s side):

    • byEquality(): The value taken from the producer’s response via the provided JSON Path must be +equal to the provided value in the contract.
    • byRegex(…​): The value taken from the producer’s response via the provided JSON Path must +match the regex.
    • byDate(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Date value.
    • byTimestamp(): The value taken from the producer’s response via the provided JSON Path must +match the regex for an ISO DateTime value.
    • byTime(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Time value.
    • byType(): The value taken from the producer’s response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the byCommand(…​) testMatcher.
    • byCommand(…​): The value taken from the producer’s response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +byCommand('foo($it)') results in calling a foo method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path:

      • String: If you point to a String value.
      • JSONArray: If you point to a List.
      • Map: If you point to a Map.
      • Number: If you point to Integer, Double, or other kind of number.
      • Boolean: If you point to a Boolean.
    • byNull(): The value taken from the response via the provided JSON Path must be null

YAML. Please read the Groovy section for detailed explanation of +what the types mean

For YAML the structure of a matcher looks like this

- path: $.foo
+  type: by_regex
+  value: bar
+  regexType: as_string

Or if you want to use one of the predefined regular expressions +[only_alpha_unicode, number, any_boolean, ip_address, hostname, +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

- path: $.foo
+  type: by_regex
+  predefined: only_alpha_unicode

Below you can find the allowed list of `type`s.

  • For stubMatchers:

    • by_equality
    • by_regex
    • by_date
    • by_timestamp
    • by_time
    • by_type

      • there are 2 additional fields accepted: minOccurrence and maxOccurrence.
  • For testMatchers:

    • by_equality
    • by_regex
    • by_date
    • by_timestamp
    • by_time
    • by_type

      • there are 2 additional fields accepted: minOccurrence and maxOccurrence.
    • by_command
    • by_null

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

  • as_integer
  • as_double
  • as_float,
  • as_long
  • as_short
  • as_boolean
  • as_string

Consider the following example:

Groovy DSL.  +

Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		urlPath '/get'
+		body([
+				duck                : 123,
+				alpha               : 'abc',
+				number              : 123,
+				aBoolean            : true,
+				date                : '2017-01-01',
+				dateTime            : '2017-01-01T01:23:45',
+				time                : '01:02:34',
+				valueWithoutAMatcher: 'foo',
+				valueWithTypeMatch  : 'string',
+				key                 : [
+						'complex.key': 'foo'
+				]
+		])
+		bodyMatchers {
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			jsonPath('$.duck', byEquality())
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+		}
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status OK()
+		body([
+				duck                 : 123,
+				alpha                : 'abc',
+				number               : 123,
+				positiveInteger      : 1234567890,
+				negativeInteger      : -1234567890,
+				positiveDecimalNumber: 123.4567890,
+				negativeDecimalNumber: -123.4567890,
+				aBoolean             : true,
+				date                 : '2017-01-01',
+				dateTime             : '2017-01-01T01:23:45',
+				time                 : "01:02:34",
+				valueWithoutAMatcher : 'foo',
+				valueWithTypeMatch   : 'string',
+				valueWithMin         : [
+						1, 2, 3
+				],
+				valueWithMax         : [
+						1, 2, 3
+				],
+				valueWithMinMax      : [
+						1, 2, 3
+				],
+				valueWithMinEmpty    : [],
+				valueWithMaxEmpty    : [],
+				key                  : [
+						'complex.key': 'foo'
+				],
+				nullValue            : null
+		])
+		bodyMatchers {
+			// asserts the jsonpath value against manual regex
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			// asserts the jsonpath value against the provided value
+			jsonPath('$.duck', byEquality())
+			// asserts the jsonpath value against some default regex
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			// asserts vs inbuilt time related regex
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			// asserts that the resulting type is the same as in response body
+			jsonPath('$.valueWithTypeMatch', byType())
+			jsonPath('$.valueWithMin', byType {
+				// results in verification of size of array (min 1)
+				minOccurrence(1)
+			})
+			jsonPath('$.valueWithMax', byType {
+				// results in verification of size of array (max 3)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinMax', byType {
+				// results in verification of size of array (min 1 & max 3)
+				minOccurrence(1)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinEmpty', byType {
+				// results in verification of size of array (min 0)
+				minOccurrence(0)
+			})
+			jsonPath('$.valueWithMaxEmpty', byType {
+				// results in verification of size of array (max 0)
+				maxOccurrence(0)
+			})
+			// will execute a method `assertThatValueIsANumber`
+			jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+			jsonPath('$.nullValue', byNull())
+		}
+		headers {
+			contentType(applicationJson())
+			header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
+		}
+	}
+}

+

YAML.  +

request:
+  method: GET
+  urlPath: /get/1
+  headers:
+    Content-Type: application/json
+  cookies:
+    foo: 2
+    bar: 3
+  queryParameters:
+    limit: 10
+    offset: 20
+    filter: 'email'
+    sort: name
+    search: 55
+    age: 99
+    name: John.Doe
+    email: 'bob@email.com'
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    key:
+      "complex.key": 'foo'
+    nullValue: null
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+  matchers:
+    url:
+      regex: /get/[0-9]
+      # predefined:
+      # execute a method
+      #command: 'equals($it)'
+    queryParameters:
+      - key: limit
+        type: equal_to
+        value: 20
+      - key: offset
+        type: containing
+        value: 20
+      - key: sort
+        type: equal_to
+        value: name
+      - key: search
+        type: not_matching
+        value: '^[0-9]{2}$'
+      - key: age
+        type: not_matching
+        value: '^\\w*$'
+      - key: name
+        type: matching
+        value: 'John.*'
+      - key: hello
+        type: absent
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: "$.['key'].['complex.key']"
+        type: by_equality
+      - path: $.nullvalue
+        type: by_null
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+response:
+  status: 200
+  cookies:
+    foo: 1
+    bar: 2
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+    key:
+      'complex.key': 'foo'
+    nulValue: null
+  matchers:
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: $.valueWithTypeMatch
+        type: by_type
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+      - path: $.valueWithMinEmpty
+        type: by_type
+        minOccurrence: 0
+      - path: $.valueWithMaxEmpty
+        type: by_type
+        maxOccurrence: 0
+      - path: $.duck
+        type: by_command
+        value: assertThatValueIsANumber($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+  headers:
+    Content-Type: application/json

+

In the preceding example, you can see the dynamic portions of the contract in the +matchers sections. For the request part, you can see that, for all fields but +valueWithoutAMatcher, the values of the regular expressions that the stub should +contain are explicitly set. For the valueWithoutAMatcher, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check.

For the response side in the bodyMatchers section, we define the dynamic parts in a +similar manner. The only difference is that the byType matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called):

  • For $.valueWithTypeMatch, the engine checks whether the type is the same.
  • For $.valueWithMin, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence.
  • For $.valueWithMax, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence.
  • For $.valueWithMinMax, the engine checks the type and asserts whether the size is +between the min and maximum occurrence.

The resulting test would resemble the following example (note that an and section +separates the autogenerated assertions and the assertion from matchers):

// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "application/json")
+   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/get");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Content-Type")).matches("application/json.*");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
+// and:
+ assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
+ assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
+ assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
+ assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
+ assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
+ assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
+ assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+ assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
+ assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
+ assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
+ assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
+ assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
+ assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
+ assertThatValueIsANumber(parsedJson.read("$.duck"));
+ assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
[Important]Important

Notice that, for the byCommand method, the example calls the +assertThatValueIsANumber. This method must be defined in the test base class or be +statically imported to your tests. Notice that the byCommand call was converted to +assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took +the method name and passed the proper JSON path as a parameter to it.

The resulting WireMock stub is in the following example:

					'''
+{
+  "request" : {
+    "urlPath" : "/get",
+    "method" : "POST",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck == 123)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha == 'abc')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}",
+    "headers" : {
+      "Content-Type" : "application/json"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+'''
[Important]Important

If you use a matcher, then the part of the request and response that the +matcher addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for all the elements of the +collection.

Consider the following example:

Contract.make {
+    request {
+        method 'GET'
+        url("/foo")
+    }
+    response {
+        status OK()
+        body(events: [[
+                                 operation          : 'EXPORT',
+                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
+                                 status             : 'OK'
+                         ], [
+                                 operation          : 'INPUT_PROCESSING',
+                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
+                                 status             : 'OK'
+                         ]
+                ]
+        )
+        bodyMatchers {
+            jsonPath('$.events[0].operation', byRegex('.+'))
+            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
+            jsonPath('$.events[0].status', byRegex('.+'))
+        }
+    }
+}

The preceding code leads to creating the following test (the code block shows only the assertion section):

and:
+	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
+	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
+and:
+	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
+	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
+	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")

As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole $.events +collection and assert it with the byCommand(…​) method.

8.6 JAX-RS Support

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define protected WebTarget webTarget and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of application/octet-stream gets used.

In order to use JAX-RS mode, use the following settings:

testMode == 'JAXRSCLIENT'

The following example shows a generated test API:

					'''
+ // when:
+  Response response = webTarget
+    .path("/users")
+    .queryParam("limit", "10")
+    .queryParam("offset", "20")
+    .queryParam("filter", "email")
+    .queryParam("sort", "name")
+    .queryParam("search", "55")
+    .queryParam("age", "99")
+    .queryParam("name", "Denis.Stepanov")
+    .queryParam("email", "bob@email.com")
+    .request()
+    .method("GET");
+
+  String responseAsString = response.readEntity(String.class);
+
+ // then:
+  assertThat(response.getStatus()).isEqualTo(200);
+ // and:
+  DocumentContext parsedJson = JsonPath.parse(responseAsString);
+  assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
+'''

8.7 Async Support

If you’re using asynchronous communication on the server side (your controllers are +returning Callable, DeferredResult, and so on), then, inside your contract, you must +provide an async() method in the response section. The following code shows an example:

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status OK()
+        body 'Passed'
+        async()
+    }
+}

+

YAML.  +

response:
+    async: true

+

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

Groovy DSL.  +

org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status 200
+        body 'Passed'
+        fixedDelayMilliseconds 1000
+    }
+}

+

YAML.  +

response:
+    fixedDelayMilliseconds: 1000

+

8.8 Working with Context Paths

Spring Cloud Contract supports context paths.

[Important]Important

The only change needed to fully support context paths is the switch on the +PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer +side remains untouched. In order for the generated test to pass, you must use EXPLICIT +mode.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>

+

Gradle.  +

contracts {
+		testMode = 'EXPLICIT'
+}

+

That way, you generate a test that DOES NOT use MockMvc. It means that you generate +real requests and you need to setup your generated test’s base class to work on a real +socket.

Consider the following contract:

org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+		url '/my-context-path/url'
+	}
+	response {
+		status OK()
+	}
+}

The following example shows how to set up a base class and Rest Assured:

import io.restassured.RestAssured;
+import org.junit.Before;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class ContextPathTestingBaseClass {
+
+	@LocalServerPort int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost";
+		RestAssured.port = this.port;
+	}
+}

If you do it this way:

  • All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, /my-context-path/url).
  • Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call /my-context-path/url).

8.9 Working with WebFlux

Spring Cloud Contract offers two ways of working with WebFlux.

8.9.1 WebFlux with WebTestClient

One of them is via the WebTestClient mode.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>WEBTESTCLIENT</testMode>
+    </configuration>
+</plugin>

+

Gradle.  +

contracts {
+		testMode = 'WEBTESTCLIENT'
+}

+

The following example shows how to set up a WebTestClient base class and RestAssured +for WebFlux:

import io.restassured.module.webtestclient.RestAssuredWebTestClient;
+import org.junit.Before;
+
+public abstract class BeerRestBase {
+
+	@Before
+	public void setup() {
+		RestAssuredWebTestClient.standaloneSetup(
+		new ProducerController(personToCheck -> personToCheck.age >= 20));
+	}
+}
+}

8.9.2 WebFlux with Explicit mode

Another way is with the EXPLICIT mode in your generated tests +to work with WebFlux.

Maven.  +

<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>

+

Gradle.  +

contracts {
+		testMode = 'EXPLICIT'
+}

+

The following example shows how to set up a base class and Rest Assured for Web Flux:

@RunWith(SpringRunner.class)
+@SpringBootTest(classes = BeerRestBase.Config.class,
+		webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+		properties = "server.port=0")
+public abstract class BeerRestBase {
+
+    // your tests go here
+
+    // in this config class you define all controllers and mocked services
+@Configuration
+@EnableAutoConfiguration
+static class Config {
+
+	@Bean
+	PersonCheckingService personCheckingService()  {
+		return personToCheck -> personToCheck.age >= 20;
+	}
+
+	@Bean
+	ProducerController producerController() {
+		return new ProducerController(personCheckingService());
+	}
+}
+
+}

8.10 XML Support for REST

For REST contracts, we also support XML request and response body. +The XML body has to be passed within the body element +as a String or GString. Also body matchers can be provided for +both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath +method should be used, with the desired xPath provided as the first argument +and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

Here is an example of a Groovy DSL contract with XML response body:

					Contract.make {
+						request {
+							method GET()
+							urlPath '/get'
+							headers {
+								contentType(applicationXml())
+							}
+						}
+						response {
+							status(OK())
+							headers {
+								contentType(applicationXml())
+							}
+							body """
+<test>
+<duck type='xtype'>123</duck>
+<alpha>abc</alpha>
+<list>
+<elem>abc</elem>
+<elem>def</elem>
+<elem>ghi</elem>
+</list>
+<number>123</number>
+<aBoolean>true</aBoolean>
+<date>2017-01-01</date>
+<dateTime>2017-01-01T01:23:45</dateTime>
+<time>01:02:34</time>
+<valueWithoutAMatcher>foo</valueWithoutAMatcher>
+<key><complex>foo</complex></key>
+</test>"""
+							bodyMatchers {
+								xPath('/test/duck/text()', byRegex("[0-9]{3}"))
+								xPath('/test/duck/text()', byCommand('test($it)'))
+								xPath('/test/duck/xxx', byNull())
+								xPath('/test/duck/text()', byEquality())
+								xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
+								xPath('/test/alpha/text()', byEquality())
+								xPath('/test/number/text()', byRegex(number()))
+								xPath('/test/date/text()', byDate())
+								xPath('/test/dateTime/text()', byTimestamp())
+								xPath('/test/time/text()', byTime())
+								xPath('/test/*/complex/text()', byEquality())
+								xPath('/test/duck/@type', byEquality())
+							}
+						}
+					}

And below is an example of a YAML contract with XML request and response bodies:

include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml

Here is an example of an automatically generated test for XML response body:

@Test
+public void validate_xmlMatches() throws Exception {
+	// given:
+	MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/xml");
+
+	// when:
+	ResponseOptions response = given().spec(request).get("/get");
+
+	// then:
+	assertThat(response.statusCode()).isEqualTo(200);
+	// and:
+	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
+					.newDocumentBuilder();
+	Document parsedXml = documentBuilder.parse(new InputSource(
+				new StringReader(response.getBody().asString())));
+	// and:
+	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
+	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
+	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
+	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
+	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
+	}

8.11 Messaging Top-Level Elements

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

8.11.1 Output Triggered by a Method

The output message can be triggered by calling a method (such as a Scheduler when a was +started and a message was sent), as shown in the following example:

Groovy DSL.  +

def dsl = Contract.make {
+	// Human readable description
+	description 'Some description'
+	// Label by means of which the output message can be triggered
+	label 'some_label'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('bookReturnedTriggered()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo('output')
+		// the body of the output message
+		body('''{ "bookName" : "foo" }''')
+		// the headers of the output message
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

+

YAML.  +

# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+input:
+  # the contract will be triggered by a method
+  triggeredBy: bookReturnedTriggered()
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo

+

In the previous example case, the output message is sent to output if a method called +bookReturnedTriggered is executed. On the message publisher’s side, we generate a +test that calls that method to trigger the message. On the consumer side, you can use +the some_label to trigger the message.

8.11.2 Output Triggered by a Message

The output message can be triggered by receiving a message, as shown in the following +example:

Groovy DSL.  +

def dsl = Contract.make {
+	description 'Some Description'
+	label 'some_label'
+	// input is a message
+	input {
+		// the message was received from this destination
+		messageFrom('input')
+		// has the following body
+		messageBody([
+				bookName: 'foo'
+		])
+		// and the following headers
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}

+

YAML.  +

# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+# input is a message
+input:
+  messageFrom: input
+  # has the following body
+  messageBody:
+    bookName: 'foo'
+  # and the following headers
+  messageHeaders:
+    sample: 'header'
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo

+

In the preceding example, the output message is sent to output if a proper message is +received on the input destination. On the message publisher’s side, the engine +generates a test that sends the input message to the defined destination. On the +consumer side, you can either send a message to the input destination or use a label +(some_label in the example) to trigger the message.

8.11.3 Consumer/Producer

[Important]Important

This section is valid only for Groovy DSL.

In HTTP, you have a notion of client/stub and `server/test notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the consumer and producer methods, as presented in the following example +(note that you can use either $ or value methods to provide consumer and producer +parts):

					Contract.make {
+						label 'some_label'
+						input {
+							messageFrom value(consumer('jms:output'), producer('jms:input'))
+							messageBody([
+									bookName: 'foo'
+							])
+							messageHeaders {
+								header('sample', 'header')
+							}
+						}
+						outputMessage {
+							sentTo $(consumer('jms:input'), producer('jms:output'))
+							body([
+									bookName: 'foo'
+							])
+						}
+					}

8.11.4 Common

In the input or outputMessage section you can call assertThat with the name +of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test.

8.12 Multiple Contracts in One File

You can define multiple contracts in one file. Such a contract might resemble the +following example:

Groovy DSL.  +

import org.springframework.cloud.contract.spec.Contract
+
+[
+	Contract.make {
+		name("should post a user")
+		request {
+			method 'POST'
+			url('/users/1')
+		}
+		response {
+			status OK()
+		}
+	},
+	Contract.make {
+		request {
+			method 'POST'
+			url('/users/2')
+		}
+		response {
+			status OK()
+		}
+	}
+]

+

YAML.  +

---
+name: should post a user
+request:
+  method: POST
+  url: /users/1
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/2
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/3
+response:
+  status: 200

+

In the preceding example, one contract has the name field and the other does not. This +leads to generation of two tests that look more or less like this:

package org.springframework.cloud.contract.verifier.tests.com.hello;
+
+import com.example.TestBase;
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
+import com.jayway.restassured.response.ResponseOptions;
+import org.junit.Test;
+
+import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class V1Test extends TestBase {
+
+	@Test
+	public void validate_should_post_a_user() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/1");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+	@Test
+	public void validate_withList_1() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/2");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+}

Notice that, for the contract that has the name field, the generated test method is named +validate_should_post_a_user. For the one that does not have the name, it is called +validate_withList_1. It corresponds to the name of the file WithList.groovy and the +index of the contract in the list.

The generated stubs is shown in the following example:

should post a user.json
+1_WithList.json

As you can see, the first file got the name parameter from the contract. The second +got the name of the contract file (WithList.groovy) prefixed with the index (in this +case, the contract had an index of 1 in the list of contracts in the file).

[Tip]Tip

As you can see, it is much better if you name your contracts because doing so makes +your tests far more meaningful.

8.13 Generating Spring REST Docs snippets from the contracts

When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven’t already.

Maven.  +

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+<dependency>
+	<groupId>org.springframework.restdocs</groupId>
+	<artifactId>spring-restdocs-mockmvc</artifactId>
+	<optional>true</optional>
+</dependency>

+

Gradle.  +

testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'

+

Next you need to make some changes to your base class like the following example.

package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
+public abstract class FraudBaseWithWebAppSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Autowired
+	private WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName()))
+				.build());
+	}
+
+	protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+public abstract class FraudBaseWithStandaloneSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
+				.standaloneSetup(new FraudDetectionController())
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName())));
+	}
+
+}
[Tip]Tip

You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs.

9. Customization

[Important]Important

This section is valid only for Groovy DSL

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section.

9.1 Extending the DSL

You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of:

  • Creating a JAR with reusable classes.
  • Referencing of these classes in the DSLs.

You can find the full example +here.

9.1.1 Common JAR

The following examples show three classes that can be reused in the DSLs.

PatternUtils contains functions used by both the consumer and the producer.

package com.example;
+
+import java.util.regex.Pattern;
+
+/**
+ * If you want to use {@link Pattern} directly in your tests
+ * then you can create a class resembling this one. It can
+ * contain all the {@link Pattern} you want to use in the DSL.
+ *
+ * <pre>
+ * {@code
+ * request {
+ *     body(
+ *         [ age: $(c(PatternUtils.oldEnough()))]
+ *     )
+ * }
+ * </pre>
+ *
+ * Notice that we're using both {@code $()} for dynamic values
+ * and {@code c()} for the consumer side.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class PatternUtils {
+
+	public static String tooYoung() {
+		//remove::start[]
+		return "[0-1][0-9]";
+		//remove::end[return]
+	}
+
+	public static Pattern oldEnough() {
+		//remove::start[]
+		return Pattern.compile("[2-9][0-9]");
+		//remove::end[return]
+	}
+
+	/**
+	 * Makes little sense but it's just an example ;)
+	 */
+	public static Pattern ok() {
+		//remove::start[]
+		return Pattern.compile("OK");
+		//remove::end[return]
+	}
+}
+//end::impl[]

ConsumerUtils contains functions used by the consumer.

package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the consumer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you can have a regular expression.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you have to have a concrete value.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ConsumerUtils {
+	/**
+	 * Consumer side property. By using the {@link ClientDslProperty}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * request {
+	 *     body(
+	 *         [ age: $(ConsumerUtils.oldEnough())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 *
+	 * @author Marcin Grzejszczak
+	 */
+	public static ClientDslProperty oldEnough() {
+		//remove::start[]
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ClientDslProperty(PatternUtils.oldEnough(), 40);
+		//remove::end[return]
+	}
+
+}
+//end::impl[]

ProducerUtils contains functions used by the producer.

package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the producer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you have to have a concrete value.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you can have a regular expression.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ProducerUtils {
+
+	/**
+	 * Producer side property. By using the {@link ProducerUtils}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * response {
+	 *     body(
+	 *         [ status: $(ProducerUtils.ok())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 */
+	public static ServerDslProperty ok() {
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ServerDslProperty( PatternUtils.ok(), "OK");
+	}
+}
+//end::impl[]

9.1.2 Adding the Dependency to the Project

In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

9.1.3 Test the Dependency in the Project’s Dependencies

First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency:

Maven.  +

<dependency>
+	<groupId>com.example</groupId>
+	<artifactId>beer-common</artifactId>
+	<version>${project.version}</version>
+	<scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")

+

9.1.4 Test a Dependency in the Plugin’s Dependencies

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example:

Maven.  +

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example</packageWithBaseClasses>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*intoxication.*</contractPackageRegex>
+				<baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>com.example</groupId>
+			<artifactId>beer-common</artifactId>
+			<version>${project.version}</version>
+			<scope>compile</scope>
+		</dependency>
+	</dependencies>
+</plugin>

+

Gradle.  +

classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"

+

9.1.5 Referencing classes in DSLs

You can now reference your classes in your DSL, as shown in the following example:

package contracts.beer.rest
+
+import com.example.ConsumerUtils
+import com.example.ProducerUtils
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	description("""
+Represents a successful scenario of getting a beer
+
+```
+given:
+	client is old enough
+when:
+	he applies for a beer
+then:
+	we'll grant him the beer
+```
+
+""")
+	request {
+		method 'POST'
+		url '/check'
+		body(
+				age: $(ConsumerUtils.oldEnough())
+		)
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status 200
+		body("""
+			{
+				"status": "${value(ProducerUtils.ok())}"
+			}
+			""")
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
[Important]Important

You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones.

10. Using the Pluggable Architecture

You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations).

10.1 Custom Contract Converter

The ContractConverter interface lets you register your own implementation of a contract +structure converter. The following code listing shows the ContractConverter interface:

package org.springframework.cloud.contract.spec
+
+/**
+ * Converter to be used to convert FROM {@link File} TO {@link Contract}
+ * and from {@link Contract} to {@code T}
+ *
+ * @param <T >     - type to which we want to convert the contract
+ *
+ * @author Marcin Grzejszczak
+ * @since 1.1.0
+ */
+interface ContractConverter<T> extends ContractStorer<T> {
+
+	/**
+	 * Should this file be accepted by the converter. Can use the file extension
+	 * to check if the conversion is possible.
+	 *
+	 * @param file - file to be considered for conversion
+	 * @return - {@code true} if the given implementation can convert the file
+	 */
+	boolean isAccepted(File file)
+
+	/**
+	 * Converts the given {@link File} to its {@link Contract} representation
+	 *
+	 * @param file - file to convert
+	 * @return - {@link Contract} representation of the file
+	 */
+	Collection<Contract> convertFrom(File file)
+
+	/**
+	 * Converts the given {@link Contract} to a {@link T} representation
+	 *
+	 * @param contract - the parsed contract
+	 * @return - {@link T} the type to which we do the conversion
+	 */
+	T convertTo(Collection<Contract> contract)
+}

Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions.

[Important]Important

Once you create your implementation, you must create a +/META-INF/spring.factories file in which you provide the fully qualified name of your +implementation.

The following example shows a typical spring.factories file:

org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.verifier.converter.YamlContractConverter

10.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of +contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used.

In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

  • to define the destination to which a message gets sent, you have to +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

10.1.2 Pact Contract

Consider following example of a Pact contract, which is a file under the +src/test/resources/contracts folder.

{
+  "provider": {
+    "name": "Provider"
+  },
+  "consumer": {
+    "name": "Consumer"
+  },
+  "interactions": [
+    {
+      "description": "",
+      "request": {
+        "method": "PUT",
+        "path": "/fraudcheck",
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "clientId": "1234567890",
+          "loanAmount": 99999
+        },
+        "generators": {
+          "body": {
+            "$.clientId": {
+              "type": "Regex",
+              "regex": "[0-9]{10}"
+            }
+          }
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.clientId": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "[0-9]{10}"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      },
+      "response": {
+        "status": 200,
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json;charset=UTF-8"
+        },
+        "body": {
+          "fraudCheckStatus": "FRAUD",
+          "rejectionReason": "Amount too high"
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.fraudCheckStatus": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "FRAUD"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      }
+    }
+  ],
+  "metadata": {
+    "pact-specification": {
+      "version": "3.0.0"
+    },
+    "pact-jvm": {
+      "version": "3.5.13"
+    }
+  }
+}

The remainder of this section about using Pact refers to the preceding file.

10.1.3 Pact for Producers

On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use.

Maven.  +

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-contract-pact</artifactId>
+			<version>${spring-cloud-contract.version}</version>
+		</dependency>
+	</dependencies>
+</plugin>

+

Gradle.  +

classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"

+

When you execute the build of your application, a test will be generated. The generated +test might be as follows:

@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+	// given:
+		MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/vnd.fraud.v1+json")
+				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
+
+	// when:
+		ResponseOptions response = given().spec(request)
+				.put("/fraudcheck");
+
+	// then:
+		assertThat(response.statusCode()).isEqualTo(200);
+		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
+	// and:
+		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
+	// and:
+		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
+}

The corresponding generated stub might be as follows:

{
+  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "request" : {
+    "url" : "/fraudcheck",
+    "method" : "PUT",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
+    "headers" : {
+      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
+    },
+    "transformers" : [ "response-template" ]
+  },
+}

10.1.4 Pact for Consumers

On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use.

Maven.  +

<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-pact</artifactId>
+	<scope>test</scope>
+</dependency>

+

Gradle.  +

testCompile "org.springframework.cloud:spring-cloud-contract-pact"

+

10.2 Using the Custom Test Generator

If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation.

The SingleTestGenerator interface lets you register your own implementation. The +following code listing shows the SingleTestGenerator interface:

package org.springframework.cloud.contract.verifier.builder
+
+
+import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties
+import org.springframework.cloud.contract.verifier.file.ContractMetadata
+
+/**
+ * Builds a single test.
+ *
+ * @since 1.1.0
+ */
+trait SingleTestGenerator {
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from
+	 * the contract metadata should be placed.
+	 *
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param className - the name of the generated test class
+	 * @param classPackage - the name of the package in which the test class should be stored
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
+	 */
+	@Deprecated
+	abstract String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles, String className, String classPackage, String includedDirectoryRelativePath)
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from
+	 * the contract metadata should be placed.
+	 *
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param generatedClassData - information about the generated class
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 */
+	String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles, String includedDirectoryRelativePath, GeneratedClassData generatedClassData) {
+		String className = generatedClassData.className
+		String classPackage = generatedClassData.classPackage
+		String path = includedDirectoryRelativePath
+		return buildClass(properties, listOfFiles, className, classPackage, path)
+	}
+
+	/**
+	 * Extension that should be appended to the generated test class. E.g. {@code .java} or {@code .php}
+	 *
+	 * @param properties - properties passed to the plugin
+	 */
+	abstract String fileExtension(ContractVerifierConfigProperties properties)
+
+	static class GeneratedClassData {
+		public final String className
+		public final String classPackage
+		public final java.nio.file.Path testClassPath
+
+		GeneratedClassData(String className, String classPackage,
+				java.nio.file.Path testClassPath) {
+			this.className = className
+			this.classPackage = classPackage
+			this.testClassPath = testClassPath
+		}
+	}
+}

Again, you must provide a spring.factories file, such as the one shown in the following +example:

org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
+com.example.MyGenerator

10.3 Using the Custom Stub Generator

If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the StubGenerator interface. The following code listing shows the +StubGenerator interface:

package org.springframework.cloud.contract.verifier.converter
+
+import groovy.transform.CompileStatic
+
+import org.springframework.cloud.contract.spec.Contract
+import org.springframework.cloud.contract.verifier.file.ContractMetadata
+
+/**
+ * Converts contracts into their stub representation.
+ *
+ * @since 1.1.0
+ */
+@CompileStatic
+interface StubGenerator {
+
+	/**
+	 * @return {@code true} if the converter can handle the file to convert it into a stub.
+	 */
+	boolean canHandleFileName(String fileName)
+
+	/**
+	 * @return the collection of converted contracts into stubs. One contract can
+	 * result in multiple stubs.
+	 */
+	Map<Contract, String> convertContents(String rootName, ContractMetadata content)
+
+	/**
+	 * @return the name of the converted stub file. If you have multiple contracts
+	 * in a single file then a prefix will be added to the generated file. If you
+	 * provide the {@link Contract#name} field then that field will override the
+	 * generated file name.
+	 *
+	 * Example: name of file with 2 contracts is {@code foo.groovy}, it will be
+	 * converted by the implementation to {@code foo.json}. The recursive file
+	 * converter will create two files {@code 0_foo.json} and {@code 1_foo.json}
+	 */
+	String generateOutputFileNameForInput(String inputFileName)
+}

Again, you must provide a spring.factories file, such as the one shown in the following +example:

# Stub converters
+org.springframework.cloud.contract.verifier.converter.StubGenerator=\
+org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter

The default implementation is the WireMock stub generation.

[Tip]Tip

You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files.

10.4 Using the Custom Stub Runner

If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider.

Assume that you use Moco to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file.

In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example:

package org.springframework.cloud.contract.stubrunner.provider.moco
+
+import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
+import com.github.dreamhead.moco.runner.JsonRunner
+import com.github.dreamhead.moco.runner.RunnerSetting
+import groovy.util.logging.Commons
+
+import org.springframework.cloud.contract.stubrunner.HttpServerStub
+import org.springframework.util.SocketUtils
+
+@Commons
+class MocoHttpServerStub implements HttpServerStub {
+
+	private boolean started
+	private JsonRunner runner
+	private int port
+
+	@Override
+	int port() {
+		if (!isRunning()) {
+			return -1
+		}
+		return port
+	}
+
+	@Override
+	boolean isRunning() {
+		return started
+	}
+
+	@Override
+	HttpServerStub start() {
+		return start(SocketUtils.findAvailableTcpPort())
+	}
+
+	@Override
+	HttpServerStub start(int port) {
+		this.port = port
+		return this
+	}
+
+	@Override
+	HttpServerStub stop() {
+		if (!isRunning()) {
+			return this
+		}
+		this.runner.stop()
+		return this
+	}
+
+	@Override
+	HttpServerStub registerMappings(Collection<File> stubFiles) {
+		List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
+			.collect {
+			log.info("Trying to parse [${it.name}]")
+			try {
+				return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()).
+					build()
+			}
+			catch (Exception e) {
+				log.warn("Exception occurred while trying to parse file [${it.name}]", e)
+				return null
+			}
+		}.findAll { it }
+		this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
+			HttpArgs.httpArgs().withPort(this.port).build())
+		this.runner.run()
+		this.started = true
+		return this
+	}
+
+	@Override
+	String registeredMappings() {
+		return ""
+	}
+
+	@Override
+	boolean isAccepted(File file) {
+		return file.name.endsWith(".json")
+	}
+}

Then, you can register it in your spring.factories file, as shown in the following +example:

org.springframework.cloud.contract.stubrunner.HttpServerStub=\
+org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub

Now you can run stubs with Moco.

[Important]Important

If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used.

10.5 Using the Custom Stub Downloader

You can customize the way your stubs are downloaded by creating an implementation of the +StubDownloaderBuilder interface, as shown in the following example:

package com.example;
+
+class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
+
+	@Override
+	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
+		return new StubDownloader() {
+			@Override
+			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
+					StubConfiguration config) {
+				File unpackedStubs = retrieveStubs();
+				return new AbstractMap.SimpleEntry<>(
+						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
+								config.getClassifier()), unpackedStubs);
+			}
+
+			File retrieveStubs() {
+			    // here goes your custom logic to provide a folder where all the stubs reside
+			}
+}

Then you can register it in your spring.factories file, as shown in the following +example:

# Example of a custom Stub Downloader Provider
+org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
+com.example.CustomStubDownloaderBuilder

Now you can pick a folder with the source of your stubs.

[Important]Important

If you do not provide any implementation, then the default is used (scan classpath). +If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or +, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used +If you provide more than one, then the first one on the list is used.

10.6 Using the SCM Stub Downloader

Whenever the repositoryRoot starts with a SCM protocol +(currently we support only git://), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs.

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

Table 10.1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

* stubrunner.properties.git.branch (system prop)

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

* stubrunner.properties.git.username (system prop)

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

 

Git clone username

* git.password (plugin prop)

* stubrunner.properties.git.password (system prop)

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

 

Git clone password

* git.no-of-attempts (plugin prop)

* stubrunner.properties.git.no-of-attempts (system prop)

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

* stubrunner.properties.git.wait-between-attempts (system prop)

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin


10.7 Using the Pact Stub Downloader

Whenever the repositoryRoot starts with a Pact protocol +(starts with pact://), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after pact:// will be parsed as the Pact Broker URL.

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

Table 10.2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

* stubrunner.properties.pactbroker.host (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

* stubrunner.properties.pactbroker.port (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

* stubrunner.properties.pactbroker.protocol (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

* stubrunner.properties.pactbroker.tags (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

* stubrunner.properties.pactbroker.auth.scheme (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

* stubrunner.properties.pactbroker.auth.username (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

* stubrunner.properties.pactbroker.auth.password (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used


11. Spring Cloud Contract WireMock

The Spring Cloud Contract WireMock modules let you use WireMock in a +Spring Boot application. Check out the +samples +for more details.

If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with spring-boot-starter-web), you can add +spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public class WiremockForDocsTests {
+
+	// A service that calls out over HTTP
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:"
+				+ this.environment.getProperty("wiremock.server.port"));
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}

To start the stub server on a different port use (for example), +@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

11.1 Registering Stubs Automatically

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +system or classpath (by default, from file:src/test/resources/mappings). You can +customize the locations using the stubs attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, */.json is +appended. The following code shows an example:

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureWireMock(stubs="classpath:/stubs")
+public class WiremockImportApplicationTests {
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
[Note]Note

Actually, WireMock always loads mappings from src/test/resources/mappings as +well as the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document.

If you’re using Spring Cloud Contract’s default stub jars, then your +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")

11.2 Using Files to Specify the Stub Bodies

WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a bodyFileName instead of a +(literal) body. The files are resolved relative to a root directory (by default, +src/test/resources/__files). To customize this location you can set the files +attribute in the @AutoConfigureWireMock annotation to the location of the parent +directory (in other words, __files is a subdirectory). You can use Spring resource +notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body.

[Note]Note

When you configure the files root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of files has no +effect on the stubs loaded explicitly from the stubs attribute.

11.3 Alternative: Using JUnit Rules

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +the server. To do so, use the WireMockSpring convenience class to obtain an Options +instance, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class WiremockForDocsClassRuleTests {
+
+	// Start WireMock on some dynamic port
+	// for some reason `dynamicPort()` is not working properly
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().dynamicPort());
+
+	// A service that calls out over HTTP to wiremock's port
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:" + wiremock.port());
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}

The @ClassRule means that the server shuts down after all the methods in this class +have been run.

11.4 Relaxed SSL Validation for Rest Template

WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that’s not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course).

To make this work with minimum fuss, you need to be using the Spring Boot +RestTemplateBuilder in your app, as shown in the following example:

@Bean
+public RestTemplate restTemplate(RestTemplateBuilder builder) {
+	return builder.build();
+}

You need RestTemplateBuilder because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the @AutoConfigureWireMock +annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the +@AutoConfigureHttpClient annotation as well, as shown in the following example:

@RunWith(SpringRunner.class)
+@SpringBootTest("app.baseUrl=https://localhost:6443")
+@AutoConfigureHttpClient
+public class WiremockHttpsServerApplicationTests {
+
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().httpsPort(6443));
+...
+}

If you are using spring-boot-starter-test, you have the Apache HTTP client on the +classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL +errors. If you use the default java.net client, you do not need the annotation (but it +won’t do any harm). There is no support currently for other clients, but it may be added +in future releases.

To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled +property to false.

11.5 WireMock and Spring MVC Mocks

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring MockRestServiceServer. The following code shows an example:

@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+public class WiremockForDocsMockServerApplicationTests {
+
+	@Autowired
+	private RestTemplate restTemplate;
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		// will read stubs classpath
+		MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
+				.baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
+				.build();
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World");
+		server.verify();
+	}
+
+}

The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to +visit https://example.org/, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +WireMock website.

Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one).

11.6 Customization of WireMock configuration

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +in order to customize the WireMock configuration (e.g. add custom transformers). +Example:

		@Bean
+		WireMockConfigurationCustomizer optionsCustomizer() {
+			return new WireMockConfigurationCustomizer() {
+				@Override
+				public void customize(WireMockConfiguration options) {
+// perform your customization here
+				}
+			};
+		}

11.7 Generating Stubs using REST Docs

Spring REST Docs can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc +or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example using MockMvc:

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(get("/resource"))
+				.andExpect(content().string("Hello World"))
+				.andDo(document("resource"));
+	}
+}

This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. The same example with WebTestClient (used +for testing Spring WebFlux applications) would look like this:

@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureWebTestClient
+public class ApplicationTests {
+
+	@Autowired
+	private WebTestClient client;
+
+	@Test
+	public void contextLoads() throws Exception {
+		client.get().uri("/resource").exchange()
+				.expectBody(String.class).isEqualTo("Hello World")
+ 				.consumeWith(document("resource"));
+	}
+}

Without any additional configuration, these tests create a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects:

  • Creating a stub that matches only in the way you specify.
  • Asserting that the request in the test case also matches the same conditions.

The main entry point for this feature is WireMockRestDocs.verify(), which can be used +as a substitute for the document() convenience method, as shown in the following +example:

import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(post("/resource")
+                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+				.andExpect(status().isOk())
+				.andDo(verify().jsonPath("$.id")
+                        .stub("resource"));
+	}
+}

This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to .jsonPath() to add additional +matchers. If JSON Path is unfamiliar, The JayWay +documentation can help you get up to speed. The WebTestClient version of this test +has a similar verify() static helper that you insert in the same place.

Instead of the jsonPath and contentType convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example:

@Test
+public void contextLoads() throws Exception {
+	mockMvc.perform(post("/resource")
+               .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+			.andExpect(status().isOk())
+			.andDo(verify()
+					.wiremock(WireMock.post(
+						urlPathEquals("/resource"))
+						.withRequestBody(matchingJsonPath("$.id"))
+                       .stub("post-resource"));
+}

The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example:

post-resource.json.  +

{
+  "request" : {
+    "url" : "/resource",
+    "method" : "POST",
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.id"
+    }]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "Hello World",
+    "headers" : {
+      "X-Application-Context" : "application:-1",
+      "Content-Type" : "text/plain"
+    }
+  }
+}

+

[Note]Note

You can use either the wiremock() method or the jsonPath() and contentType() +methods to create request matchers, but you can’t use both approaches.

On the consumer side, you can make the resource.json generated earlier in this section +available on the classpath (by +<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this +document.

11.8 Generating Contracts by Using REST Docs

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs.

Why would you want to use this feature? Some people in the community asked questions +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them.

[Tip]Tip

You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs.

Consider the following test:

		this.mockMvc
+				.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
+						.accept(MediaType.APPLICATION_JSON)
+						.contentType(MediaType.APPLICATION_JSON)
+						.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
+				.andExpect(status().isOk()).andExpect(content().string("bar"))
+				// first WireMock
+				.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
+						.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
+						.contentType(MediaType.valueOf("application/json"))
+						.stub("shouldGrantABeerIfOldEnough"))
+				// then Contract DSL documentation
+				.andDo(document("index", SpringCloudContractRestDocs.dslContract()));

The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file.

The contract is called index.groovy and might look like the following example:

import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+    request {
+        method 'POST'
+        url '/foo'
+        body('''
+            {"foo": 23 }
+        ''')
+        headers {
+            header('''Accept''', '''application/json''')
+            header('''Content-Type''', '''application/json''')
+        }
+    }
+    response {
+        status OK()
+        body('''
+        bar
+        ''')
+        headers {
+            header('''Content-Type''', '''application/json;charset=UTF-8''')
+            header('''Content-Length''', '''3''')
+        }
+        testMatchers {
+            jsonPath('$[?(@.foo >= 20)]', byType())
+        }
+    }
+}

The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be index/dsl-contract.adoc.

12. Migrations

[Tip]Tip

For up to date migration guides please visit +the project’s wiki page.

This section covers migrating from one version of Spring Cloud Contract Verifier to the +next version. It covers the following versions upgrade paths:

12.1 1.0.x → 1.1.x

This section covers upgrading from version 1.0 to version 1.1.

12.1.1 New structure of generated stubs

In 1.1.x we have introduced a change to the structure of generated stubs. If you have +been using the @AutoConfigureWireMock notation to use the stubs from the classpath, +it no longer works. The following example shows how the @AutoConfigureWireMock notation +used to work:

@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)

You must either change the location of the stubs to: +classpath:…​/META-INF/groupId/artifactId/version/mappings or use the new +classpath-based @AutoConfigureStubRunner, as shown in the following example:

@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)

If you do not want to use @AutoConfigureStubRunner and you want to remain with the old +structure, set your plugin tasks accordingly. The following example would work for the +structure presented in the previous snippet.

Maven.  +

<!-- start of pom.xml -->
+
+<properties>
+    <!-- we don't want the verifier to do a jar for us -->
+    <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+</properties>
+
+<!-- ... -->
+
+<!-- You need to set up the assembly plugin -->
+<build>
+    <plugins>
+        <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-assembly-plugin</artifactId>
+            <executions>
+                <execution>
+                    <id>stub</id>
+                    <phase>prepare-package</phase>
+                    <goals>
+                        <goal>single</goal>
+                    </goals>
+                    <inherited>false</inherited>
+                    <configuration>
+                        <attach>true</attach>
+                        <descriptor>${basedir}/src/assembly/stub.xml</descriptor>
+                    </configuration>
+                </execution>
+            </executions>
+        </plugin>
+    </plugins>
+</build>
+<!-- end of pom.xml -->
+
+<!-- start of stub.xml-->
+
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>customer-stubs/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>customer-stubs/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+<!-- end of stub.xml-->

+

Gradle.  +

task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
+//    Preserve directory structure from 1.0.X of spring-cloud-contract
+    from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
+    into "${project.buildDir}/resources/main/customer-stubs"
+}

+

12.2 1.1.x → 1.2.x

This section covers upgrading from version 1.1 to version 1.2.

12.2.1 Custom HttpServerStub

HttpServerStub includes a method that was not in version 1.1. The method is +String registeredMappings() If you have classes that implement HttpServerStub, you +now have to implement the registeredMappings() method. It should return a String +representing all mappings available in a single HttpServerStub.

See issue 355 for more +detail.

12.2.2 New packages for generated tests

The flow for setting the generated tests package name will look like this:

  • Set basePackageForTests
  • If basePackageForTests was not set, pick the package from baseClassForTests
  • If baseClassForTests was not set, pick packageWithBaseClasses
  • If nothing got set, pick the default value: +org.springframework.cloud.contract.verifier.tests

See issue 260 for more +detail.

12.2.3 New Methods in TemplateProcessor

In order to add support for fromRequest.path, the following methods had to be added to the +TemplateProcessor interface:

  • path()
  • path(int index)

See issue 388 for more +detail.

12.2.4 RestAssured 3.0

Rest Assured, used in the generated test classes, got bumped to 3.0. If +you manually set versions of Spring Cloud Contract and the release train +you might see the following exception:

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
+[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist

This exception will occur due to the fact that the tests got generated with +an old version of plugin and at test execution time you have an incompatible +version of the release train (and vice versa).

Done via issue 267

12.3 1.2.x → 2.0.x

\ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/checkstyle.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/checkstyle.html new file mode 100644 index 00000000..3758dd1c --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/checkstyle.html @@ -0,0 +1,3803 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Checkstyle Results + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Checkstyle Results

+

The following document contains the results of Checkstyle 8.18 with sun_checks.xml ruleset. rss feed

+
+

Summary

+ + + + + + + + + + +
Files Info Warnings Errors
1200539
+ +
+

Rules

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CategoryRuleViolationsSeverity
blocksRightCurly11 Error
codingAvoidInlineConditionals10 Error
HiddenField36 Error
MagicNumber1 Error
designDesignForExtension23 Error
javadocJavadocMethod58 Error
JavadocPackage2 Error
JavadocType2 Error
JavadocVariable71 Error
miscFinalParameters63 Error
namingConstantName4 Error
sizesLineLength244 Error
ParameterNumber1 Error
whitespaceFileTabCharacter12 Error
NoWhitespaceAfter1 Error
+
+

Details

+
+

org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).20
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).28
 ErrorjavadocJavadocVariableMissing a Javadoc comment.28
 ErrorjavadocJavadocVariableMissing a Javadoc comment.30
 ErrordesignDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'getContractPackageRegex' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'getContractPackageRegex' static/final/abstract/empty, or adding allowed annotation for the method.32
 ErrorjavadocJavadocMethodMissing a Javadoc comment.32
 ErrordesignDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'setContractPackageRegex' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'setContractPackageRegex' static/final/abstract/empty, or adding allowed annotation for the method.36
 ErrorjavadocJavadocMethodMissing a Javadoc comment.36
 ErrormiscFinalParametersParameter contractPackageRegex should be final.36
 ErrorcodingHiddenField'contractPackageRegex' hides a field.36
 ErrordesignDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'getBaseClassFQN' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'getBaseClassFQN' static/final/abstract/empty, or adding allowed annotation for the method.40
 ErrorjavadocJavadocMethodMissing a Javadoc comment.40
 ErrordesignDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'setBaseClassFQN' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'setBaseClassFQN' static/final/abstract/empty, or adding allowed annotation for the method.44
 ErrorjavadocJavadocMethodMissing a Javadoc comment.44
 ErrormiscFinalParametersParameter baseClassFQN should be final.44
 ErrorcodingHiddenField'baseClassFQN' hides a field.44
 ErrordesignDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'equals' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'equals' static/final/abstract/empty, or adding allowed annotation for the method.48
 ErrormiscFinalParametersParameter o should be final.49
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).58
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.58
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).62
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.62
 ErrordesignDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'hashCode' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'hashCode' static/final/abstract/empty, or adding allowed annotation for the method.67
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.70
 ErrorcodingMagicNumber'31' is a magic number.71
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).72
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.72
 ErrordesignDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'toString' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'toString' static/final/abstract/empty, or adding allowed annotation for the method.76
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).78
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).79
+
+

org/springframework/cloud/contract/maven/verifier/ConvertMojo.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).44
 ErrorsizesLineLengthLine is longer than 80 characters (found 86).46
 ErrorsizesLineLengthLine is longer than 80 characters (found 102).51
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).54
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).54
 ErrorjavadocJavadocVariableMissing a Javadoc comment.54
 ErrorjavadocJavadocVariableMissing a Javadoc comment.55
 ErrorjavadocJavadocVariableMissing a Javadoc comment.56
 ErrorjavadocJavadocVariableMissing a Javadoc comment.57
 ErrorjavadocJavadocVariableMissing a Javadoc comment.59
 ErrorjavadocJavadocVariableMissing a Javadoc comment.61
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).65
 ErrorsizesLineLengthLine is longer than 80 characters (found 148).68
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).72
 ErrorsizesLineLengthLine is longer than 80 characters (found 86).81
 ErrorjavadocJavadocVariableMissing a Javadoc comment.86
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).89
 ErrorjavadocJavadocVariableMissing a Javadoc comment.89
 ErrorjavadocJavadocVariableMissing a Javadoc comment.92
 ErrorjavadocJavadocVariableMissing a Javadoc comment.95
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).99
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).100
 ErrorjavadocJavadocVariableMissing a Javadoc comment.106
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).110
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).111
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).112
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).113
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).125
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).156
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).160
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).165
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).173
 ErrorjavadocJavadocVariableMissing a Javadoc comment.184
 ErrorjavadocJavadocMethodMissing a Javadoc comment.187
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).188
 ErrormiscFinalParametersParameter aetherStubDownloaderFactory should be final.188
 ErrorcodingHiddenField'aetherStubDownloaderFactory' hides a field.188
 ErrordesignDesignForExtensionClass 'ConvertMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'ConvertMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.192
 ErrorjavadocJavadocMethodMissing a Javadoc comment.192
 ErrorsizesLineLengthLine is longer than 80 characters (found 132).195
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).202
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).204
 ErrorcodingHiddenField'contractsDirectory' hides a field.206
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).207
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).209
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).212
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).218
 ErrorjavadocJavadocMethodMissing a Javadoc comment.222
 ErrormiscFinalParametersParameter rootPath should be final.222
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).223
 ErrormiscFinalParametersParameter config should be final.223
 ErrormiscFinalParametersParameter contractsDirectory should be final.223
 ErrorcodingHiddenField'contractsDirectory' hides a field.223
 ErrormiscFinalParametersParameter contractsDslDir should be final.224
 ErrorsizesLineLengthLine is longer than 80 characters (found 86).227
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).231
 ErrorjavadocJavadocMethodMissing a Javadoc comment.231
 ErrormiscFinalParametersParameter rootPath should be final.231
 ErrormiscFinalParametersParameter config should be final.231
 ErrormiscFinalParametersParameter contractsDirectory should be final.232
 ErrorcodingHiddenField'contractsDirectory' hides a field.232
 ErrorsizesLineLengthLine is longer than 80 characters (found 96).235
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).236
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).240
 ErrorjavadocJavadocMethodMissing a Javadoc comment.240
 ErrormiscFinalParametersParameter rootPath should be final.240
 ErrormiscFinalParametersParameter config should be final.240
 ErrormiscFinalParametersParameter contractsDirectory should be final.241
 ErrorcodingHiddenField'contractsDirectory' hides a field.241
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.243
 ErrorsizesLineLengthLine is longer than 80 characters (found 107).244
 ErrorsizesLineLengthLine is longer than 80 characters (found 96).245
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).246
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).250
 ErrorjavadocJavadocMethodMissing a Javadoc comment.250
 ErrormiscFinalParametersParameter config should be final.250
 ErrormiscFinalParametersParameter contractsDslDir should be final.250
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).252
 ErrorsizesLineLengthLine is longer than 80 characters (found 119).255
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).257
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).259
 ErrorjavadocJavadocMethodMissing a Javadoc comment.263
 ErrormiscFinalParametersParameter contractsDirectory should be final.263
 ErrorcodingHiddenField'contractsDirectory' hides a field.263
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).264
 ErrorsizesLineLengthLine is longer than 80 characters (found 123).268
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).275
 ErrorjavadocJavadocMethodMissing a Javadoc comment.275
 ErrormiscFinalParametersParameter config should be final.275
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).276
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).277
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).279
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).280
 ErrorsizesLineLengthLine is longer than 80 characters (found 102).281
 ErrorjavadocJavadocMethodMissing a Javadoc comment.285
 ErrormiscFinalParametersParameter rootPath should be final.285
 ErrorsizesLineLengthLine is longer than 80 characters (found 98).286
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.286
 ErrorjavadocJavadocMethodMissing a Javadoc comment.290
 ErrormiscFinalParametersParameter contractsDirectory should be final.290
 ErrorcodingHiddenField'contractsDirectory' hides a field.290
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.291
 ErrorjavadocJavadocMethodMissing a Javadoc comment.294
+
+

org/springframework/cloud/contract/maven/verifier/CopyContracts.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorjavadocJavadocTypeMissing a Javadoc comment.34
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).36
 ErrorjavadocJavadocVariableMissing a Javadoc comment.36
 ErrornamingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.36
 ErrorjavadocJavadocVariableMissing a Javadoc comment.38
 ErrorjavadocJavadocVariableMissing a Javadoc comment.40
 ErrorjavadocJavadocVariableMissing a Javadoc comment.42
 ErrorjavadocJavadocVariableMissing a Javadoc comment.44
 ErrorjavadocJavadocMethodMissing a Javadoc comment.46
 ErrormiscFinalParametersParameter project should be final.46
 ErrorcodingHiddenField'project' hides a field.46
 ErrormiscFinalParametersParameter mavenSession should be final.46
 ErrorcodingHiddenField'mavenSession' hides a field.46
 ErrormiscFinalParametersParameter mavenResourcesFiltering should be final.47
 ErrorcodingHiddenField'mavenResourcesFiltering' hides a field.47
 ErrormiscFinalParametersParameter config should be final.48
 ErrorcodingHiddenField'config' hides a field.48
 ErrorjavadocJavadocMethodMissing a Javadoc comment.55
 ErrormiscFinalParametersParameter contractsDirectory should be final.55
 ErrormiscFinalParametersParameter outputDirectory should be final.55
 ErrorsizesLineLengthLine is longer than 80 characters (found 98).57
 ErrorsizesLineLengthLine is longer than 80 characters (found 102).58
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).59
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).63
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).65
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).69
 ErrorsizesLineLengthLine is longer than 80 characters (found 82).80
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).92
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).98
 ErrorjavadocJavadocMethodMissing a Javadoc comment.98
 ErrormiscFinalParametersParameter includedRootFolderAntPattern should be final.98
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).99
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).101
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).102
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).103
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).109
 ErrorjavadocJavadocMethodMissing a Javadoc comment.109
 ErrormiscFinalParametersParameter includedRootFolderAntPattern should be final.109
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).110
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).112
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).113
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).114
 ErrorjavadocJavadocMethodMissing a Javadoc comment.120
 ErrorjavadocJavadocMethodMissing a Javadoc comment.124
+
+

org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).37
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).42
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).45
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).45
 ErrorjavadocJavadocVariableMissing a Javadoc comment.45
 ErrorsizesLineLengthLine is longer than 80 characters (found 98).48
 ErrorjavadocJavadocVariableMissing a Javadoc comment.48
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).54
 ErrorsizesLineLengthLine is longer than 80 characters (found 96).60
 ErrorjavadocJavadocVariableMissing a Javadoc comment.63
 ErrorjavadocJavadocVariableMissing a Javadoc comment.72
 ErrorjavadocJavadocVariableMissing a Javadoc comment.75
 ErrorjavadocJavadocVariableMissing a Javadoc comment.78
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).81
 ErrordesignDesignForExtensionClass 'GenerateStubsMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateStubsMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.81
 ErrorjavadocJavadocMethodMissing a Javadoc comment.81
 ErrorsizesLineLengthLine is longer than 80 characters (found 129).84
 ErrorsizesLineLengthLine is longer than 80 characters (found 114).85
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).90
 ErrorjavadocJavadocMethodMissing a Javadoc comment.94
 ErrormiscFinalParametersParameter stubsOutputDir should be final.94
 ErrorsizesLineLengthLine is longer than 80 characters (found 86).97
 ErrorsizesLineLengthLine is longer than 80 characters (found 114).99
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).101
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).103
 ErrorsizesLineLengthLine is longer than 80 characters (found 82).105
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).106
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).108
 ErrorwhitespaceNoWhitespaceAfter'{' is followed by whitespace.108
 ErrorsizesLineLengthLine is longer than 80 characters (found 99).109
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.109
 ErrorsizesLineLengthLine is longer than 80 characters (found 109).113
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).115
 ErrorsizesLineLengthLine is longer than 80 characters (found 101).118
 ErrorjavadocJavadocMethodMissing a Javadoc comment.123
 ErrorjavadocJavadocMethodMissing a Javadoc comment.133
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).134
+
+

org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).47
 ErrorsizesLineLengthLine is longer than 80 characters (found 135).52
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).55
 ErrorjavadocJavadocVariableMissing a Javadoc comment.55
 ErrorjavadocJavadocVariableMissing a Javadoc comment.57
 ErrorsizesLineLengthLine is longer than 80 characters (found 148).60
 ErrorjavadocJavadocVariableMissing a Javadoc comment.60
 ErrorsizesLineLengthLine is longer than 80 characters (found 96).63
 ErrorjavadocJavadocVariableMissing a Javadoc comment.63
 ErrorsizesLineLengthLine is longer than 80 characters (found 98).66
 ErrorjavadocJavadocVariableMissing a Javadoc comment.66
 ErrorjavadocJavadocVariableMissing a Javadoc comment.69
 ErrorjavadocJavadocVariableMissing a Javadoc comment.72
 ErrorjavadocJavadocVariableMissing a Javadoc comment.75
 ErrorjavadocJavadocVariableMissing a Javadoc comment.78
 ErrorjavadocJavadocVariableMissing a Javadoc comment.81
 ErrorjavadocJavadocVariableMissing a Javadoc comment.84
 ErrorsizesLineLengthLine is longer than 80 characters (found 86).112
 ErrorsizesLineLengthLine is longer than 80 characters (found 99).115
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).119
 ErrorjavadocJavadocVariableMissing a Javadoc comment.124
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).127
 ErrorjavadocJavadocVariableMissing a Javadoc comment.127
 ErrorjavadocJavadocVariableMissing a Javadoc comment.130
 ErrorjavadocJavadocVariableMissing a Javadoc comment.133
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).137
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).138
 ErrorjavadocJavadocVariableMissing a Javadoc comment.144
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).148
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).149
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).150
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).151
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).163
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).164
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).166
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).168
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).175
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).176
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).178
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).179
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).210
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).214
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).219
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).227
 ErrorjavadocJavadocMethodMissing a Javadoc comment.232
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).233
 ErrormiscFinalParametersParameter aetherStubDownloaderFactory should be final.233
 ErrorcodingHiddenField'aetherStubDownloaderFactory' hides a field.233
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).237
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.237
 ErrorjavadocJavadocMethodMissing a Javadoc comment.237
 ErrorsizesLineLengthLine is longer than 80 characters (found 137).241
 ErrorsizesLineLengthLine is longer than 80 characters (found 117).246
 ErrorsizesLineLengthLine is longer than 80 characters (found 86).247
 ErrorsizesLineLengthLine is longer than 80 characters (found 110).251
 ErrorsizesLineLengthLine is longer than 80 characters (found 82).252
 ErrorsizesLineLengthLine is longer than 80 characters (found 128).257
 ErrorsizesLineLengthLine is longer than 80 characters (found 103).258
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).260
 ErrorcodingHiddenField'contractsDirectory' hides a field.260
 ErrorsizesLineLengthLine is longer than 80 characters (found 105).261
 ErrorsizesLineLengthLine is longer than 80 characters (found 95).262
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).263
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).264
 ErrorsizesLineLengthLine is longer than 80 characters (found 102).265
 ErrorsizesLineLengthLine is longer than 80 characters (found 102).268
 ErrorsizesLineLengthLine is longer than 80 characters (found 106).271
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).273
 ErrorsizesLineLengthLine is longer than 80 characters (found 102).277
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).280
 ErrorsizesLineLengthLine is longer than 80 characters (found 101).281
 ErrorsizesLineLengthLine is longer than 80 characters (found 101).282
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).288
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).289
 ErrorsizesLineLengthLine is longer than 80 characters (found 108).292
 ErrorjavadocJavadocMethodMissing a Javadoc comment.298
 ErrormiscFinalParametersParameter config should be final.298
 ErrormiscFinalParametersParameter contractsDirectory should be final.299
 ErrorcodingHiddenField'contractsDirectory' hides a field.299
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).302
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'mappingsToMap' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'mappingsToMap' static/final/abstract/empty, or adding allowed annotation for the method.321
 ErrorjavadocJavadocMethodMissing a Javadoc comment.321
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).327
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'getExcludedFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'getExcludedFiles' static/final/abstract/empty, or adding allowed annotation for the method.332
 ErrorjavadocJavadocMethodMissing a Javadoc comment.332
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'setExcludedFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'setExcludedFiles' static/final/abstract/empty, or adding allowed annotation for the method.336
 ErrorjavadocJavadocMethodMissing a Javadoc comment.336
 ErrormiscFinalParametersParameter excludedFiles should be final.336
 ErrorcodingHiddenField'excludedFiles' hides a field.336
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'getIgnoredFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'getIgnoredFiles' static/final/abstract/empty, or adding allowed annotation for the method.340
 ErrorjavadocJavadocMethodMissing a Javadoc comment.340
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'setIgnoredFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'setIgnoredFiles' static/final/abstract/empty, or adding allowed annotation for the method.344
 ErrorjavadocJavadocMethodMissing a Javadoc comment.344
 ErrormiscFinalParametersParameter ignoredFiles should be final.344
 ErrorcodingHiddenField'ignoredFiles' hides a field.344
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'isAssertJsonSize' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'isAssertJsonSize' static/final/abstract/empty, or adding allowed annotation for the method.348
 ErrorjavadocJavadocMethodMissing a Javadoc comment.348
 ErrordesignDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'setAssertJsonSize' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'setAssertJsonSize' static/final/abstract/empty, or adding allowed annotation for the method.352
 ErrorjavadocJavadocMethodMissing a Javadoc comment.352
 ErrormiscFinalParametersParameter assertJsonSize should be final.352
 ErrorcodingHiddenField'assertJsonSize' hides a field.352
+
+

org/springframework/cloud/contract/maven/verifier/ManifestCreator.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorjavadocJavadocTypeMissing a Javadoc comment.27
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).29
 ErrorjavadocJavadocMethodMissing a Javadoc comment.29
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).30
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).33
 ErrorjavadocJavadocMethodMissing a Javadoc comment.33
 ErrormiscFinalParametersParameter project should be final.33
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).35
 ErrorsizesLineLengthLine is longer than 80 characters (found 108).38
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).39
 ErrorsizesLineLengthLine is longer than 80 characters (found 86).42
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).46
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).47
 ErrorsizesLineLengthLine is longer than 80 characters (found 108).48
 ErrorjavadocJavadocMethodMissing a Javadoc comment.54
 ErrormiscFinalParametersParameter plugins should be final.54
 ErrorsizesLineLengthLine is longer than 80 characters (found 98).56
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).63
 ErrorjavadocJavadocMethodMissing a Javadoc comment.63
 ErrormiscFinalParametersParameter deps should be final.63
 ErrorsizesLineLengthLine is longer than 80 characters (found 91).65
+
+

org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorjavadocJavadocPackageMissing package-info.java file.1
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).44
 ErrorjavadocJavadocVariableMissing a Javadoc comment.44
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).46
 ErrorjavadocJavadocVariableMissing a Javadoc comment.46
 ErrorjavadocJavadocVariableMissing a Javadoc comment.48
 ErrorjavadocJavadocVariableMissing a Javadoc comment.50
 ErrorjavadocJavadocVariableMissing a Javadoc comment.52
 ErrorjavadocJavadocVariableMissing a Javadoc comment.54
 ErrorjavadocJavadocVariableMissing a Javadoc comment.56
 ErrorjavadocJavadocVariableMissing a Javadoc comment.58
 ErrorsizesLineLengthLine is longer than 80 characters (found 82).60
 ErrorjavadocJavadocVariableMissing a Javadoc comment.60
 ErrorjavadocJavadocVariableMissing a Javadoc comment.62
 ErrorjavadocJavadocVariableMissing a Javadoc comment.64
 ErrorjavadocJavadocVariableMissing a Javadoc comment.66
 ErrorjavadocJavadocVariableMissing a Javadoc comment.68
 ErrorjavadocJavadocVariableMissing a Javadoc comment.70
 ErrorjavadocJavadocVariableMissing a Javadoc comment.72
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).74
 ErrorjavadocJavadocMethodMissing a Javadoc comment.74
 ErrorsizesParameterNumberMore than 7 parameters (found 12).74
 ErrormiscFinalParametersParameter project should be final.74
 ErrorcodingHiddenField'project' hides a field.74
 ErrormiscFinalParametersParameter contractDependency should be final.74
 ErrorcodingHiddenField'contractDependency' hides a field.74
 ErrormiscFinalParametersParameter contractsPath should be final.75
 ErrorcodingHiddenField'contractsPath' hides a field.75
 ErrormiscFinalParametersParameter contractsRepositoryUrl should be final.75
 ErrorcodingHiddenField'contractsRepositoryUrl' hides a field.75
 ErrorsizesLineLengthLine is longer than 80 characters (found 101).76
 ErrormiscFinalParametersParameter stubsMode should be final.76
 ErrorcodingHiddenField'stubsMode' hides a field.76
 ErrormiscFinalParametersParameter log should be final.76
 ErrorcodingHiddenField'log' hides a field.76
 ErrormiscFinalParametersParameter repositoryUsername should be final.76
 ErrorcodingHiddenField'repositoryUsername' hides a field.76
 ErrormiscFinalParametersParameter repositoryPassword should be final.77
 ErrorcodingHiddenField'repositoryPassword' hides a field.77
 ErrormiscFinalParametersParameter repositoryProxyHost should be final.77
 ErrorcodingHiddenField'repositoryProxyHost' hides a field.77
 ErrorsizesLineLengthLine is longer than 80 characters (found 82).78
 ErrormiscFinalParametersParameter repositoryProxyPort should be final.78
 ErrorcodingHiddenField'repositoryProxyPort' hides a field.78
 ErrormiscFinalParametersParameter deleteStubsAfterTest should be final.78
 ErrorcodingHiddenField'deleteStubsAfterTest' hides a field.78
 ErrormiscFinalParametersParameter contractsProperties should be final.79
 ErrorcodingHiddenField'contractsProperties' hides a field.79
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).90
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).95
 ErrorjavadocJavadocMethodMissing a Javadoc comment.95
 ErrormiscFinalParametersParameter config should be final.95
 ErrormiscFinalParametersParameter defaultContractsDir should be final.96
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).99
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.100
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).102
 ErrorsizesLineLengthLine is longer than 80 characters (found 108).104
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).105
 ErrorsizesLineLengthLine is longer than 80 characters (found 98).106
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).109
 ErrorsizesLineLengthLine is longer than 80 characters (found 124).112
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).115
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).119
 ErrorjavadocJavadocMethodMissing a Javadoc comment.124
 ErrorsizesLineLengthLine is longer than 80 characters (found 95).126
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).127
 ErrorjavadocJavadocMethodMissing a Javadoc comment.130
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).131
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).133
 ErrorjavadocJavadocMethodMissing a Javadoc comment.136
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).138
 ErrorjavadocJavadocMethodMissing a Javadoc comment.141
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).142
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).143
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).144
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).146
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).149
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).152
 ErrorjavadocJavadocMethodMissing a Javadoc comment.157
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).160
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).161
 ErrorcodingAvoidInlineConditionalsAvoid inline conditionals.161
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).163
+
+

org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).44
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).44
 ErrorjavadocJavadocVariableMissing a Javadoc comment.44
 ErrorsizesLineLengthLine is longer than 80 characters (found 98).47
 ErrorjavadocJavadocVariableMissing a Javadoc comment.47
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).53
 ErrorsizesLineLengthLine is longer than 80 characters (found 113).59
 ErrorjavadocJavadocVariableMissing a Javadoc comment.62
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).78
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).79
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).92
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).100
 ErrordesignDesignForExtensionClass 'PushStubsToScmMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'PushStubsToScmMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.105
 ErrorjavadocJavadocMethodMissing a Javadoc comment.105
 ErrorsizesLineLengthLine is longer than 80 characters (found 129).108
 ErrorsizesLineLengthLine is longer than 80 characters (found 119).110
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).114
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).115
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).116
 ErrorsizesLineLengthLine is longer than 80 characters (found 123).117
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).121
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).122
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).123
 ErrordesignDesignForExtensionClass 'PushStubsToScmMojo' looks like designed for extension (can be subclassed), but the method 'buildOptions' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'PushStubsToScmMojo' final or making the method 'buildOptions' static/final/abstract/empty, or adding allowed annotation for the method.127
 ErrorjavadocJavadocMethodMissing a Javadoc comment.127
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).128
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).129
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).130
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).134
+
+

org/springframework/cloud/contract/maven/verifier/RunMojo.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).48
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).51
 ErrorjavadocJavadocVariableMissing a Javadoc comment.51
 ErrorjavadocJavadocVariableMissing a Javadoc comment.53
 ErrorjavadocJavadocVariableMissing a Javadoc comment.55
 ErrorjavadocJavadocVariableMissing a Javadoc comment.58
 ErrorjavadocJavadocVariableMissing a Javadoc comment.61
 ErrorsizesLineLengthLine is longer than 80 characters (found 96).67
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).73
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).79
 ErrorsizesLineLengthLine is longer than 80 characters (found 84).83
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).91
 ErrorsizesLineLengthLine is longer than 80 characters (found 100).97
 ErrorsizesLineLengthLine is longer than 80 characters (found 89).101
 ErrorsizesLineLengthLine is longer than 80 characters (found 107).103
 ErrorjavadocJavadocVariableMissing a Javadoc comment.112
 ErrorjavadocJavadocMethodMissing a Javadoc comment.115
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).116
 ErrormiscFinalParametersParameter localStubRunner should be final.116
 ErrorcodingHiddenField'localStubRunner' hides a field.116
 ErrormiscFinalParametersParameter remoteStubRunner should be final.116
 ErrorcodingHiddenField'remoteStubRunner' hides a field.116
 ErrorsizesLineLengthLine is longer than 80 characters (found 83).121
 ErrordesignDesignForExtensionClass 'RunMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'RunMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.121
 ErrorjavadocJavadocMethodMissing a Javadoc comment.121
 ErrorsizesLineLengthLine is longer than 80 characters (found 107).124
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).129
 ErrorsizesLineLengthLine is longer than 80 characters (found 94).133
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).135
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).136
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).137
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).139
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).140
 ErrorsizesLineLengthLine is longer than 80 characters (found 95).141
 ErrorblocksRightCurly'}' at column 4 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).147
 ErrorsizesLineLengthLine is longer than 80 characters (found 103).149
 ErrorjavadocJavadocMethodMissing a Javadoc comment.154
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).157
 ErrorjavadocJavadocMethodMissing a Javadoc comment.163
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).170
 ErrorjavadocJavadocMethodMissing a Javadoc comment.175
+
+

org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorjavadocJavadocPackageMissing package-info.java file.1
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).45
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).45
 ErrorjavadocJavadocVariableMissing a Javadoc comment.45
 ErrornamingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.45
 ErrorjavadocJavadocVariableMissing a Javadoc comment.47
 ErrorjavadocJavadocVariableMissing a Javadoc comment.49
 ErrorjavadocJavadocMethodMissing a Javadoc comment.51
 ErrormiscFinalParametersParameter repoSystem should be final.52
 ErrorcodingHiddenField'repoSystem' hides a field.52
 ErrormiscFinalParametersParameter project should be final.53
 ErrorcodingHiddenField'project' hides a field.53
 ErrorsizesLineLengthLine is longer than 80 characters (found 87).58
 ErrordesignDesignForExtensionClass 'AetherStubDownloaderFactory' looks like designed for extension (can be subclassed), but the method 'build' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'AetherStubDownloaderFactory' final or making the method 'build' static/final/abstract/empty, or adding allowed annotation for the method.58
 ErrorjavadocJavadocMethodMissing a Javadoc comment.58
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).61
 ErrormiscFinalParametersParameter stubRunnerOptions should be final.61
 ErrorsizesLineLengthLine is longer than 80 characters (found 120).63
 ErrorsizesLineLengthLine is longer than 80 characters (found 92).65
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).66
 ErrorsizesLineLengthLine is longer than 80 characters (found 96).67
 ErrorsizesLineLengthLine is longer than 80 characters (found 97).72
 ErrormiscFinalParametersParameter location should be final.72
 ErrormiscFinalParametersParameter resourceLoader should be final.72
+
+

org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).36
 ErrorjavadocJavadocVariableMissing a Javadoc comment.36
 ErrornamingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.36
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).38
 ErrordesignDesignForExtensionClass 'LocalStubRunner' looks like designed for extension (can be subclassed), but the method 'run' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'LocalStubRunner' final or making the method 'run' static/final/abstract/empty, or adding allowed annotation for the method.38
 ErrorjavadocJavadocMethodMissing a Javadoc comment.38
 ErrormiscFinalParametersParameter options should be final.38
 ErrorsizesLineLengthLine is longer than 80 characters (found 85).39
+
+

org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityCategoryRuleMessageLine
 ErrorsizesLineLengthLine is longer than 80 characters (found 81).40
 ErrorwhitespaceFileTabCharacterFile contains tab characters (this is the first instance).40
 ErrorjavadocJavadocVariableMissing a Javadoc comment.40
 ErrornamingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.40
 ErrorjavadocJavadocVariableMissing a Javadoc comment.42
 ErrorjavadocJavadocMethodMissing a Javadoc comment.44
 ErrorsizesLineLengthLine is longer than 80 characters (found 90).45
 ErrormiscFinalParametersParameter aetherStubDownloaderFactory should be final.45
 ErrorcodingHiddenField'aetherStubDownloaderFactory' hides a field.45
 ErrordesignDesignForExtensionClass 'RemoteStubRunner' looks like designed for extension (can be subclassed), but the method 'run' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'RemoteStubRunner' final or making the method 'run' static/final/abstract/empty, or adding allowed annotation for the method.49
 ErrorjavadocJavadocMethodMissing a Javadoc comment.49
 ErrormiscFinalParametersParameter options should be final.49
 ErrormiscFinalParametersParameter repositorySystemSession should be final.50
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).55
 ErrorsizesLineLengthLine is longer than 80 characters (found 88).57
 ErrorsizesLineLengthLine is longer than 80 characters (found 82).59
 ErrorblocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).62
 ErrorsizesLineLengthLine is longer than 80 characters (found 93).64
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/checkstyle.rss b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/checkstyle.rss new file mode 100644 index 00000000..8fba292b --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/checkstyle.rss @@ -0,0 +1,222 @@ + + + + + Spring Cloud Contract Maven Plugin - Checkstyle report + https://github.com/spring-cloud/spring-cloud-contract + Spring Cloud Contract Maven Plugin - Checkstyle report + en-us + ©2016 - 2019 Spring + + File: 12, + Errors: 539, + Warnings: 0, + Infos: 0 + + https://github.com/spring-cloud/spring-cloud-contract/checkstyle.html + +

Click here for the full Checkstyle report.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FilesIWE
+ org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java + + 0 + + 0 + + 83 +
+ org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java + + 0 + + 0 + + 101 +
+ org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java + + 0 + + 0 + + 37 +
+ org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java + + 0 + + 0 + + 30 +
+ org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java + + 0 + + 0 + + 29 +
+ org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java + + 0 + + 0 + + 24 +
+ org/springframework/cloud/contract/maven/verifier/RunMojo.java + + 0 + + 0 + + 41 +
+ org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java + + 0 + + 0 + + 18 +
+ org/springframework/cloud/contract/maven/verifier/CopyContracts.java + + 0 + + 0 + + 44 +
+ org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java + + 0 + + 0 + + 8 +
+ org/springframework/cloud/contract/maven/verifier/ManifestCreator.java + + 0 + + 0 + + 21 +
+ org/springframework/cloud/contract/maven/verifier/ConvertMojo.java + + 0 + + 0 + + 103 +
+ +
+
+
+
+ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/ci-management.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/ci-management.html new file mode 100644 index 00000000..5332ae46 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/ci-management.html @@ -0,0 +1,351 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – CI Management + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Overview

+

This project uses Continuous Integration System.

+
+

Access

+

The following is a link to the continuous integration system used by the project:

+
+
+

Notifiers

+

No notifiers are defined. Please check back at a later date.

+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/complex.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/complex.html new file mode 100644 index 00000000..cb242ad5 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/complex.html @@ -0,0 +1,469 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

More Complex Plugin Configuration

+
+
+

Sample more complex configuration for Java Project with JUnit tests.

+
+
+

Project configuration for Spring Cloud Contract Verifier with JUnit tests and stub publishing

+
+
+
                        <plugin>
+                                <groupId>org.springframework.cloud</groupId>
+                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                <version>${spring-cloud-verifier-plugin.version}</version>
+                                <executions>
+                                        <execution>
+                                                <goals>
+                                                        <goal>convert</goal>
+                                                        <goal>generateStubs</goal>
+                                                        <goal>generateTests</goal>
+                                                </goals>
+                                                <configuration>
+                                                        <contractsDirectory>src/test/contracts</contractsDirectory>
+                                                        <basePackageForTests>
+                                                                com.blogspot.toomuchcoding.frauddetection
+                                                        </basePackageForTests>
+                                                        <testMode>MOCKMVC</testMode>
+                                                        <testFramework>JUNIT</testFramework>
+                                                        <classifier>stubs</classifier>
+                                                        <nameSuffixForTests>Test</nameSuffixForTests>
+                                                        <ruleClassForTests>org.junit.rules.ErrorCollector
+                                                        </ruleClassForTests>
+                                                        <staticImports>
+                                                                <staticImport>
+                                                                        com.blogspot.toomuchcoding.frauddetection.matchers.CustomMatchers.*
+                                                                </staticImport>
+                                                        </staticImports>
+                                                        <imports>
+                                                                <import>
+                                                                        com.blogspot.toomuchcoding.frauddetection.matchers.CustomMatchers
+                                                                </import>
+                                                        </imports>
+                                                        <ignoredFiles>
+                                                                <ignoredFile>broken**</ignoredFile>
+                                                        </ignoredFiles>
+                                                        <excludedFiles>
+                                                                <param>shouldMarkClientAsFraud.groovy</param>
+                                                        </excludedFiles>
+                                                </configuration>
+                                        </execution>
+                                </executions>
+                                <configuration>
+                                        <baseClassForTests>
+                                                com.blogspot.toomuchcoding.frauddetection.BaseAccurest
+                                        </baseClassForTests>
+                                </configuration>
+                        </plugin>
+
+
+
+
+

Base Test class

+
+
+
/*
+ * Copyright 2013-2019 the original author or 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.
+ */package com.blogspot.toomuchcoding.frauddetection;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+
+public class BaseAccurest {
+
+        @Before
+        public void setup() {
+                RestAssuredMockMvc.standaloneSetup(new FraudDetectionController());
+        }
+
+}
+
+
+
+
+

Sample additional matcher

+
+
+
/*
+ * Copyright 2013-2019 the original author or 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.
+ */package com.blogspot.toomuchcoding.frauddetection.matchers;
+
+import org.junit.Assert;
+
+public class CustomMatchers {
+
+        public static void assertThatRejectionReasonIsNull(String rejectionReason) {
+                Assert.assertNull(rejectionReason);
+        }
+
+}
+
+
+
+
+

Sample contract using matcher

+
+
+
/*
+ * Copyright 2013-2019 the original author or 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.
+ */ org.springframework.cloud.contract.spec.Contract.make {
+        request {
+                method 'PUT'
+                url '/fraudcheck'
+                body("""
+                                                {
+                                                "clientPesel":"${
+                        value(consumer(regex('[0-9]{10}')), producer('1234567890'))
+                }",
+                                                "loanAmount":123.123
+                                                }
+                                        """
+                )
+                headers {
+                        header('Content-Type', 'application/vnd.fraud.v1+json')
+                }
+
+        }
+        response {
+                status OK()
+                body(
+                                fraudCheckStatus: "OK",
+                                rejectionReason: $(consumer(null),
+                                                producer(execute('assertThatRejectionReasonIsNull($it)')))
+                )
+                headers {
+                        header('Content-Type': 'application/vnd.fraud.v1+json')
+                }
+        }
+
+}
+
+
+
+ +
+

More samples

+
+

You can check out the Spring Cloud Contract Samples project for +more examples of Maven plugin setup.

+
+
+
+
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/configs.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/configs.html new file mode 100644 index 00000000..1718acf0 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/configs.html @@ -0,0 +1,364 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Configuration snippets

+
+
+

Here you’ll be able to see different Spring Cloud Contract Maven plugin configuration

+
+
+

Base class from mappings

+
+

Define regular expression mappings to map a contract to its base class.

+
+
+
+
                        <plugin>
+                                <groupId>org.springframework.cloud</groupId>
+                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                <configuration>
+                                        <baseClassForTests>com.example.FooBase</baseClassForTests>
+                                        <baseClassMappings>
+                                                <baseClassMapping>
+                                                        <contractPackageRegex>.*com.*</contractPackageRegex>
+                                                        <baseClassFQN>com.example.TestBase</baseClassFQN>
+                                                </baseClassMapping>
+                                        </baseClassMappings>
+                                </configuration>
+                        </plugin>
+
+
+
+
+

Convention based mappings

+
+

Define a package in which base classes are placed. In this case we define +a package called hello. If there’s a contract under /contracts/hello/V1/Contract.groovy` then +we’ll search for a HelloV1Base base class. We’re taking two last folders +from the path and combine them into a class name.

+
+
+
+
                        <plugin>
+                                <groupId>org.springframework.cloud</groupId>
+                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                <configuration>
+                                        <packageWithBaseClasses>hello</packageWithBaseClasses>
+                                </configuration>
+                        </plugin>
+
+
+
+
+

Remote contracts

+
+

Here you can see a setup where we point to a repository where the JAR with the +contracts got deployed.

+
+
+
+
                        <plugin>
+                                <groupId>org.springframework.cloud</groupId>
+                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                <configuration>
+                                        <contractsMode>REMOTE</contractsMode>
+                                        <contractsRepositoryUrl>
+                                                https://link/to/your/nexus/or/artifactory/or/sth
+                                        </contractsRepositoryUrl>
+                                        <contractDependency>
+                                                <groupId>com.example.standalone</groupId>
+                                                <artifactId>contracts</artifactId>
+                                        </contractDependency>
+                                </configuration>
+                        </plugin>
+
+
+
+
+

Setting up repo with common contracts

+
+

A setup of a repo that contains all common contracts. It can exclude the target / build +folder that gets created when you’re installing stubs locally as a consumer.

+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/convert-mojo.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/convert-mojo.html new file mode 100644 index 00000000..0caa0922 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/convert-mojo.html @@ -0,0 +1,800 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – spring-cloud-contract:convert + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ + + +
+

spring-cloud-contract:convert

+ +

Full name:

+ +

org.springframework.cloud:spring-cloud-contract-maven-plugin:2.1.2.RELEASE:convert

+ +

Description:

+ +
Convert Spring Cloud Contract Verifier contracts into WireMock +stubs mappings. + +

This goal allows you to generate `stubs-jar` or execute +`spring-cloud-contract:run` with generated WireMock mappings.

+ +

Attributes:

+ + + +
+

Optional Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeSinceDescription
contractDependencyDependency-(no description)
User property is: contractDependency.
contractsDirectoryFile-Directory containing Spring Cloud Contract Verifier contracts +written using the GroovyDSL.
Default value is: ${project.basedir}/src/test/resources/contracts.
User property is: spring.cloud.contract.verifier.contractsDirectory.
contractsModeStubRunnerProperties$StubsMode-Picks the mode in which stubs will be found and registered.
Default value is: CLASSPATH.
User property is: contractsMode.
contractsPathString-The path in the JAR with all the contracts where contracts for this +particular service lay. If not provided will be resolved to +groupid/artifactid. Example: If groupid +is com.example and artifactid is +service then the resolved path will be +/com/example/artifactid
User property is: contractsPath.
contractsPropertiesMap-Map of properties that can be passed to custom +StubDownloaderBuilder.
User property is: contractsProperties.
contractsRepositoryPasswordString-The password to be used to connect to the repo with contracts.
User property is: contractsRepositoryPassword.
contractsRepositoryProxyHostString-The proxy host to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyHost.
contractsRepositoryProxyPortInteger-The proxy port to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyPort.
contractsRepositoryUrlString-The URL from which a JAR containing the contracts should get +downloaded. If not provided but artifactid / coordinates notation +was provided then the current Maven's build repositories will be +taken into consideration
User property is: contractsRepositoryUrl.
contractsRepositoryUsernameString-The user name to be used to connect to the repo with contracts.
User property is: contractsRepositoryUsername.
contractsSnapshotCheckSkipboolean-Deprecated. - with 2.1.0 this option is redundant
Default value is: false.
User property is: contractsSnapshotCheckSkip.
convertToYamlboolean-If true then will convert contracts to a YAML +representation.
Default value is: false.
User property is: convertToYaml.
deleteStubsAfterTestboolean-If set to false will NOT delete stubs from a temporary +folder after running tests.
Default value is: true.
User property is: deleteStubsAfterTest.
destinationFile-(no description)
Default value is: ${basedir}.
User property is: stubsDirectory.
excludeBuildFoldersboolean-If true then any file laying in a path that contains +build or target will get excluded in +further processing.
Default value is: false.
User property is: excludeBuildFolders.
skipboolean-(no description)
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
sourceFile-Directory containing contracts written using the GroovyDSL + +

This parameter is only used when goal is executed outside of +maven project.


Default value is: ${basedir}.
User property is: contractsDirectory.
stubsDirectoryFile-Directory where the generated WireMock stubs from Groovy DSL should +be placed. You can then mention them in your packaging task to +create jar with stubs
Default value is: ${project.build.directory}/stubs/.
+
+ +
+

Parameter Details

+ +

contractDependency:

+ +
(no description)
+ +
    + +
  • Type: org.apache.maven.model.Dependency
  • + +
  • Required: No
  • + +
  • User Property: contractDependency
  • +

+

contractsDirectory:

+ +
Directory containing Spring Cloud Contract Verifier contracts +written using the GroovyDSL.
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.contractsDirectory
  • + +
  • Default: ${project.basedir}/src/test/resources/contracts
  • +

+

contractsMode:

+ +
Picks the mode in which stubs will be found and registered.
+ +
    + +
  • Type: org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties$StubsMode
  • + +
  • Required: No
  • + +
  • User Property: contractsMode
  • + +
  • Default: CLASSPATH
  • +

+

contractsPath:

+ +
The path in the JAR with all the contracts where contracts for this +particular service lay. If not provided will be resolved to +groupid/artifactid. Example: If groupid +is com.example and artifactid is +service then the resolved path will be +/com/example/artifactid
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsPath
  • +

+

contractsProperties:

+ +
Map of properties that can be passed to custom +StubDownloaderBuilder.
+ +
    + +
  • Type: java.util.Map
  • + +
  • Required: No
  • + +
  • User Property: contractsProperties
  • +

+

contractsRepositoryPassword:

+ +
The password to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryPassword
  • +

+

contractsRepositoryProxyHost:

+ +
The proxy host to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryProxyHost
  • +

+

contractsRepositoryProxyPort:

+ +
The proxy port to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.Integer
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryProxyPort
  • +

+

contractsRepositoryUrl:

+ +
The URL from which a JAR containing the contracts should get +downloaded. If not provided but artifactid / coordinates notation +was provided then the current Maven's build repositories will be +taken into consideration
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryUrl
  • +

+

contractsRepositoryUsername:

+ +
The user name to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryUsername
  • +

+

contractsSnapshotCheckSkip:

+ +
Deprecated. - with 2.1.0 this option is redundant
+ +
If true then will not assert whether a stub / contract +JAR was downloaded from local or remote location.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: contractsSnapshotCheckSkip
  • + +
  • Default: false
  • +

+

convertToYaml:

+ +
If true then will convert contracts to a YAML +representation.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: convertToYaml
  • + +
  • Default: false
  • +

+

deleteStubsAfterTest:

+ +
If set to false will NOT delete stubs from a temporary +folder after running tests.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: deleteStubsAfterTest
  • + +
  • Default: true
  • +

+

destination:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • User Property: stubsDirectory
  • + +
  • Default: ${basedir}
  • +

+

excludeBuildFolders:

+ +
If true then any file laying in a path that contains +build or target will get excluded in +further processing.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: excludeBuildFolders
  • + +
  • Default: false
  • +

+

skip:

+ +
(no description)
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.skip
  • + +
  • Default: false
  • +

+

source:

+ +
Directory containing contracts written using the GroovyDSL + +

This parameter is only used when goal is executed outside of +maven project.

+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • User Property: contractsDirectory
  • + +
  • Default: ${basedir}
  • +

+

stubsDirectory:

+ +
Directory where the generated WireMock stubs from Groovy DSL should +be placed. You can then mention them in your packaging task to +create jar with stubs
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • Default: ${project.build.directory}/stubs/
  • +
+
+
+ + +
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/apache-maven-fluido-1.5.min.css b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/apache-maven-fluido-1.5.min.css new file mode 100644 index 00000000..38762711 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/apache-maven-fluido-1.5.min.css @@ -0,0 +1,9 @@ +/*! + * Bootstrap v2.3.2 + * + * Copyright 2013 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world by @mdo and @fat. + */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333;background-color:#fff}a{color:#08c;text-decoration:none}a:hover,a:focus{color:#005580;text-decoration:underline}.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.span12{width:940px}.span11{width:860px}.span10{width:780px}.span9{width:700px}.span8{width:620px}.span7{width:540px}.span6{width:460px}.span5{width:380px}.span4{width:300px}.span3{width:220px}.span2{width:140px}.span1{width:60px}.offset12{margin-left:980px}.offset11{margin-left:900px}.offset10{margin-left:820px}.offset9{margin-left:740px}.offset8{margin-left:660px}.offset7{margin-left:580px}.offset6{margin-left:500px}.offset5{margin-left:420px}.offset4{margin-left:340px}.offset3{margin-left:260px}.offset2{margin-left:180px}.offset1{margin-left:100px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%}.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%}.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%}.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%}.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%}.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%}.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%}.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%}.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%}.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%}.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%}.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%}.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%}.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%}.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%}.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%}.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%}.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%}.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%}.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%}.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%}.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%}.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%}.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%}.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%}.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%}[class*="span"].hide,.row-fluid [class*="span"].hide{display:none}[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right}.container{margin-right:auto;margin-left:auto;*zoom:1}.container:before,.container:after{display:table;line-height:0;content:""}.container:after{clear:both}.container-fluid{padding-right:20px;padding-left:20px;*zoom:1}.container-fluid:before,.container-fluid:after{display:table;line-height:0;content:""}.container-fluid:after{clear:both}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px}small{font-size:85%}strong{font-weight:bold}em{font-style:italic}cite{font-style:normal}.muted{color:#999}a.muted:hover,a.muted:focus{color:#808080}.text-warning{color:#c09853}a.text-warning:hover,a.text-warning:focus{color:#a47e3c}.text-error{color:#b94a48}a.text-error:hover,a.text-error:focus{color:#953b39}.text-info{color:#3a87ad}a.text-info:hover,a.text-info:focus{color:#2d6987}.text-success{color:#468847}a.text-success:hover,a.text-success:focus{color:#356635}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:20px;color:inherit;text-rendering:optimizelegibility}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{line-height:40px}h1{font-size:38.5px}h2{font-size:31.5px}h3{font-size:24.5px}h4{font-size:17.5px}h5{font-size:14px}h6{font-size:11.9px}h1 small{font-size:24.5px}h2 small{font-size:17.5px}h3 small{font-size:14px}h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eee}ul,ol{padding:0;margin:0 0 10px 25px}ul ul,ul ol,ol ol,ol ul{margin-bottom:0}li{line-height:20px}ul.unstyled,ol.unstyled{margin-left:0;list-style:none}ul.inline,ol.inline{margin-left:0;list-style:none}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;padding-right:5px;padding-left:5px;*zoom:1}dl{margin-bottom:20px}dt,dd{line-height:20px}dt{font-weight:bold}dd{margin-left:10px}.dl-horizontal{*zoom:1}.dl-horizontal:before,.dl-horizontal:after{display:table;line-height:0;content:""}.dl-horizontal:after{clear:both}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}hr{margin:20px 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{margin-bottom:0;font-size:17.5px;font-weight:300;line-height:1.25}blockquote small{display:block;line-height:20px;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:20px}code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}code{padding:2px 4px;color:#d14;white-space:nowrap;background-color:#f7f7f9;border:1px solid #e1e1e8}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}form{margin:0 0 20px}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5}legend small{font-size:15px;color:#999}label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px}input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif}label{display:block;margin-bottom:5px}select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}input,textarea,.uneditable-input{width:206px}textarea{height:auto}textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;*margin-top:0;line-height:normal}input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto}select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px}select{width:220px;background-color:#fff;border:1px solid #ccc}select[multiple],select[size]{height:auto}select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.uneditable-input,.uneditable-textarea{color:#999;cursor:not-allowed;background-color:#fcfcfc;border-color:#ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);box-shadow:inset 0 1px 2px rgba(0,0,0,0.025)}.uneditable-input{overflow:hidden;white-space:nowrap}.uneditable-textarea{width:auto;height:auto}input:-moz-placeholder,textarea:-moz-placeholder{color:#999}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999}.radio,.checkbox{min-height:20px;padding-left:20px}.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px}.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px}.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle}.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px}.input-mini{width:60px}.input-small{width:90px}.input-medium{width:150px}.input-large{width:210px}.input-xlarge{width:270px}.input-xxlarge{width:530px}input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0}.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:926px}input.span11,textarea.span11,.uneditable-input.span11{width:846px}input.span10,textarea.span10,.uneditable-input.span10{width:766px}input.span9,textarea.span9,.uneditable-input.span9{width:686px}input.span8,textarea.span8,.uneditable-input.span8{width:606px}input.span7,textarea.span7,.uneditable-input.span7{width:526px}input.span6,textarea.span6,.uneditable-input.span6{width:446px}input.span5,textarea.span5,.uneditable-input.span5{width:366px}input.span4,textarea.span4,.uneditable-input.span4{width:286px}input.span3,textarea.span3,.uneditable-input.span3{width:206px}input.span2,textarea.span2,.uneditable-input.span2{width:126px}input.span1,textarea.span1,.uneditable-input.span1{width:46px}.controls-row{*zoom:1}.controls-row:before,.controls-row:after{display:table;line-height:0;content:""}.controls-row:after{clear:both}.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left}.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px}input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eee}input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent}.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853}.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853}.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48}.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48}.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847}.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847}.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847}.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad}.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad}.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3}.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7}.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1}.form-actions:before,.form-actions:after{display:table;line-height:0;content:""}.form-actions:after{clear:both}.help-block,.help-inline{color:#595959}.help-block{display:block;margin-bottom:10px}.help-inline{display:inline-block;*display:inline;padding-left:5px;vertical-align:middle;*zoom:1}.input-append,.input-prepend{display:inline-block;margin-bottom:10px;font-size:0;white-space:nowrap;vertical-align:middle}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:14px}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2}.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;background-color:#eee;border:1px solid #ccc}.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546}.input-prepend .add-on,.input-prepend .btn{margin-right:-1px}.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px}.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .btn-group:first-child{margin-left:0}input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;margin-bottom:0;vertical-align:middle;*zoom:1}.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none}.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block}.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0}.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle}.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0}.control-group{margin-bottom:10px}legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate}.form-horizontal .control-group{margin-bottom:20px;*zoom:1}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;line-height:0;content:""}.form-horizontal .control-group:after{clear:both}.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right}.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0}.form-horizontal .controls:first-child{*padding-left:180px}.form-horizontal .help-block{margin-bottom:0}.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px}.form-horizontal .form-actions{padding-left:180px}table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0}.table{width:100%;margin-bottom:20px}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #ddd}.table th{font-weight:bold}.table thead th{vertical-align:bottom}.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed th,.table-condensed td{padding:4px 5px}.table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.table-bordered th,.table-bordered td{border-left:1px solid #ddd}.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0}.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px}.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px}.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomleft:0}.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-moz-border-radius-bottomright:0}.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#f5f5f5}table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0}.table td.span1,.table th.span1{float:none;width:44px;margin-left:0}.table td.span2,.table th.span2{float:none;width:124px;margin-left:0}.table td.span3,.table th.span3{float:none;width:204px;margin-left:0}.table td.span4,.table th.span4{float:none;width:284px;margin-left:0}.table td.span5,.table th.span5{float:none;width:364px;margin-left:0}.table td.span6,.table th.span6{float:none;width:444px;margin-left:0}.table td.span7,.table th.span7{float:none;width:524px;margin-left:0}.table td.span8,.table th.span8{float:none;width:604px;margin-left:0}.table td.span9,.table th.span9{float:none;width:684px;margin-left:0}.table td.span10,.table th.span10{float:none;width:764px;margin-left:0}.table td.span11,.table th.span11{float:none;width:844px;margin-left:0}.table td.span12,.table th.span12{float:none;width:924px;margin-left:0}.table tbody tr.success>td{background-color:#dff0d8}.table tbody tr.error>td{background-color:#f2dede}.table tbody tr.warning>td{background-color:#fcf8e3}.table tbody tr.info>td{background-color:#d9edf7}.table-hover tbody tr.success:hover>td{background-color:#d0e9c6}.table-hover tbody tr.error:hover>td{background-color:#ebcccc}.table-hover tbody tr.warning:hover>td{background-color:#faf2cc}.table-hover tbody tr.info:hover>td{background-color:#c4e3f3}[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;margin-top:1px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat}.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png")}.icon-glass{background-position:0 0}.icon-music{background-position:-24px 0}.icon-search{background-position:-48px 0}.icon-envelope{background-position:-72px 0}.icon-heart{background-position:-96px 0}.icon-star{background-position:-120px 0}.icon-star-empty{background-position:-144px 0}.icon-user{background-position:-168px 0}.icon-film{background-position:-192px 0}.icon-th-large{background-position:-216px 0}.icon-th{background-position:-240px 0}.icon-th-list{background-position:-264px 0}.icon-ok{background-position:-288px 0}.icon-remove{background-position:-312px 0}.icon-zoom-in{background-position:-336px 0}.icon-zoom-out{background-position:-360px 0}.icon-off{background-position:-384px 0}.icon-signal{background-position:-408px 0}.icon-cog{background-position:-432px 0}.icon-trash{background-position:-456px 0}.icon-home{background-position:0 -24px}.icon-file{background-position:-24px -24px}.icon-time{background-position:-48px -24px}.icon-road{background-position:-72px -24px}.icon-download-alt{background-position:-96px -24px}.icon-download{background-position:-120px -24px}.icon-upload{background-position:-144px -24px}.icon-inbox{background-position:-168px -24px}.icon-play-circle{background-position:-192px -24px}.icon-repeat{background-position:-216px -24px}.icon-refresh{background-position:-240px -24px}.icon-list-alt{background-position:-264px -24px}.icon-lock{background-position:-287px -24px}.icon-flag{background-position:-312px -24px}.icon-headphones{background-position:-336px -24px}.icon-volume-off{background-position:-360px -24px}.icon-volume-down{background-position:-384px -24px}.icon-volume-up{background-position:-408px -24px}.icon-qrcode{background-position:-432px -24px}.icon-barcode{background-position:-456px -24px}.icon-tag{background-position:0 -48px}.icon-tags{background-position:-25px -48px}.icon-book{background-position:-48px -48px}.icon-bookmark{background-position:-72px -48px}.icon-print{background-position:-96px -48px}.icon-camera{background-position:-120px -48px}.icon-font{background-position:-144px -48px}.icon-bold{background-position:-167px -48px}.icon-italic{background-position:-192px -48px}.icon-text-height{background-position:-216px -48px}.icon-text-width{background-position:-240px -48px}.icon-align-left{background-position:-264px -48px}.icon-align-center{background-position:-288px -48px}.icon-align-right{background-position:-312px -48px}.icon-align-justify{background-position:-336px -48px}.icon-list{background-position:-360px -48px}.icon-indent-left{background-position:-384px -48px}.icon-indent-right{background-position:-408px -48px}.icon-facetime-video{background-position:-432px -48px}.icon-picture{background-position:-456px -48px}.icon-pencil{background-position:0 -72px}.icon-map-marker{background-position:-24px -72px}.icon-adjust{background-position:-48px -72px}.icon-tint{background-position:-72px -72px}.icon-edit{background-position:-96px -72px}.icon-share{background-position:-120px -72px}.icon-check{background-position:-144px -72px}.icon-move{background-position:-168px -72px}.icon-step-backward{background-position:-192px -72px}.icon-fast-backward{background-position:-216px -72px}.icon-backward{background-position:-240px -72px}.icon-play{background-position:-264px -72px}.icon-pause{background-position:-288px -72px}.icon-stop{background-position:-312px -72px}.icon-forward{background-position:-336px -72px}.icon-fast-forward{background-position:-360px -72px}.icon-step-forward{background-position:-384px -72px}.icon-eject{background-position:-408px -72px}.icon-chevron-left{background-position:-432px -72px}.icon-chevron-right{background-position:-456px -72px}.icon-plus-sign{background-position:0 -96px}.icon-minus-sign{background-position:-24px -96px}.icon-remove-sign{background-position:-48px -96px}.icon-ok-sign{background-position:-72px -96px}.icon-question-sign{background-position:-96px -96px}.icon-info-sign{background-position:-120px -96px}.icon-screenshot{background-position:-144px -96px}.icon-remove-circle{background-position:-168px -96px}.icon-ok-circle{background-position:-192px -96px}.icon-ban-circle{background-position:-216px -96px}.icon-arrow-left{background-position:-240px -96px}.icon-arrow-right{background-position:-264px -96px}.icon-arrow-up{background-position:-289px -96px}.icon-arrow-down{background-position:-312px -96px}.icon-share-alt{background-position:-336px -96px}.icon-resize-full{background-position:-360px -96px}.icon-resize-small{background-position:-384px -96px}.icon-plus{background-position:-408px -96px}.icon-minus{background-position:-433px -96px}.icon-asterisk{background-position:-456px -96px}.icon-exclamation-sign{background-position:0 -120px}.icon-gift{background-position:-24px -120px}.icon-leaf{background-position:-48px -120px}.icon-fire{background-position:-72px -120px}.icon-eye-open{background-position:-96px -120px}.icon-eye-close{background-position:-120px -120px}.icon-warning-sign{background-position:-144px -120px}.icon-plane{background-position:-168px -120px}.icon-calendar{background-position:-192px -120px}.icon-random{width:16px;background-position:-216px -120px}.icon-comment{background-position:-240px -120px}.icon-magnet{background-position:-264px -120px}.icon-chevron-up{background-position:-288px -120px}.icon-chevron-down{background-position:-313px -119px}.icon-retweet{background-position:-336px -120px}.icon-shopping-cart{background-position:-360px -120px}.icon-folder-close{width:16px;background-position:-384px -120px}.icon-folder-open{width:16px;background-position:-408px -120px}.icon-resize-vertical{background-position:-432px -119px}.icon-resize-horizontal{background-position:-456px -118px}.icon-hdd{background-position:0 -144px}.icon-bullhorn{background-position:-24px -144px}.icon-bell{background-position:-48px -144px}.icon-certificate{background-position:-72px -144px}.icon-thumbs-up{background-position:-96px -144px}.icon-thumbs-down{background-position:-120px -144px}.icon-hand-right{background-position:-144px -144px}.icon-hand-left{background-position:-168px -144px}.icon-hand-up{background-position:-192px -144px}.icon-hand-down{background-position:-216px -144px}.icon-circle-arrow-right{background-position:-240px -144px}.icon-circle-arrow-left{background-position:-264px -144px}.icon-circle-arrow-up{background-position:-288px -144px}.icon-circle-arrow-down{background-position:-312px -144px}.icon-globe{background-position:-336px -144px}.icon-wrench{background-position:-360px -144px}.icon-tasks{background-position:-384px -144px}.icon-filter{background-position:-408px -144px}.icon-briefcase{background-position:-432px -144px}.icon-fullscreen{background-position:-456px -144px}.dropup,.dropdown{position:relative}.dropdown-toggle{*margin-bottom:-3px}.dropdown-toggle:active,.open .dropdown-toggle{outline:0}.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown .caret{margin-top:8px;margin-left:2px}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open{*z-index:1000}.open>.dropdown-menu{display:block}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.dropdown-submenu{position:relative}.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}.dropdown-submenu:hover>.dropdown-menu{display:block}.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0}.dropdown-submenu>a:after{display:block;float:right;width:0;height:0;margin-top:5px;margin-right:-10px;border-color:transparent;border-left-color:#ccc;border-style:solid;border-width:5px 0 5px 5px;content:" "}.dropdown-submenu:hover>a:after{border-left-color:#fff}.dropdown-submenu.pull-left{float:none}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.dropdown .dropdown-menu .nav-header{padding-right:20px;padding-left:20px}.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fade{opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-moz-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.collapse.in{height:auto}.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.4;filter:alpha(opacity=40)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.btn{display:inline-block;*display:inline;padding:4px 12px;margin-bottom:0;*margin-left:.3em;font-size:14px;line-height:20px;color:#333;text-align:center;text-shadow:0 1px 1px rgba(255,255,255,0.75);vertical-align:middle;cursor:pointer;background-color:#f5f5f5;*background-color:#e6e6e6;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;border:1px solid #ccc;*border:0;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);*zoom:1;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;*background-color:#04c;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #0044cc #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;*background-color:#f89406;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;*background-color:#bd362f;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;*background-color:#51a351;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;*background-color:#2f96b4;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;*background-color:#222;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;border-color:#222 #222222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{color:#08c;cursor:pointer;border-color:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.btn-group{position:relative;display:inline-block;*display:inline;*margin-left:.3em;font-size:0;white-space:nowrap;vertical-align:middle;*zoom:1}.btn-group:first-child{*margin-left:0}.btn-group+.btn-group{margin-left:5px}.btn-toolbar{margin-top:10px;margin-bottom:10px;font-size:0}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px}.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group>.btn+.btn{margin-left:-1px}.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px}.btn-group>.btn-mini{font-size:10.5px}.btn-group>.btn-small{font-size:11.9px}.btn-group>.btn-large{font-size:17.5px}.btn-group>.btn:first-child{margin-left:0;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{*padding-top:5px;padding-right:8px;*padding-bottom:5px;padding-left:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn-group>.btn-mini+.dropdown-toggle{*padding-top:2px;padding-right:5px;*padding-bottom:2px;padding-left:5px}.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px}.btn-group>.btn-large+.dropdown-toggle{*padding-top:7px;padding-right:12px;*padding-bottom:7px;padding-left:12px}.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6}.btn-group.open .btn-primary.dropdown-toggle{background-color:#04c}.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406}.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f}.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351}.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4}.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222}.btn .caret{margin-top:8px;margin-left:0}.btn-large .caret{margin-top:6px}.btn-large .caret{border-top-width:5px;border-right-width:5px;border-left-width:5px}.btn-mini .caret,.btn-small .caret{margin-top:8px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#fff;border-bottom-color:#fff}.btn-group-vertical{display:inline-block;*display:inline;*zoom:1}.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group-vertical>.btn+.btn{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0}.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255,255,255,0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.alert,.alert h4{color:#c09853}.alert h4{margin:0}.alert .close{position:relative;top:-2px;right:-21px;line-height:20px}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success h4{color:#468847}.alert-danger,.alert-error{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger h4,.alert-error h4{color:#b94a48}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info h4{color:#3a87ad}.alert-block{padding-top:14px;padding-bottom:14px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.nav{margin-bottom:20px;margin-left:0;list-style:none}.nav>li>a{display:block}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li>a>img{max-width:none}.nav>.pull-right{float:right}.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999;text-shadow:0 1px 0 rgba(255,255,255,0.5);text-transform:uppercase}.nav li+.nav-header{margin-top:9px}.nav-list{padding-right:15px;padding-left:15px;margin-bottom:0}.nav-list>li>a,.nav-list .nav-header{margin-right:-15px;margin-left:-15px;text-shadow:0 1px 0 rgba(255,255,255,0.5)}.nav-list>li>a{padding:3px 15px}.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.2);background-color:#08c}.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px}.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.nav-tabs,.nav-pills{*zoom:1}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;line-height:0;content:""}.nav-tabs:after,.nav-pills:after{clear:both}.nav-tabs>li,.nav-pills>li{float:left}.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{margin-bottom:-1px}.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eee #eeeeee #ddd}.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#fff;background-color:#08c}.nav-stacked>li{float:none}.nav-stacked>li>a{margin-right:0}.nav-tabs.nav-stacked{border-bottom:0}.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-topleft:4px}.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomright:4px;-moz-border-radius-bottomleft:4px}.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{z-index:2;border-color:#ddd}.nav-pills.nav-stacked>li>a{margin-bottom:3px}.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px}.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.nav .dropdown-toggle .caret{margin-top:6px;border-top-color:#08c;border-bottom-color:#08c}.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580}.nav-tabs .dropdown-toggle .caret{margin-top:8px}.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer}.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#fff;background-color:#999;border-color:#999}.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#fff;border-bottom-color:#fff;opacity:1;filter:alpha(opacity=100)}.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#999}.tabbable{*zoom:1}.tabbable:before,.tabbable:after{display:table;line-height:0;content:""}.tabbable:after{clear:both}.tab-content{overflow:auto}.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.tabs-below>.nav-tabs{border-top:1px solid #ddd}.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-top-color:#ddd;border-bottom-color:transparent}.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd}.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none}.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px}.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd}.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eee #dddddd #eee #eeeeee}.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#fff}.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd}.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eee #eeeeee #eee #dddddd}.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#fff}.nav>.disabled>a{color:#999}.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent}.navbar{*position:relative;*z-index:2;margin-bottom:20px;overflow:visible}.navbar-inner{min-height:40px;padding-right:20px;padding-left:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top,#fff,#f2f2f2);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#f2f2f2));background-image:-webkit-linear-gradient(top,#fff,#f2f2f2);background-image:-o-linear-gradient(top,#fff,#f2f2f2);background-image:linear-gradient(to bottom,#fff,#f2f2f2);background-repeat:repeat-x;border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff2f2f2',GradientType=0);*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.navbar-inner:before,.navbar-inner:after{display:table;line-height:0;content:""}.navbar-inner:after{clear:both}.navbar .container{width:auto}.nav-collapse.collapse{height:auto;overflow:visible}.navbar .brand{display:block;float:left;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777;text-shadow:0 1px 0 #fff}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none}.navbar-text{margin-bottom:0;line-height:40px;color:#777}.navbar-link{color:#777}.navbar-link:hover,.navbar-link:focus{color:#333}.navbar .divider-vertical{height:40px;margin:0 9px;border-right:1px solid #fff;border-left:1px solid #f2f2f2}.navbar .btn,.navbar .btn-group{margin-top:5px}.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0}.navbar-form{margin-bottom:0;*zoom:1}.navbar-form:before,.navbar-form:after{display:table;line-height:0;content:""}.navbar-form:after{clear:both}.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px}.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0}.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px}.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0}.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0}.navbar-search .search-query{padding:4px 14px;margin-bottom:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.navbar-static-top{position:static;margin-bottom:0}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px}.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-right:0;padding-left:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.navbar-fixed-top{top:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.navbar-fixed-bottom{bottom:0}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,0.1);box-shadow:0 -1px 10px rgba(0,0,0,0.1)}.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0}.navbar .nav.pull-right{float:right;margin-right:0}.navbar .nav>li{float:left}.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777;text-decoration:none;text-shadow:0 1px 0 #fff}.navbar .nav .dropdown-toggle .caret{margin-top:8px}.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{color:#333;text-decoration:none;background-color:transparent}.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);-moz-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);box-shadow:inset 0 3px 8px rgba(0,0,0,0.125)}.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-right:5px;margin-left:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#ededed;*background-color:#e5e5e5;background-image:-moz-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-o-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:linear-gradient(to bottom,#f2f2f2,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffe5e5e5',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075)}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#fff;background-color:#e5e5e5;*background-color:#d9d9d9}.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#ccc \9}.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25)}.btn-navbar .icon-bar+.icon-bar{margin-top:3px}.navbar .nav>li>.dropdown-menu:before{position:absolute;top:-7px;left:9px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.navbar .nav>li>.dropdown-menu:after{position:absolute;top:-6px;left:10px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.navbar-fixed-bottom .nav>li>.dropdown-menu:before{top:auto;bottom:-7px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.navbar-fixed-bottom .nav>li>.dropdown-menu:after{top:auto;bottom:-6px;border-top:6px solid #fff;border-bottom:0}.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{color:#555;background-color:#e5e5e5}.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777;border-bottom-color:#777}.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{right:12px;left:auto}.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{right:13px;left:auto}.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{right:100%;left:auto;margin-right:-1px;margin-left:0;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top,#222,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#111));background-image:-webkit-linear-gradient(top,#222,#111);background-image:-o-linear-gradient(top,#222,#111);background-image:linear-gradient(to bottom,#222,#111);background-repeat:repeat-x;border-color:#252525;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff111111',GradientType=0)}.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999;text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#fff}.navbar-inverse .brand{color:#999}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#fff;background-color:#111}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#fff}.navbar-inverse .divider-vertical{border-right-color:#222;border-left-color:#111}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{color:#fff;background-color:#111}.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-search .search-query{color:#fff;background-color:#515151;border-color:#111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333;text-shadow:0 1px 0 #fff;background-color:#fff;border:0;outline:0;-webkit-box-shadow:0 0 3px rgba(0,0,0,0.15);-moz-box-shadow:0 0 3px rgba(0,0,0,0.15);box-shadow:0 0 3px rgba(0,0,0,0.15)}.navbar-inverse .btn-navbar{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e0e0e;*background-color:#040404;background-image:-moz-linear-gradient(top,#151515,#040404);background-image:-webkit-gradient(linear,0 0,0 100%,from(#151515),to(#040404));background-image:-webkit-linear-gradient(top,#151515,#040404);background-image:-o-linear-gradient(top,#151515,#040404);background-image:linear-gradient(to bottom,#151515,#040404);background-repeat:repeat-x;border-color:#040404 #040404 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515',endColorstr='#ff040404',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#fff;background-color:#040404;*background-color:#000}.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000 \9}.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.breadcrumb>li{display:inline-block;*display:inline;text-shadow:0 1px 0 #fff;*zoom:1}.breadcrumb>li>.divider{padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{margin:20px 0}.pagination ul{display:inline-block;*display:inline;margin-bottom:0;margin-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.pagination ul>li{display:inline}.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5}.pagination ul>.active>a,.pagination ul>.active>span{color:#999;cursor:default}.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#999;cursor:default;background-color:transparent}.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.pagination-centered{text-align:center}.pagination-right{text-align:right}.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:17.5px}.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px}.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px}.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.9px}.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:10.5px}.pager{margin:20px 0;text-align:center;list-style:none;*zoom:1}.pager:before,.pager:after{display:table;line-height:0;content:""}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:default;background-color:#fff}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop,.modal-backdrop.fade.in{opacity:.8;filter:alpha(opacity=80)}.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;outline:0;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box}.modal.fade{top:-25%;-webkit-transition:opacity .3s linear,top .3s ease-out;-moz-transition:opacity .3s linear,top .3s ease-out;-o-transition:opacity .3s linear,top .3s ease-out;transition:opacity .3s linear,top .3s ease-out}.modal.fade.in{top:10%}.modal-header{padding:9px 15px;border-bottom:1px solid #eee}.modal-header .close{margin-top:2px}.modal-header h3{margin:0;line-height:30px}.modal-body{position:relative;max-height:400px;padding:15px;overflow-y:auto}.modal-form{margin-bottom:0}.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;*zoom:1;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.modal-footer:before,.modal-footer:after{display:table;line-height:0;content:""}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.tooltip{position:absolute;z-index:1030;display:block;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.8;filter:alpha(opacity=80)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.popover-title:empty{display:none}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0}.thumbnails{margin-left:-20px;list-style:none;*zoom:1}.thumbnails:before,.thumbnails:after{display:table;line-height:0;content:""}.thumbnails:after{clear:both}.row-fluid .thumbnails{margin-left:0}.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px}.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.055);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.055);box-shadow:0 1px 3px rgba(0,0,0,0.055);-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}a.thumbnail:hover,a.thumbnail:focus{border-color:#08c;-webkit-box-shadow:0 1px 4px rgba(0,105,214,0.25);-moz-box-shadow:0 1px 4px rgba(0,105,214,0.25);box-shadow:0 1px 4px rgba(0,105,214,0.25)}.thumbnail>img{display:block;max-width:100%;margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#555}.media,.media-body{overflow:hidden;*overflow:visible;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{margin-left:0;list-style:none}.label,.badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);white-space:nowrap;vertical-align:baseline;background-color:#999}.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.badge{padding-right:9px;padding-left:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px}.label:empty,.badge:empty{display:none}a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.label-important,.badge-important{background-color:#b94a48}.label-important[href],.badge-important[href]{background-color:#953b39}.label-warning,.badge-warning{background-color:#f89406}.label-warning[href],.badge-warning[href]{background-color:#c67605}.label-success,.badge-success{background-color:#468847}.label-success[href],.badge-success[href]{background-color:#356635}.label-info,.badge-info{background-color:#3a87ad}.label-info[href],.badge-info[href]{background-color:#2d6987}.label-inverse,.badge-inverse{background-color:#333}.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a}.btn .label,.btn .badge{position:relative;top:-1px}.btn-mini .label,.btn-mini .badge{top:0}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f7f7f7;background-image:-moz-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f5f5f5),to(#f9f9f9));background-image:-webkit-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-o-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);background-repeat:repeat-x;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#fff9f9f9',GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress .bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top,#149bdf,#0480be);background-image:-webkit-gradient(linear,0 0,0 100%,from(#149bdf),to(#0480be));background-image:-webkit-linear-gradient(top,#149bdf,#0480be);background-image:-o-linear-gradient(top,#149bdf,#0480be);background-image:linear-gradient(to bottom,#149bdf,#0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf',endColorstr='#ff0480be',GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width .6s ease;-moz-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15)}.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px}.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top,#ee5f5b,#c43c35);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#c43c35));background-image:-webkit-linear-gradient(top,#ee5f5b,#c43c35);background-image:-o-linear-gradient(top,#ee5f5b,#c43c35);background-image:linear-gradient(to bottom,#ee5f5b,#c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffc43c35',GradientType=0)}.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top,#62c462,#57a957);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#57a957));background-image:-webkit-linear-gradient(top,#62c462,#57a957);background-image:-o-linear-gradient(top,#62c462,#57a957);background-image:linear-gradient(to bottom,#62c462,#57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff57a957',GradientType=0)}.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top,#5bc0de,#339bb9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#339bb9));background-image:-webkit-linear-gradient(top,#5bc0de,#339bb9);background-image:-o-linear-gradient(top,#5bc0de,#339bb9);background-image:linear-gradient(to bottom,#5bc0de,#339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff339bb9',GradientType=0)}.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0)}.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px}.accordion-toggle{cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative;margin-bottom:20px;line-height:1}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-moz-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#fff;text-align:center;background:#222;border:3px solid #fff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:.5;filter:alpha(opacity=50)}.carousel-control.right{right:15px;left:auto}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255,255,255,0.25);border-radius:5px}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:0;bottom:0;left:0;padding:15px;background:#333;background:rgba(0,0,0,0.75)}.carousel-caption h4,.carousel-caption p{line-height:20px;color:#fff}.carousel-caption h4{margin:0 0 5px}.carousel-caption p{margin-bottom:0}.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;letter-spacing:-1px;color:inherit}.hero-unit li{line-height:30px}.pull-right{float:right}.pull-left{float:left}.hide{display:none}.show{display:block}.invisible{visibility:hidden}.affix{position:fixed}.clear{clear:both;visibility:hidden}.clear hr{display:none}.section p,.section p,.section dt,.section dt{margin-right:7px;margin-left:7px}#ohloh{margin-bottom:10px}#poweredBy{text-align:center}a.externalLink{padding-right:18px}a.newWindow{background:url('../images/window-new.png') right center no-repeat;padding-right:18px}a.externalLink[href^=http]{background:url('../images/internet-web-browser.png') right center no-repeat;padding-right:18px}a.externalLink[href$=".asc"]{background:url('../images/accessories-text-editor.png') right center no-repeat;padding-right:18px}a.externalLink[href$=".jpg"],a.externalLink[href$=".jpeg"],a.externalLink[href$=".gif"],a.externalLink[href$=".png"]{background:url('../images/image-x-generic.png') right center no-repeat;padding-right:18px}a.externalLink[href$=".tar.gz"],a.externalLink[href$=".zip"]{background:url('../images/package-x-generic.png') right center no-repeat;padding-right:18px}a.externalLink[href$=".md5"],a.externalLink[href$=".sha1"]{background:url('../images/document-properties.png') right center no-repeat;padding-right:18px}a.externalLink[href^=https]{background:url('../images/application-certificate.png') right center no-repeat;padding-right:18px}a.externalLink[href^=file]{background:url('../images/drive-harddisk.png') right center no-repeat;padding-right:18px}a.externalLink[href^=ftp]{background:url('../images/network-server.png') right center no-repeat;padding-right:18px}a.externalLink[href^=mailto]{background:url('../images/contact-new.png') right center no-repeat;padding-right:18px}li.none{list-style:none}.search-query{background-image:url(https://cse.google.com/cse/images/google_custom_search_watermark.gif);background-attachment:initial;background-origin:initial;background-clip:initial;background-color:#fff;background-position:0 50%;background-repeat:no-repeat no-repeat;width:95%}body.topBarEnabled{padding-top:60px}body.topBarDisabled{padding-top:20px}.builtBy{display:block}img.builtBy{margin:10px auto}#search-form{margin-left:9px;margin-right:9px}.hero-unit h2{font-size:60px}tt{padding:0 3px 2px;font-family:Monaco,Andale Mono,Courier New,monospace;font-size:.9em;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;background-color:#fee9cc;color:rgba(0,0,0,0.75);padding:1px 3px}li{color:#404040}table.zebra-striped{background-color:#FFF}.footer{background-color:#EEE}.sidebar-nav{padding-left:0;padding-right:0}.sidebar-nav .icon-chevron-right,.sidebar-nav .icon-chevron-down{margin-top:2px;margin-right:-6px;float:right;opacity:.25}li.pull-right{margin-left:3px;margin-right:3px}.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0;padding-left:15px}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/print.css b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/print.css new file mode 100644 index 00000000..46c5e810 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/print.css @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +/* $Id: print.css 1201871 2011-11-14 20:18:24Z simonetripodi $ */ + +#banner, #footer, #leftcol, #breadcrumbs, .docs #toc, .docs .courtesylinks, #leftColumn, #navColumn {display: none !important;} +#bodyColumn, body.docs div.docs {margin: 0 !important;border: none !important} diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/site.css b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/site.css new file mode 100644 index 00000000..055e7e28 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/css/site.css @@ -0,0 +1 @@ +/* You can override this file with your own styles */ \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.eot b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.eot new file mode 100644 index 00000000..af587a81 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.eot differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.svg b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.svg new file mode 100644 index 00000000..c8f06d9a --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.svg @@ -0,0 +1,229 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.ttf b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.ttf new file mode 100644 index 00000000..8681f1ec Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.ttf differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.woff b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.woff new file mode 100644 index 00000000..1e69f489 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/fonts/glyphicons-halflings-regular.woff differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/generateStubs-mojo.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/generateStubs-mojo.html new file mode 100644 index 00000000..ef1d5a7a --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/generateStubs-mojo.html @@ -0,0 +1,445 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – spring-cloud-contract:generateStubs + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ + + +
+

spring-cloud-contract:generateStubs

+ +

Full name:

+ +

org.springframework.cloud:spring-cloud-contract-maven-plugin:2.1.2.RELEASE:generateStubs

+ +

Description:

+ +
Picks the converted .json files and creates a jar. Requires convert +to be executed first.
+ +

Attributes:

+ +
    + +
  • Requires a Maven project to be executed.
  • + +
  • Binds by default to the lifecycle phase: package.
  • +
+ +
+

Optional Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeSinceDescription
classifierString-(no description)
Default value is: stubs.
excludedFilesString[]-Patterns that should not be taken into account for processing.
jarSkipboolean-Set this to "true" to bypass only JAR creation.
Default value is: false.
User property is: spring.cloud.contract.verifier.jar.skip.
outputDirectoryFile-(no description)
Default value is: ${project.build.directory}/stubs.
User property is: stubsDirectory.
skipboolean-Set this to "true" to bypass the whole Verifier execution.
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
+
+ +
+

Parameter Details

+ +

classifier:

+ +
(no description)
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • Default: stubs
  • +

+

excludedFiles:

+ +
Patterns that should not be taken into account for processing.
+ +
    + +
  • Type: java.lang.String[]
  • + +
  • Required: No
  • +

+

jarSkip:

+ +
Set this to "true" to bypass only JAR creation.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.jar.skip
  • + +
  • Default: false
  • +

+

outputDirectory:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • User Property: stubsDirectory
  • + +
  • Default: ${project.build.directory}/stubs
  • +

+

skip:

+ +
Set this to "true" to bypass the whole Verifier execution.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.skip
  • + +
  • Default: false
  • +
+
+
+ + +
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/generateTests-mojo.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/generateTests-mojo.html new file mode 100644 index 00000000..84efe48f --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/generateTests-mojo.html @@ -0,0 +1,1098 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – spring-cloud-contract:generateTests + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ + + +
+

spring-cloud-contract:generateTests

+ +

Full name:

+ +

org.springframework.cloud:spring-cloud-contract-maven-plugin:2.1.2.RELEASE:generateTests

+ +

Description:

+ +
From the provided directory with contracts generates the acceptance +tests on the producer side.
+ +

Attributes:

+ +
    + +
  • Requires a Maven project to be executed.
  • + +
  • Requires dependency resolution of artifacts in scope: test.
  • + +
  • Binds by default to the lifecycle phase: generate-test-sources.
  • +
+ +
+

Optional Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeSinceDescription
assertJsonSizeboolean-Incubating feature. You can check the size of JSON arrays. If not +turned on explicitly will be disabled.
Default value is: false.
User property is: spring.cloud.contract.verifier.assert.size.
baseClassForTestsString-(no description)
baseClassMappingsList-A way to override any base class mappings. The keys are regular +expressions on the package name of the contract and the values FQN +to a base class for that given expression. Example of a mapping +.*.com.example.v1..* -> +com.example.SomeBaseClass When a contract's package +matches the provided regular expression then extending class will +be the one provided in the map - in this case +com.example.SomeBaseClass.
User property is: baseClassMappings.
basePackageForTestsString-(no description)
contractDependencyDependency-(no description)
User property is: contractDependency.
contractsDirectoryFile-(no description)
Default value is: ${project.basedir}/src/test/resources/contracts.
User property is: spring.cloud.contract.verifier.contractsDirectory.
contractsModeStubRunnerProperties$StubsMode-Picks the mode in which stubs will be found and registered.
Default value is: CLASSPATH.
User property is: contractsMode.
contractsPathString-The path in the JAR with all the contracts where contracts for this +particular service lay. If not provided will be resolved to +groupid/artifactid. Example: If groupid +is com.example and artifactid is +service then the resolved path will be +/com/example/artifactid
User property is: contractsPath.
contractsPropertiesMap-Map of properties that can be passed to custom +StubDownloaderBuilder.
User property is: contractsProperties.
contractsRepositoryPasswordString-The password to be used to connect to the repo with contracts.
User property is: contractsRepositoryPassword.
contractsRepositoryProxyHostString-The proxy host to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyHost.
contractsRepositoryProxyPortInteger-The proxy port to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyPort.
contractsRepositoryUrlString-The URL from which a contracts should get downloaded. If not +provided but artifactid / coordinates notation was provided then +the current Maven's build repositories will be taken into +consideration.
User property is: contractsRepositoryUrl.
contractsRepositoryUsernameString-The user name to be used to connect to the repo with contracts.
User property is: contractsRepositoryUsername.
contractsSnapshotCheckSkipboolean-Deprecated. - with 2.1.0 this option is redundant
Default value is: false.
User property is: contractsSnapshotCheckSkip.
deleteStubsAfterTestboolean-If set to false will NOT delete stubs from a temporary +folder after running tests.
Default value is: true.
User property is: deleteStubsAfterTest.
excludedFilesList-Patterns that should not be taken into account for processing.
generatedTestResourcesDirFile-(no description)
Default value is: ${project.build.directory}/generated-test-resources/contracts.
generatedTestSourcesDirFile-(no description)
Default value is: ${project.build.directory}/generated-test-sources/contracts.
ignoredFilesList-Patterns for which Spring Cloud Contract Verifier should generate +@Ignored tests.
importsString[]-Imports that should be added to generated tests.
includedFilesList-Patterns that should be taken into account for processing.
User property is: includedFiles.
mavenTestSkipboolean-(no description)
Default value is: false.
User property is: maven.test.skip.
nameSuffixForTestsString-(no description)
packageWithBaseClassesString-A package that contains all the base clases for generated tests. If +your contract resides in a location +src/test/resources/contracts/com/example/v1/ and you +provide the packageWithBaseClasses value to +com.example.contracts.base then we will search for a +test source file that will have the package +com.example.contracts.base and name +ExampleV1Base. As you can see it will take the two +last folders to and attach Base to its name.
User property is: packageWithBaseClasses.
ruleClassForTestsString-(no description)
skipboolean-(no description)
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
skipTestsboolean-(no description)
Default value is: false.
User property is: skipTests.
staticImportsString[]-Static imports that should be added to generated tests.
testFrameworkTestFramework-(no description)
Default value is: JUNIT.
testModeTestMode-(no description)
Default value is: MOCKMVC.
+
+ +
+

Parameter Details

+ +

assertJsonSize:

+ +
Incubating feature. You can check the size of JSON arrays. If not +turned on explicitly will be disabled.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.assert.size
  • + +
  • Default: false
  • +

+

baseClassForTests:

+ +
(no description)
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • +

+

baseClassMappings:

+ +
A way to override any base class mappings. The keys are regular +expressions on the package name of the contract and the values FQN +to a base class for that given expression. Example of a mapping +.*.com.example.v1..* -> +com.example.SomeBaseClass When a contract's package +matches the provided regular expression then extending class will +be the one provided in the map - in this case +com.example.SomeBaseClass.
+ +
    + +
  • Type: java.util.List
  • + +
  • Required: No
  • + +
  • User Property: baseClassMappings
  • +

+

basePackageForTests:

+ +
(no description)
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • +

+

contractDependency:

+ +
(no description)
+ +
    + +
  • Type: org.apache.maven.model.Dependency
  • + +
  • Required: No
  • + +
  • User Property: contractDependency
  • +

+

contractsDirectory:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.contractsDirectory
  • + +
  • Default: ${project.basedir}/src/test/resources/contracts
  • +

+

contractsMode:

+ +
Picks the mode in which stubs will be found and registered.
+ +
    + +
  • Type: org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties$StubsMode
  • + +
  • Required: No
  • + +
  • User Property: contractsMode
  • + +
  • Default: CLASSPATH
  • +

+

contractsPath:

+ +
The path in the JAR with all the contracts where contracts for this +particular service lay. If not provided will be resolved to +groupid/artifactid. Example: If groupid +is com.example and artifactid is +service then the resolved path will be +/com/example/artifactid
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsPath
  • +

+

contractsProperties:

+ +
Map of properties that can be passed to custom +StubDownloaderBuilder.
+ +
    + +
  • Type: java.util.Map
  • + +
  • Required: No
  • + +
  • User Property: contractsProperties
  • +

+

contractsRepositoryPassword:

+ +
The password to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryPassword
  • +

+

contractsRepositoryProxyHost:

+ +
The proxy host to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryProxyHost
  • +

+

contractsRepositoryProxyPort:

+ +
The proxy port to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.Integer
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryProxyPort
  • +

+

contractsRepositoryUrl:

+ +
The URL from which a contracts should get downloaded. If not +provided but artifactid / coordinates notation was provided then +the current Maven's build repositories will be taken into +consideration.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryUrl
  • +

+

contractsRepositoryUsername:

+ +
The user name to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryUsername
  • +

+

contractsSnapshotCheckSkip:

+ +
Deprecated. - with 2.1.0 this option is redundant
+ +
If true then will not assert whether a stub / contract +JAR was downloaded from local or remote location.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: contractsSnapshotCheckSkip
  • + +
  • Default: false
  • +

+

deleteStubsAfterTest:

+ +
If set to false will NOT delete stubs from a temporary +folder after running tests.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: deleteStubsAfterTest
  • + +
  • Default: true
  • +

+

excludedFiles:

+ +
Patterns that should not be taken into account for processing.
+ +
    + +
  • Type: java.util.List
  • + +
  • Required: No
  • +

+

generatedTestResourcesDir:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • Default: ${project.build.directory}/generated-test-resources/contracts
  • +

+

generatedTestSourcesDir:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • Default: ${project.build.directory}/generated-test-sources/contracts
  • +

+

ignoredFiles:

+ +
Patterns for which Spring Cloud Contract Verifier should generate +@Ignored tests.
+ +
    + +
  • Type: java.util.List
  • + +
  • Required: No
  • +

+

imports:

+ +
Imports that should be added to generated tests.
+ +
    + +
  • Type: java.lang.String[]
  • + +
  • Required: No
  • +

+

includedFiles:

+ +
Patterns that should be taken into account for processing.
+ +
    + +
  • Type: java.util.List
  • + +
  • Required: No
  • + +
  • User Property: includedFiles
  • +

+

mavenTestSkip:

+ +
(no description)
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: maven.test.skip
  • + +
  • Default: false
  • +

+

nameSuffixForTests:

+ +
(no description)
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • +

+

packageWithBaseClasses:

+ +
A package that contains all the base clases for generated tests. If +your contract resides in a location +src/test/resources/contracts/com/example/v1/ and you +provide the packageWithBaseClasses value to +com.example.contracts.base then we will search for a +test source file that will have the package +com.example.contracts.base and name +ExampleV1Base. As you can see it will take the two +last folders to and attach Base to its name.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: packageWithBaseClasses
  • +

+

ruleClassForTests:

+ +
(no description)
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • +

+

skip:

+ +
(no description)
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.skip
  • + +
  • Default: false
  • +

+

skipTests:

+ +
(no description)
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: skipTests
  • + +
  • Default: false
  • +

+

staticImports:

+ +
Static imports that should be added to generated tests.
+ +
    + +
  • Type: java.lang.String[]
  • + +
  • Required: No
  • +

+

testFramework:

+ +
(no description)
+ +
    + +
  • Type: org.springframework.cloud.contract.verifier.config.TestFramework
  • + +
  • Required: No
  • + +
  • Default: JUNIT
  • +

+

testMode:

+ +
(no description)
+ +
    + +
  • Type: org.springframework.cloud.contract.verifier.config.TestMode
  • + +
  • Required: No
  • + +
  • Default: MOCKMVC
  • +
+
+
+ + +
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/help-mojo.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/help-mojo.html new file mode 100644 index 00000000..8d638504 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/help-mojo.html @@ -0,0 +1,423 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – spring-cloud-contract:help + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ + + +
+

spring-cloud-contract:help

+ +

Full name:

+ +

org.springframework.cloud:spring-cloud-contract-maven-plugin:2.1.2.RELEASE:help

+ +

Description:

+ +
Display help information on +spring-cloud-contract-maven-plugin.
+Call mvn spring-cloud-contract:help -Ddetail=true +-Dgoal=<goal-name> to display parameter details.
+ +

Attributes:

+ +
+

Optional Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeSinceDescription
detailboolean-If true, display all settable properties for each +goal.
Default value is: false.
User property is: detail.
goalString-The name of the goal for which to show help. If unspecified, all +goals will be displayed.
User property is: goal.
indentSizeint-The number of spaces per indentation level, should be positive.
Default value is: 2.
User property is: indentSize.
lineLengthint-The maximum length of a display line, should be positive.
Default value is: 80.
User property is: lineLength.
+
+ +
+

Parameter Details

+ +

detail:

+ +
If true, display all settable properties for each +goal.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: detail
  • + +
  • Default: false
  • +

+

goal:

+ +
The name of the goal for which to show help. If unspecified, all +goals will be displayed.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: goal
  • +

+

indentSize:

+ +
The number of spaces per indentation level, should be positive.
+ +
    + +
  • Type: int
  • + +
  • Required: No
  • + +
  • User Property: indentSize
  • + +
  • Default: 2
  • +

+

lineLength:

+ +
The maximum length of a display line, should be positive.
+ +
    + +
  • Type: int
  • + +
  • Required: No
  • + +
  • User Property: lineLength
  • + +
  • Default: 80
  • +
+
+
+ + +
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/accessories-text-editor.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/accessories-text-editor.png new file mode 100644 index 00000000..abc3366e Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/accessories-text-editor.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/add.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/add.gif new file mode 100644 index 00000000..1cb3dbf9 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/add.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/apache-maven-project-2.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/apache-maven-project-2.png new file mode 100644 index 00000000..a44db6ed Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/apache-maven-project-2.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/application-certificate.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/application-certificate.png new file mode 100644 index 00000000..cc6aff61 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/application-certificate.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/contact-new.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/contact-new.png new file mode 100644 index 00000000..ebc4316d Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/contact-new.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/document-properties.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/document-properties.png new file mode 100644 index 00000000..34c2409a Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/document-properties.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/drive-harddisk.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/drive-harddisk.png new file mode 100644 index 00000000..d7ce475f Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/drive-harddisk.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/fix.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/fix.gif new file mode 100644 index 00000000..b7eb3dc4 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/fix.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_error_sml.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_error_sml.gif new file mode 100644 index 00000000..12e9a01a Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_error_sml.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_help_sml.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_help_sml.gif new file mode 100644 index 00000000..aaf20e6e Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_help_sml.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_info_sml.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_info_sml.gif new file mode 100644 index 00000000..b7763267 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_info_sml.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_success_sml.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_success_sml.gif new file mode 100644 index 00000000..0a195279 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_success_sml.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_warning_sml.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_warning_sml.gif new file mode 100644 index 00000000..ac6ad6ad Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/icon_warning_sml.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/image-x-generic.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/image-x-generic.png new file mode 100644 index 00000000..ab49efb3 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/image-x-generic.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/internet-web-browser.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/internet-web-browser.png new file mode 100644 index 00000000..307d6aca Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/internet-web-browser.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/build-by-maven-black.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/build-by-maven-black.png new file mode 100644 index 00000000..919fd0f6 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/build-by-maven-black.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/build-by-maven-white.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/build-by-maven-white.png new file mode 100644 index 00000000..7d44c9c2 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/build-by-maven-white.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/maven-feather.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/maven-feather.png new file mode 100644 index 00000000..b5ada836 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/logos/maven-feather.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/network-server.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/network-server.png new file mode 100644 index 00000000..1d12e193 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/network-server.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/package-x-generic.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/package-x-generic.png new file mode 100644 index 00000000..8b7e9e67 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/package-x-generic.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/pre-release.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/pre-release.png new file mode 100644 index 00000000..d448e850 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/pre-release.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/retired.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/retired.png new file mode 100644 index 00000000..f89f6a29 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/retired.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/sandbox.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/sandbox.png new file mode 100644 index 00000000..f88b3626 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/profiles/sandbox.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/remove.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/remove.gif new file mode 100644 index 00000000..fc65631c Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/remove.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/rss.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/rss.png new file mode 100644 index 00000000..a9850ee2 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/rss.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/update.gif b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/update.gif new file mode 100644 index 00000000..b2a6d0bf Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/update.gif differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/window-new.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/window-new.png new file mode 100644 index 00000000..0e12ef95 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/images/window-new.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/img/glyphicons-halflings-white.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/img/glyphicons-halflings-white.png new file mode 100644 index 00000000..3bf6484a Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/img/glyphicons-halflings-white.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/img/glyphicons-halflings.png b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/img/glyphicons-halflings.png new file mode 100644 index 00000000..a9969993 Binary files /dev/null and b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/img/glyphicons-halflings.png differ diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/index.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/index.html new file mode 100644 index 00000000..1b734a4f --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/index.html @@ -0,0 +1,392 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +

Spring Cloud Contract Maven Plugin

+
+
+
+

Just to make long story short - Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications.

+
+
+
    +
  • +

    Stubs mappings to be used by WireMock when doing integration testing on the client code (client tests).

    +
  • +
  • +

    Acceptance tests used to verify if server-side implementation of the API is compliant with the contract (server tests).

    +
  • +
+
+
+

Spring Cloud Contract Verifier moves TDD to the level of software architecture.

+
+
+

This plugin allows you to:

+
+
+
    +
  • +

    generate tests from the provided contracts

    +
  • +
  • +

    run the stubs from the stubs

    +
  • +
+
+
+
+ +
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/issue-management.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/issue-management.html new file mode 100644 index 00000000..1138e0a7 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/issue-management.html @@ -0,0 +1,348 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Issue Management + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Overview

+

This project uses GitHub to manage its issues.

+
+

Issue Management

+

Issues, bugs, and feature requests should be submitted to the following issue management system for this project.

+
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/js/apache-maven-fluido-1.5.min.js b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/js/apache-maven-fluido-1.5.min.js new file mode 100644 index 00000000..0537c09d --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/js/apache-maven-fluido-1.5.min.js @@ -0,0 +1,25 @@ +/*! + * jQuery JavaScript Library v1.11.2 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-12-17T15:27Z + */ +(function(b,a){if(typeof module==="object"&&typeof module.exports==="object"){module.exports=b.document?a(b,true):function(c){if(!c.document){throw new Error("jQuery requires a window with a document")}return a(c)}}else{a(b)}}(typeof window!=="undefined"?window:this,function(a5,av){var aP=[];var P=aP.slice;var az=aP.concat;var x=aP.push;var bU=aP.indexOf;var ac={};var y=ac.toString;var K=ac.hasOwnProperty;var D={};var ai="1.11.2",bI=function(e,i){return new bI.fn.init(e,i)},E=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,bS=/^-ms-/,aW=/-([\da-z])/gi,O=function(e,i){return i.toUpperCase()};bI.fn=bI.prototype={jquery:ai,constructor:bI,selector:"",length:0,toArray:function(){return P.call(this)},get:function(e){return e!=null?(e<0?this[e+this.length]:this[e]):P.call(this)},pushStack:function(e){var i=bI.merge(this.constructor(),e);i.prevObject=this;i.context=this.context;return i},each:function(i,e){return bI.each(this,i,e)},map:function(e){return this.pushStack(bI.map(this,function(b7,b6){return e.call(b7,b6,b7)}))},slice:function(){return this.pushStack(P.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(b7){var e=this.length,b6=+b7+(b7<0?e:0);return this.pushStack(b6>=0&&b6=0},isEmptyObject:function(i){var e;for(e in i){return false}return true},isPlainObject:function(b7){var i;if(!b7||bI.type(b7)!=="object"||b7.nodeType||bI.isWindow(b7)){return false}try{if(b7.constructor&&!K.call(b7,"constructor")&&!K.call(b7.constructor.prototype,"isPrototypeOf")){return false}}catch(b6){return false}if(D.ownLast){for(i in b7){return K.call(b7,i)}}for(i in b7){}return i===undefined||K.call(b7,i)},type:function(e){if(e==null){return e+""}return typeof e==="object"||typeof e==="function"?ac[y.call(e)]||"object":typeof e},globalEval:function(e){if(e&&bI.trim(e)){(a5.execScript||function(i){a5["eval"].call(a5,i)})(e)}},camelCase:function(e){return e.replace(bS,"ms-").replace(aW,O)},nodeName:function(i,e){return i.nodeName&&i.nodeName.toLowerCase()===e.toLowerCase()},each:function(ca,cb,b6){var b9,b7=0,b8=ca.length,e=ad(ca);if(b6){if(e){for(;b70&&(i-1) in b6}var m= +/*! + * Sizzle CSS Selector Engine v2.2.0-pre + * http://sizzlejs.com/ + * + * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-12-16 + */ +(function(de){var cy,dh,cn,cH,cK,ci,cW,dg,dm,cI,cX,cZ,cC,co,c8,c3,df,ce,cF,da="sizzle"+1*new Date(),cJ=de.document,di=0,c4=0,b9=cA(),c9=cA(),cG=cA(),cE=function(i,e){if(i===e){cX=true}return 0},cQ=1<<31,cO=({}).hasOwnProperty,dc=[],dd=dc.pop,cM=dc.push,b7=dc.push,cm=dc.slice,cd=function(dq,dp){var dn=0,e=dq.length;for(;dn+~]|"+cp+")"+cp+"*"),ct=new RegExp("="+cp+"*([^\\]'\"]*?)"+cp+"*\\]","g"),cS=new RegExp(ck),cU=new RegExp("^"+cL+"$"),c2={ID:new RegExp("^#("+b6+")"),CLASS:new RegExp("^\\.("+b6+")"),TAG:new RegExp("^("+b6.replace("w","w*")+")"),ATTR:new RegExp("^"+c6),PSEUDO:new RegExp("^"+ck),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+cp+"*(even|odd|(([+-]|)(\\d*)n|)"+cp+"*(?:([+-]|)"+cp+"*(\\d+)|))"+cp+"*\\)|)","i"),bool:new RegExp("^(?:"+b8+")$","i"),needsContext:new RegExp("^"+cp+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+cp+"*((?:-\\d)?\\d*)"+cp+"*\\)|)(?=[^-]|$)","i")},cc=/^(?:input|select|textarea|button)$/i,cl=/^h\d$/i,cP=/^[^{]+\{\s*\[native \w/,cR=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,c1=/[+~]/,cN=/'|\\/g,cs=new RegExp("\\\\([\\da-f]{1,6}"+cp+"?|("+cp+")|.)","ig"),c5=function(e,dp,i){var dn="0x"+dp-65536;return dn!==dn||i?dp:dn<0?String.fromCharCode(dn+65536):String.fromCharCode(dn>>10|55296,dn&1023|56320)},dl=function(){cZ()};try{b7.apply((dc=cm.call(cJ.childNodes)),cJ.childNodes);dc[cJ.childNodes.length].nodeType}catch(cD){b7={apply:dc.length?function(i,e){cM.apply(i,cm.call(e))}:function(dq,dp){var e=dq.length,dn=0;while((dq[e++]=dp[dn++])){}dq.length=e-1}}}function cw(dv,dn,dz,dB){var dA,ds,dt,dx,dy,dr,dq,e,dp,dw;if((dn?dn.ownerDocument||dn:cJ)!==cC){cZ(dn)}dn=dn||cC;dz=dz||[];dx=dn.nodeType;if(typeof dv!=="string"||!dv||dx!==1&&dx!==9&&dx!==11){return dz}if(!dB&&c8){if(dx!==11&&(dA=cR.exec(dv))){if((dt=dA[1])){if(dx===9){ds=dn.getElementById(dt);if(ds&&ds.parentNode){if(ds.id===dt){dz.push(ds);return dz}}else{return dz}}else{if(dn.ownerDocument&&(ds=dn.ownerDocument.getElementById(dt))&&cF(dn,ds)&&ds.id===dt){dz.push(ds);return dz}}}else{if(dA[2]){b7.apply(dz,dn.getElementsByTagName(dv));return dz}else{if((dt=dA[3])&&dh.getElementsByClassName){b7.apply(dz,dn.getElementsByClassName(dt));return dz}}}}if(dh.qsa&&(!c3||!c3.test(dv))){e=dq=da;dp=dn;dw=dx!==1&&dv;if(dx===1&&dn.nodeName.toLowerCase()!=="object"){dr=ci(dv);if((dq=dn.getAttribute("id"))){e=dq.replace(cN,"\\$&")}else{dn.setAttribute("id",e)}e="[id='"+e+"'] ";dy=dr.length;while(dy--){dr[dy]=e+ch(dr[dy])}dp=c1.test(dv)&&cT(dn.parentNode)||dn;dw=dr.join(",")}if(dw){try{b7.apply(dz,dp.querySelectorAll(dw));return dz}catch(du){}finally{if(!dq){dn.removeAttribute("id")}}}}}return dg(dv.replace(cr,"$1"),dn,dz,dB)}function cA(){var i=[];function e(dn,dp){if(i.push(dn+" ")>cn.cacheLength){delete e[i.shift()]}return(e[dn+" "]=dp)}return e}function cj(e){e[da]=true;return e}function cf(i){var dp=cC.createElement("div");try{return !!i(dp)}catch(dn){return false}finally{if(dp.parentNode){dp.parentNode.removeChild(dp)}dp=null}}function dj(dn,dq){var e=dn.split("|"),dp=dn.length;while(dp--){cn.attrHandle[e[dp]]=dq}}function ca(i,e){var dp=e&&i,dn=dp&&i.nodeType===1&&e.nodeType===1&&(~e.sourceIndex||cQ)-(~i.sourceIndex||cQ);if(dn){return dn}if(dp){while((dp=dp.nextSibling)){if(dp===e){return -1}}}return i?1:-1}function cx(e){return function(dn){var i=dn.nodeName.toLowerCase();return i==="input"&&dn.type===e}}function cb(e){return function(dn){var i=dn.nodeName.toLowerCase();return(i==="input"||i==="button")&&dn.type===e}}function c7(e){return cj(function(i){i=+i;return cj(function(dn,ds){var dq,dp=e([],dn.length,i),dr=dp.length;while(dr--){if(dn[(dq=dp[dr])]){dn[dq]=!(ds[dq]=dn[dq])}}})})}function cT(e){return e&&typeof e.getElementsByTagName!=="undefined"&&e}dh=cw.support={};cK=cw.isXML=function(e){var i=e&&(e.ownerDocument||e).documentElement;return i?i.nodeName!=="HTML":false};cZ=cw.setDocument=function(dn){var e,i,dp=dn?dn.ownerDocument||dn:cJ;if(dp===cC||dp.nodeType!==9||!dp.documentElement){return cC}cC=dp;co=dp.documentElement;i=dp.defaultView;if(i&&i!==i.top){if(i.addEventListener){i.addEventListener("unload",dl,false)}else{if(i.attachEvent){i.attachEvent("onunload",dl)}}}c8=!cK(dp);dh.attributes=cf(function(dq){dq.className="i";return !dq.getAttribute("className")});dh.getElementsByTagName=cf(function(dq){dq.appendChild(dp.createComment(""));return !dq.getElementsByTagName("*").length});dh.getElementsByClassName=cP.test(dp.getElementsByClassName);dh.getById=cf(function(dq){co.appendChild(dq).id=da;return !dp.getElementsByName||!dp.getElementsByName(da).length});if(dh.getById){cn.find.ID=function(ds,dr){if(typeof dr.getElementById!=="undefined"&&c8){var dq=dr.getElementById(ds);return dq&&dq.parentNode?[dq]:[]}};cn.filter.ID=function(dr){var dq=dr.replace(cs,c5);return function(ds){return ds.getAttribute("id")===dq}}}else{delete cn.find.ID;cn.filter.ID=function(dr){var dq=dr.replace(cs,c5);return function(dt){var ds=typeof dt.getAttributeNode!=="undefined"&&dt.getAttributeNode("id");return ds&&ds.value===dq}}}cn.find.TAG=dh.getElementsByTagName?function(dq,dr){if(typeof dr.getElementsByTagName!=="undefined"){return dr.getElementsByTagName(dq)}else{if(dh.qsa){return dr.querySelectorAll(dq)}}}:function(dq,du){var dv,dt=[],ds=0,dr=du.getElementsByTagName(dq);if(dq==="*"){while((dv=dr[ds++])){if(dv.nodeType===1){dt.push(dv)}}return dt}return dr};cn.find.CLASS=dh.getElementsByClassName&&function(dr,dq){if(c8){return dq.getElementsByClassName(dr)}};df=[];c3=[];if((dh.qsa=cP.test(dp.querySelectorAll))){cf(function(dq){co.appendChild(dq).innerHTML="";if(dq.querySelectorAll("[msallowcapture^='']").length){c3.push("[*^$]="+cp+"*(?:''|\"\")")}if(!dq.querySelectorAll("[selected]").length){c3.push("\\["+cp+"*(?:value|"+b8+")")}if(!dq.querySelectorAll("[id~="+da+"-]").length){c3.push("~=")}if(!dq.querySelectorAll(":checked").length){c3.push(":checked")}if(!dq.querySelectorAll("a#"+da+"+*").length){c3.push(".#.+[+~]")}});cf(function(dr){var dq=dp.createElement("input");dq.setAttribute("type","hidden");dr.appendChild(dq).setAttribute("name","D");if(dr.querySelectorAll("[name=d]").length){c3.push("name"+cp+"*[*^$|!~]?=")}if(!dr.querySelectorAll(":enabled").length){c3.push(":enabled",":disabled")}dr.querySelectorAll("*,:x");c3.push(",.*:")})}if((dh.matchesSelector=cP.test((ce=co.matches||co.webkitMatchesSelector||co.mozMatchesSelector||co.oMatchesSelector||co.msMatchesSelector)))){cf(function(dq){dh.disconnectedMatch=ce.call(dq,"div");ce.call(dq,"[s!='']:x");df.push("!=",ck)})}c3=c3.length&&new RegExp(c3.join("|"));df=df.length&&new RegExp(df.join("|"));e=cP.test(co.compareDocumentPosition);cF=e||cP.test(co.contains)?function(dr,dq){var dt=dr.nodeType===9?dr.documentElement:dr,ds=dq&&dq.parentNode;return dr===ds||!!(ds&&ds.nodeType===1&&(dt.contains?dt.contains(ds):dr.compareDocumentPosition&&dr.compareDocumentPosition(ds)&16))}:function(dr,dq){if(dq){while((dq=dq.parentNode)){if(dq===dr){return true}}}return false};cE=e?function(dr,dq){if(dr===dq){cX=true;return 0}var ds=!dr.compareDocumentPosition-!dq.compareDocumentPosition;if(ds){return ds}ds=(dr.ownerDocument||dr)===(dq.ownerDocument||dq)?dr.compareDocumentPosition(dq):1;if(ds&1||(!dh.sortDetached&&dq.compareDocumentPosition(dr)===ds)){if(dr===dp||dr.ownerDocument===cJ&&cF(cJ,dr)){return -1}if(dq===dp||dq.ownerDocument===cJ&&cF(cJ,dq)){return 1}return cI?(cd(cI,dr)-cd(cI,dq)):0}return ds&4?-1:1}:function(dr,dq){if(dr===dq){cX=true;return 0}var dx,du=0,dw=dr.parentNode,dt=dq.parentNode,ds=[dr],dv=[dq];if(!dw||!dt){return dr===dp?-1:dq===dp?1:dw?-1:dt?1:cI?(cd(cI,dr)-cd(cI,dq)):0}else{if(dw===dt){return ca(dr,dq)}}dx=dr;while((dx=dx.parentNode)){ds.unshift(dx)}dx=dq;while((dx=dx.parentNode)){dv.unshift(dx)}while(ds[du]===dv[du]){du++}return du?ca(ds[du],dv[du]):ds[du]===cJ?-1:dv[du]===cJ?1:0};return dp};cw.matches=function(i,e){return cw(i,null,null,e)};cw.matchesSelector=function(dn,dq){if((dn.ownerDocument||dn)!==cC){cZ(dn)}dq=dq.replace(ct,"='$1']");if(dh.matchesSelector&&c8&&(!df||!df.test(dq))&&(!c3||!c3.test(dq))){try{var i=ce.call(dn,dq);if(i||dh.disconnectedMatch||dn.document&&dn.document.nodeType!==11){return i}}catch(dp){}}return cw(dq,cC,null,[dn]).length>0};cw.contains=function(e,i){if((e.ownerDocument||e)!==cC){cZ(e)}return cF(e,i)};cw.attr=function(dn,e){if((dn.ownerDocument||dn)!==cC){cZ(dn)}var i=cn.attrHandle[e.toLowerCase()],dp=i&&cO.call(cn.attrHandle,e.toLowerCase())?i(dn,e,!c8):undefined;return dp!==undefined?dp:dh.attributes||!c8?dn.getAttribute(e):(dp=dn.getAttributeNode(e))&&dp.specified?dp.value:null};cw.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};cw.uniqueSort=function(dp){var dq,dr=[],e=0,dn=0;cX=!dh.detectDuplicates;cI=!dh.sortStable&&dp.slice(0);dp.sort(cE);if(cX){while((dq=dp[dn++])){if(dq===dp[dn]){e=dr.push(dn)}}while(e--){dp.splice(dr[e],1)}}cI=null;return dp};cH=cw.getText=function(dr){var dq,dn="",dp=0,e=dr.nodeType;if(!e){while((dq=dr[dp++])){dn+=cH(dq)}}else{if(e===1||e===9||e===11){if(typeof dr.textContent==="string"){return dr.textContent}else{for(dr=dr.firstChild;dr;dr=dr.nextSibling){dn+=cH(dr)}}}else{if(e===3||e===4){return dr.nodeValue}}}return dn};cn=cw.selectors={cacheLength:50,createPseudo:cj,match:c2,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(cs,c5);e[3]=(e[3]||e[4]||e[5]||"").replace(cs,c5);if(e[2]==="~="){e[3]=" "+e[3]+" "}return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if(e[1].slice(0,3)==="nth"){if(!e[3]){cw.error(e[0])}e[4]=+(e[4]?e[5]+(e[6]||1):2*(e[3]==="even"||e[3]==="odd"));e[5]=+((e[7]+e[8])||e[3]==="odd")}else{if(e[3]){cw.error(e[0])}}return e},PSEUDO:function(i){var e,dn=!i[6]&&i[2];if(c2.CHILD.test(i[0])){return null}if(i[3]){i[2]=i[4]||i[5]||""}else{if(dn&&cS.test(dn)&&(e=ci(dn,true))&&(e=dn.indexOf(")",dn.length-e)-dn.length)){i[0]=i[0].slice(0,e);i[2]=dn.slice(0,e)}}return i.slice(0,3)}},filter:{TAG:function(i){var e=i.replace(cs,c5).toLowerCase();return i==="*"?function(){return true}:function(dn){return dn.nodeName&&dn.nodeName.toLowerCase()===e}},CLASS:function(e){var i=b9[e+" "];return i||(i=new RegExp("(^|"+cp+")"+e+"("+cp+"|$)"))&&b9(e,function(dn){return i.test(typeof dn.className==="string"&&dn.className||typeof dn.getAttribute!=="undefined"&&dn.getAttribute("class")||"")})},ATTR:function(dn,i,e){return function(dq){var dp=cw.attr(dq,dn);if(dp==null){return i==="!="}if(!i){return true}dp+="";return i==="="?dp===e:i==="!="?dp!==e:i==="^="?e&&dp.indexOf(e)===0:i==="*="?e&&dp.indexOf(e)>-1:i==="$="?e&&dp.slice(-e.length)===e:i==="~="?(" "+dp.replace(cu," ")+" ").indexOf(e)>-1:i==="|="?dp===e||dp.slice(0,e.length+1)===e+"-":false}},CHILD:function(i,dq,dp,dr,dn){var dt=i.slice(0,3)!=="nth",e=i.slice(-4)!=="last",ds=dq==="of-type";return dr===1&&dn===0?function(du){return !!du.parentNode}:function(dA,dy,dD){var du,dG,dB,dF,dC,dx,dz=dt!==e?"nextSibling":"previousSibling",dE=dA.parentNode,dw=ds&&dA.nodeName.toLowerCase(),dv=!dD&&!ds;if(dE){if(dt){while(dz){dB=dA;while((dB=dB[dz])){if(ds?dB.nodeName.toLowerCase()===dw:dB.nodeType===1){return false}}dx=dz=i==="only"&&!dx&&"nextSibling"}return true}dx=[e?dE.firstChild:dE.lastChild];if(e&&dv){dG=dE[da]||(dE[da]={});du=dG[i]||[];dC=du[0]===di&&du[1];dF=du[0]===di&&du[2];dB=dC&&dE.childNodes[dC];while((dB=++dC&&dB&&dB[dz]||(dF=dC=0)||dx.pop())){if(dB.nodeType===1&&++dF&&dB===dA){dG[i]=[di,dC,dF];break}}}else{if(dv&&(du=(dA[da]||(dA[da]={}))[i])&&du[0]===di){dF=du[1]}else{while((dB=++dC&&dB&&dB[dz]||(dF=dC=0)||dx.pop())){if((ds?dB.nodeName.toLowerCase()===dw:dB.nodeType===1)&&++dF){if(dv){(dB[da]||(dB[da]={}))[i]=[di,dF]}if(dB===dA){break}}}}}dF-=dn;return dF===dr||(dF%dr===0&&dF/dr>=0)}}},PSEUDO:function(dp,dn){var e,i=cn.pseudos[dp]||cn.setFilters[dp.toLowerCase()]||cw.error("unsupported pseudo: "+dp);if(i[da]){return i(dn)}if(i.length>1){e=[dp,dp,"",dn];return cn.setFilters.hasOwnProperty(dp.toLowerCase())?cj(function(ds,du){var dr,dq=i(ds,dn),dt=dq.length;while(dt--){dr=cd(ds,dq[dt]);ds[dr]=!(du[dr]=dq[dt])}}):function(dq){return i(dq,0,e)}}return i}},pseudos:{not:cj(function(e){var i=[],dn=[],dp=cW(e.replace(cr,"$1"));return dp[da]?cj(function(dr,dw,du,ds){var dv,dq=dp(dr,null,ds,[]),dt=dr.length;while(dt--){if((dv=dq[dt])){dr[dt]=!(dw[dt]=dv)}}}):function(ds,dr,dq){i[0]=ds;dp(i,null,dq,dn);i[0]=null;return !dn.pop()}}),has:cj(function(e){return function(i){return cw(e,i).length>0}}),contains:cj(function(e){e=e.replace(cs,c5);return function(i){return(i.textContent||i.innerText||cH(i)).indexOf(e)>-1}}),lang:cj(function(e){if(!cU.test(e||"")){cw.error("unsupported lang: "+e)}e=e.replace(cs,c5).toLowerCase();return function(dn){var i;do{if((i=c8?dn.lang:dn.getAttribute("xml:lang")||dn.getAttribute("lang"))){i=i.toLowerCase();return i===e||i.indexOf(e+"-")===0}}while((dn=dn.parentNode)&&dn.nodeType===1);return false}}),target:function(e){var i=de.location&&de.location.hash;return i&&i.slice(1)===e.id},root:function(e){return e===co},focus:function(e){return e===cC.activeElement&&(!cC.hasFocus||cC.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===false},disabled:function(e){return e.disabled===true},checked:function(e){var i=e.nodeName.toLowerCase();return(i==="input"&&!!e.checked)||(i==="option"&&!!e.selected)},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling){if(e.nodeType<6){return false}}return true},parent:function(e){return !cn.pseudos.empty(e)},header:function(e){return cl.test(e.nodeName)},input:function(e){return cc.test(e.nodeName)},button:function(i){var e=i.nodeName.toLowerCase();return e==="input"&&i.type==="button"||e==="button"},text:function(i){var e;return i.nodeName.toLowerCase()==="input"&&i.type==="text"&&((e=i.getAttribute("type"))==null||e.toLowerCase()==="text")},first:c7(function(){return[0]}),last:c7(function(e,i){return[i-1]}),eq:c7(function(e,dn,i){return[i<0?i+dn:i]}),even:c7(function(e,dp){var dn=0;for(;dn=0;){e.push(dn)}return e}),gt:c7(function(e,dq,dp){var dn=dp<0?dp+dq:dp;for(;++dn1?function(dr,dq,dn){var dp=e.length;while(dp--){if(!e[dp](dr,dq,dn)){return false}}return true}:e[0]}function cz(dn,dr,dq){var dp=0,e=dr.length;for(;dp-1){dC[dE]=!(dz[dE]=dw)}}}}else{dy=c0(dy===dz?dy.splice(dt,dy.length):dy);if(dr){dr(null,dz,dy,dB)}else{b7.apply(dz,dy)}}})}function db(dt){var dn,dr,dp,ds=dt.length,dw=cn.relative[dt[0].type],dx=dw||cn.relative[" "],dq=dw?1:0,du=cq(function(i){return i===dn},dx,true),dv=cq(function(i){return cd(dn,i)>-1},dx,true),e=[function(dA,dz,dy){var i=(!dw&&(dy||dz!==dm))||((dn=dz).nodeType?du(dA,dz,dy):dv(dA,dz,dy));dn=null;return i}];for(;dq1&&dk(e),dq>1&&ch(dt.slice(0,dq-1).concat({value:dt[dq-2].type===" "?"*":""})).replace(cr,"$1"),dr,dq0,dq=dp.length>0,i=function(dA,du,dz,dy,dD){var dv,dw,dB,dF=0,dx="0",dr=dA&&[],dG=[],dE=dm,dt=dA||dq&&cn.find.TAG("*",dD),ds=(di+=dE==null?1:Math.random()||0.1),dC=dt.length;if(dD){dm=du!==cC&&du}for(;dx!==dC&&(dv=dt[dx])!=null;dx++){if(dq&&dv){dw=0;while((dB=dp[dw++])){if(dB(dv,du,dz)){dy.push(dv);break}}if(dD){di=ds}}if(e){if((dv=!dB&&dv)){dF--}if(dA){dr.push(dv)}}}dF+=dx;if(e&&dx!==dF){dw=0;while((dB=dn[dw++])){dB(dr,dG,du,dz)}if(dA){if(dF>0){while(dx--){if(!(dr[dx]||dG[dx])){dG[dx]=dd.call(dy)}}}dG=c0(dG)}b7.apply(dy,dG);if(dD&&!dA&&dG.length>0&&(dF+dn.length)>1){cw.uniqueSort(dy)}}if(dD){di=ds;dm=dE}return dr};return e?cj(i):i}cW=cw.compile=function(e,dp){var dq,dn=[],ds=[],dr=cG[e+" "];if(!dr){if(!dp){dp=ci(e)}dq=dp.length;while(dq--){dr=db(dp[dq]);if(dr[da]){dn.push(dr)}else{ds.push(dr)}}dr=cG(e,cY(ds,dn));dr.selector=e}return dr};dg=cw.select=function(dp,e,dq,dt){var dr,dw,dn,dx,du,dv=typeof dp==="function"&&dp,ds=!dt&&ci((dp=dv.selector||dp));dq=dq||[];if(ds.length===1){dw=ds[0]=ds[0].slice(0);if(dw.length>2&&(dn=dw[0]).type==="ID"&&dh.getById&&e.nodeType===9&&c8&&cn.relative[dw[1].type]){e=(cn.find.ID(dn.matches[0].replace(cs,c5),e)||[])[0];if(!e){return dq}else{if(dv){e=e.parentNode}}dp=dp.slice(dw.shift().value.length)}dr=c2.needsContext.test(dp)?0:dw.length;while(dr--){dn=dw[dr];if(cn.relative[(dx=dn.type)]){break}if((du=cn.find[dx])){if((dt=du(dn.matches[0].replace(cs,c5),c1.test(dw[0].type)&&cT(e.parentNode)||e))){dw.splice(dr,1);dp=dt.length&&ch(dw);if(!dp){b7.apply(dq,dt);return dq}break}}}}(dv||cW(dp,ds))(dt,e,!c8,dq,c1.test(dp)&&cT(e.parentNode)||e);return dq};dh.sortStable=da.split("").sort(cE).join("")===da;dh.detectDuplicates=!!cX;cZ();dh.sortDetached=cf(function(e){return e.compareDocumentPosition(cC.createElement("div"))&1});if(!cf(function(e){e.innerHTML="";return e.firstChild.getAttribute("href")==="#"})){dj("type|href|height|width",function(i,e,dn){if(!dn){return i.getAttribute(e,e.toLowerCase()==="type"?1:2)}})}if(!dh.attributes||!cf(function(e){e.innerHTML="";e.firstChild.setAttribute("value","");return e.firstChild.getAttribute("value")===""})){dj("value",function(i,e,dn){if(!dn&&i.nodeName.toLowerCase()==="input"){return i.defaultValue}})}if(!cf(function(e){return e.getAttribute("disabled")==null})){dj(b8,function(i,e,dp){var dn;if(!dp){return i[e]===true?e.toLowerCase():(dn=i.getAttributeNode(e))&&dn.specified?dn.value:null}})}return cw})(a5);bI.find=m;bI.expr=m.selectors;bI.expr[":"]=bI.expr.pseudos;bI.unique=m.uniqueSort;bI.text=m.getText;bI.isXMLDoc=m.isXML;bI.contains=m.contains;var A=bI.expr.match.needsContext;var a=(/^<(\w+)\s*\/?>(?:<\/\1>|)$/);var aL=/^.[^:#\[\.,]*$/;function aR(b6,e,i){if(bI.isFunction(e)){return bI.grep(b6,function(b8,b7){return !!e.call(b8,b7,b8)!==i})}if(e.nodeType){return bI.grep(b6,function(b7){return(b7===e)!==i})}if(typeof e==="string"){if(aL.test(e)){return bI.filter(e,b6,i)}e=bI.filter(e,b6)}return bI.grep(b6,function(b7){return(bI.inArray(b7,e)>=0)!==i})}bI.filter=function(b7,e,b6){var i=e[0];if(b6){b7=":not("+b7+")"}return e.length===1&&i.nodeType===1?bI.find.matchesSelector(i,b7)?[i]:[]:bI.find.matches(b7,bI.grep(e,function(b8){return b8.nodeType===1}))};bI.fn.extend({find:function(b6){var b9,b8=[],b7=this,e=b7.length;if(typeof b6!=="string"){return this.pushStack(bI(b6).filter(function(){for(b9=0;b91?bI.unique(b8):b8);b8.selector=this.selector?this.selector+" "+b6:b6;return b8},filter:function(e){return this.pushStack(aR(this,e||[],false))},not:function(e){return this.pushStack(aR(this,e||[],true))},is:function(e){return !!aR(this,typeof e==="string"&&A.test(e)?bI(e):e||[],false).length}});var z,n=a5.document,bt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,bV=bI.fn.init=function(e,b6){var i,b7;if(!e){return this}if(typeof e==="string"){if(e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3){i=[null,e,null]}else{i=bt.exec(e)}if(i&&(i[1]||!b6)){if(i[1]){b6=b6 instanceof bI?b6[0]:b6;bI.merge(this,bI.parseHTML(i[1],b6&&b6.nodeType?b6.ownerDocument||b6:n,true));if(a.test(i[1])&&bI.isPlainObject(b6)){for(i in b6){if(bI.isFunction(this[i])){this[i](b6[i])}else{this.attr(i,b6[i])}}}return this}else{b7=n.getElementById(i[2]);if(b7&&b7.parentNode){if(b7.id!==i[2]){return z.find(e)}this.length=1;this[0]=b7}this.context=n;this.selector=e;return this}}else{if(!b6||b6.jquery){return(b6||z).find(e)}else{return this.constructor(b6).find(e)}}}else{if(e.nodeType){this.context=this[0]=e;this.length=1;return this}else{if(bI.isFunction(e)){return typeof z.ready!=="undefined"?z.ready(e):e(bI)}}}if(e.selector!==undefined){this.selector=e.selector;this.context=e.context}return bI.makeArray(e,this)};bV.prototype=bI.fn;z=bI(n);var bv=/^(?:parents|prev(?:Until|All))/,bz={children:true,contents:true,next:true,prev:true};bI.extend({dir:function(b6,i,b8){var e=[],b7=b6[i];while(b7&&b7.nodeType!==9&&(b8===undefined||b7.nodeType!==1||!bI(b7).is(b8))){if(b7.nodeType===1){e.push(b7)}b7=b7[i]}return e},sibling:function(b6,i){var e=[];for(;b6;b6=b6.nextSibling){if(b6.nodeType===1&&b6!==i){e.push(b6)}}return e}});bI.fn.extend({has:function(b8){var b7,b6=bI(b8,this),e=b6.length;return this.filter(function(){for(b7=0;b7-1:ca.nodeType===1&&bI.find.matchesSelector(ca,b9))){e.push(ca);break}}}return this.pushStack(e.length>1?bI.unique(e):e)},index:function(e){if(!e){return(this[0]&&this[0].parentNode)?this.first().prevAll().length:-1}if(typeof e==="string"){return bI.inArray(this[0],bI(e))}return bI.inArray(e.jquery?e[0]:e,this)},add:function(e,i){return this.pushStack(bI.unique(bI.merge(this.get(),bI(e,i))))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}});function aY(i,e){do{i=i[e]}while(i&&i.nodeType!==1);return i}bI.each({parent:function(i){var e=i.parentNode;return e&&e.nodeType!==11?e:null},parents:function(e){return bI.dir(e,"parentNode")},parentsUntil:function(b6,e,b7){return bI.dir(b6,"parentNode",b7)},next:function(e){return aY(e,"nextSibling")},prev:function(e){return aY(e,"previousSibling")},nextAll:function(e){return bI.dir(e,"nextSibling")},prevAll:function(e){return bI.dir(e,"previousSibling")},nextUntil:function(b6,e,b7){return bI.dir(b6,"nextSibling",b7)},prevUntil:function(b6,e,b7){return bI.dir(b6,"previousSibling",b7)},siblings:function(e){return bI.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return bI.sibling(e.firstChild)},contents:function(e){return bI.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:bI.merge([],e.childNodes)}},function(e,i){bI.fn[e]=function(b8,b6){var b7=bI.map(this,i,b8);if(e.slice(-5)!=="Until"){b6=b8}if(b6&&typeof b6==="string"){b7=bI.filter(b6,b7)}if(this.length>1){if(!bz[e]){b7=bI.unique(b7)}if(bv.test(e)){b7=b7.reverse()}}return this.pushStack(b7)}});var aF=(/\S+/g);var b2={};function af(i){var e=b2[i]={};bI.each(i.match(aF)||[],function(b7,b6){e[b6]=true});return e}bI.Callbacks=function(ce){ce=typeof ce==="string"?(b2[ce]||af(ce)):bI.extend({},ce);var b8,b7,e,b9,ca,b6,cb=[],cc=!ce.once&&[],i=function(cf){b7=ce.memory&&cf;e=true;ca=b6||0;b6=0;b9=cb.length;b8=true;for(;cb&&ca-1){cb.splice(cg,1);if(b8){if(cg<=b9){b9--}if(cg<=ca){ca--}}}})}return this},has:function(cf){return cf?bI.inArray(cf,cb)>-1:!!(cb&&cb.length)},empty:function(){cb=[];b9=0;return this},disable:function(){cb=cc=b7=undefined;return this},disabled:function(){return !cb},lock:function(){cc=undefined;if(!b7){cd.disable()}return this},locked:function(){return !cc},fireWith:function(cg,cf){if(cb&&(!e||cc)){cf=cf||[];cf=[cg,cf.slice?cf.slice():cf];if(b8){cc.push(cf)}else{i(cf)}}return this},fire:function(){cd.fireWith(this,arguments);return this},fired:function(){return !!e}};return cd};bI.extend({Deferred:function(b6){var i=[["resolve","done",bI.Callbacks("once memory"),"resolved"],["reject","fail",bI.Callbacks("once memory"),"rejected"],["notify","progress",bI.Callbacks("memory")]],b7="pending",b8={state:function(){return b7},always:function(){e.done(arguments).fail(arguments);return this},then:function(){var b9=arguments;return bI.Deferred(function(ca){bI.each(i,function(cc,cb){var cd=bI.isFunction(b9[cc])&&b9[cc];e[cb[1]](function(){var ce=cd&&cd.apply(this,arguments);if(ce&&bI.isFunction(ce.promise)){ce.promise().done(ca.resolve).fail(ca.reject).progress(ca.notify)}else{ca[cb[0]+"With"](this===b8?ca.promise():this,cd?[ce]:arguments)}})});b9=null}).promise()},promise:function(b9){return b9!=null?bI.extend(b9,b8):b8}},e={};b8.pipe=b8.then;bI.each(i,function(ca,b9){var cc=b9[2],cb=b9[3];b8[b9[1]]=cc.add;if(cb){cc.add(function(){b7=cb},i[ca^1][2].disable,i[2][2].lock)}e[b9[0]]=function(){e[b9[0]+"With"](this===e?b8:this,arguments);return this};e[b9[0]+"With"]=cc.fireWith});b8.promise(e);if(b6){b6.call(e,e)}return e},when:function(b9){var b7=0,cb=P.call(arguments),e=cb.length,b6=e!==1||(b9&&bI.isFunction(b9.promise))?e:0,ce=b6===1?b9:bI.Deferred(),b8=function(cg,ch,cf){return function(i){ch[cg]=this;cf[cg]=arguments.length>1?P.call(arguments):i;if(cf===cd){ce.notifyWith(ch,cf)}else{if(!(--b6)){ce.resolveWith(ch,cf)}}}},cd,ca,cc;if(e>1){cd=new Array(e);ca=new Array(e);cc=new Array(e);for(;b70){return}ak.resolveWith(n,[bI]);if(bI.fn.triggerHandler){bI(n).triggerHandler("ready");bI(n).off("ready")}}});function bm(){if(n.addEventListener){n.removeEventListener("DOMContentLoaded",bZ,false);a5.removeEventListener("load",bZ,false)}else{n.detachEvent("onreadystatechange",bZ);a5.detachEvent("onload",bZ)}}function bZ(){if(n.addEventListener||event.type==="load"||n.readyState==="complete"){bm();bI.ready()}}bI.ready.promise=function(b8){if(!ak){ak=bI.Deferred();if(n.readyState==="complete"){setTimeout(bI.ready)}else{if(n.addEventListener){n.addEventListener("DOMContentLoaded",bZ,false);a5.addEventListener("load",bZ,false)}else{n.attachEvent("onreadystatechange",bZ);a5.attachEvent("onload",bZ);var b7=false;try{b7=a5.frameElement==null&&n.documentElement}catch(b6){}if(b7&&b7.doScroll){(function i(){if(!bI.isReady){try{b7.doScroll("left")}catch(b9){return setTimeout(i,50)}bm();bI.ready()}})()}}}}return ak.promise(b8)};var aC=typeof undefined;var bh;for(bh in bI(D)){break}D.ownLast=bh!=="0";D.inlineBlockNeedsLayout=false;bI(function(){var b6,b7,e,i;e=n.getElementsByTagName("body")[0];if(!e||!e.style){return}b7=n.createElement("div");i=n.createElement("div");i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";e.appendChild(i).appendChild(b7);if(typeof b7.style.zoom!==aC){b7.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";D.inlineBlockNeedsLayout=b6=b7.offsetWidth===3;if(b6){e.style.zoom=1}}e.removeChild(i)});(function(){var b6=n.createElement("div");if(D.deleteExpando==null){D.deleteExpando=true;try{delete b6.test}catch(i){D.deleteExpando=false}}b6=null})();bI.acceptData=function(b6){var i=bI.noData[(b6.nodeName+" ").toLowerCase()],e=+b6.nodeType||1;return e!==1&&e!==9?false:!i||i!==true&&b6.getAttribute("classid")===i};var by=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,aQ=/([A-Z])/g;function bA(b7,b6,b8){if(b8===undefined&&b7.nodeType===1){var i="data-"+b6.replace(aQ,"-$1").toLowerCase();b8=b7.getAttribute(i);if(typeof b8==="string"){try{b8=b8==="true"?true:b8==="false"?false:b8==="null"?null:+b8+""===b8?+b8:by.test(b8)?bI.parseJSON(b8):b8}catch(b9){}bI.data(b7,b6,b8)}else{b8=undefined}}return b8}function Q(i){var e;for(e in i){if(e==="data"&&bI.isEmptyObject(i[e])){continue}if(e!=="toJSON"){return false}}return true}function bc(b7,i,b9,b8){if(!bI.acceptData(b7)){return}var cb,ca,cc=bI.expando,cd=b7.nodeType,e=cd?bI.cache:b7,b6=cd?b7[cc]:b7[cc]&&cc;if((!b6||!e[b6]||(!b8&&!e[b6].data))&&b9===undefined&&typeof i==="string"){return}if(!b6){if(cd){b6=b7[cc]=aP.pop()||bI.guid++}else{b6=cc}}if(!e[b6]){e[b6]=cd?{}:{toJSON:bI.noop}}if(typeof i==="object"||typeof i==="function"){if(b8){e[b6]=bI.extend(e[b6],i)}else{e[b6].data=bI.extend(e[b6].data,i)}}ca=e[b6];if(!b8){if(!ca.data){ca.data={}}ca=ca.data}if(b9!==undefined){ca[bI.camelCase(i)]=b9}if(typeof i==="string"){cb=ca[i];if(cb==null){cb=ca[bI.camelCase(i)]}}else{cb=ca}return cb}function ab(b9,b7,e){if(!bI.acceptData(b9)){return}var cb,b8,ca=b9.nodeType,b6=ca?bI.cache:b9,cc=ca?b9[bI.expando]:bI.expando;if(!b6[cc]){return}if(b7){cb=e?b6[cc]:b6[cc].data;if(cb){if(!bI.isArray(b7)){if(b7 in cb){b7=[b7]}else{b7=bI.camelCase(b7);if(b7 in cb){b7=[b7]}else{b7=b7.split(" ")}}}else{b7=b7.concat(bI.map(b7,bI.camelCase))}b8=b7.length;while(b8--){delete cb[b7[b8]]}if(e?!Q(cb):!bI.isEmptyObject(cb)){return}}}if(!e){delete b6[cc].data;if(!Q(b6[cc])){return}}if(ca){bI.cleanData([b9],true)}else{if(D.deleteExpando||b6!=b6.window){delete b6[cc]}else{b6[cc]=null}}}bI.extend({cache:{},noData:{"applet ":true,"embed ":true,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?bI.cache[e[bI.expando]]:e[bI.expando];return !!e&&!Q(e)},data:function(i,e,b6){return bc(i,e,b6)},removeData:function(i,e){return ab(i,e)},_data:function(i,e,b6){return bc(i,e,b6,true)},_removeData:function(i,e){return ab(i,e,true)}});bI.fn.extend({data:function(b8,cb){var b7,b6,ca,b9=this[0],e=b9&&b9.attributes;if(b8===undefined){if(this.length){ca=bI.data(b9);if(b9.nodeType===1&&!bI._data(b9,"parsedAttrs")){b7=e.length;while(b7--){if(e[b7]){b6=e[b7].name;if(b6.indexOf("data-")===0){b6=bI.camelCase(b6.slice(5));bA(b9,b6,ca[b6])}}}bI._data(b9,"parsedAttrs",true)}}return ca}if(typeof b8==="object"){return this.each(function(){bI.data(this,b8)})}return arguments.length>1?this.each(function(){bI.data(this,b8,cb)}):b9?bA(b9,b8,bI.data(b9,b8)):undefined},removeData:function(e){return this.each(function(){bI.removeData(this,e)})}});bI.extend({queue:function(b6,i,b7){var e;if(b6){i=(i||"fx")+"queue";e=bI._data(b6,i);if(b7){if(!e||bI.isArray(b7)){e=bI._data(b6,i,bI.makeArray(b7))}else{e.push(b7)}}return e||[]}},dequeue:function(b9,b8){b8=b8||"fx";var i=bI.queue(b9,b8),ca=i.length,b7=i.shift(),e=bI._queueHooks(b9,b8),b6=function(){bI.dequeue(b9,b8)};if(b7==="inprogress"){b7=i.shift();ca--}if(b7){if(b8==="fx"){i.unshift("inprogress")}delete e.stop;b7.call(b9,b6,e)}if(!ca&&e){e.empty.fire()}},_queueHooks:function(b6,i){var e=i+"queueHooks";return bI._data(b6,e)||bI._data(b6,e,{empty:bI.Callbacks("once memory").add(function(){bI._removeData(b6,i+"queue");bI._removeData(b6,e)})})}});bI.fn.extend({queue:function(e,i){var b6=2;if(typeof e!=="string"){i=e;e="fx";b6--}if(arguments.length
a";D.leadingWhitespace=b8.firstChild.nodeType===3;D.tbody=!b8.getElementsByTagName("tbody").length;D.htmlSerialize=!!b8.getElementsByTagName("link").length;D.html5Clone=n.createElement("nav").cloneNode(true).outerHTML!=="<:nav>";i.type="checkbox";i.checked=true;b6.appendChild(i);D.appendChecked=i.checked;b8.innerHTML="";D.noCloneChecked=!!b8.cloneNode(true).lastChild.defaultValue;b6.appendChild(b8);b8.innerHTML="";D.checkClone=b8.cloneNode(true).cloneNode(true).lastChild.checked;D.noCloneEvent=true;if(b8.attachEvent){b8.attachEvent("onclick",function(){D.noCloneEvent=false});b8.cloneNode(true).click()}if(D.deleteExpando==null){D.deleteExpando=true;try{delete b8.test}catch(b7){D.deleteExpando=false}}})();(function(){var b6,e,b7=n.createElement("div");for(b6 in {submit:true,change:true,focusin:true}){e="on"+b6;if(!(D[b6+"Bubbles"]=e in a5)){b7.setAttribute(e,"t");D[b6+"Bubbles"]=b7.attributes[e].expando===false}}b7=null})();var bG=/^(?:input|select|textarea)$/i,a6=/^key/,bM=/^(?:mouse|pointer|contextmenu)|click/,bC=/^(?:focusinfocus|focusoutblur)$/,bx=/^([^.]*)(?:\.(.+)|)$/;function U(){return true}function Z(){return false}function am(){try{return n.activeElement}catch(e){}}bI.event={global:{},add:function(b8,cd,ci,ca,b9){var cb,cj,ck,b6,cf,cc,ch,b7,cg,e,i,ce=bI._data(b8);if(!ce){return}if(ci.handler){b6=ci;ci=b6.handler;b9=b6.selector}if(!ci.guid){ci.guid=bI.guid++}if(!(cj=ce.events)){cj=ce.events={}}if(!(cc=ce.handle)){cc=ce.handle=function(cl){return typeof bI!==aC&&(!cl||bI.event.triggered!==cl.type)?bI.event.dispatch.apply(cc.elem,arguments):undefined};cc.elem=b8}cd=(cd||"").match(aF)||[""];ck=cd.length;while(ck--){cb=bx.exec(cd[ck])||[];cg=i=cb[1];e=(cb[2]||"").split(".").sort();if(!cg){continue}cf=bI.event.special[cg]||{};cg=(b9?cf.delegateType:cf.bindType)||cg;cf=bI.event.special[cg]||{};ch=bI.extend({type:cg,origType:i,data:ca,handler:ci,guid:ci.guid,selector:b9,needsContext:b9&&bI.expr.match.needsContext.test(b9),namespace:e.join(".")},b6);if(!(b7=cj[cg])){b7=cj[cg]=[];b7.delegateCount=0;if(!cf.setup||cf.setup.call(b8,ca,e,cc)===false){if(b8.addEventListener){b8.addEventListener(cg,cc,false)}else{if(b8.attachEvent){b8.attachEvent("on"+cg,cc)}}}}if(cf.add){cf.add.call(b8,ch);if(!ch.handler.guid){ch.handler.guid=ci.guid}}if(b9){b7.splice(b7.delegateCount++,0,ch)}else{b7.push(ch)}bI.event.global[cg]=true}b8=null},remove:function(b7,cd,ck,b8,cc){var ca,ch,cb,b9,cj,ci,cf,b6,cg,e,i,ce=bI.hasData(b7)&&bI._data(b7);if(!ce||!(ci=ce.events)){return}cd=(cd||"").match(aF)||[""];cj=cd.length;while(cj--){cb=bx.exec(cd[cj])||[];cg=i=cb[1];e=(cb[2]||"").split(".").sort();if(!cg){for(cg in ci){bI.event.remove(b7,cg+cd[cj],ck,b8,true)}continue}cf=bI.event.special[cg]||{};cg=(b8?cf.delegateType:cf.bindType)||cg;b6=ci[cg]||[];cb=cb[2]&&new RegExp("(^|\\.)"+e.join("\\.(?:.*\\.|)")+"(\\.|$)");b9=ca=b6.length;while(ca--){ch=b6[ca];if((cc||i===ch.origType)&&(!ck||ck.guid===ch.guid)&&(!cb||cb.test(ch.namespace))&&(!b8||b8===ch.selector||b8==="**"&&ch.selector)){b6.splice(ca,1);if(ch.selector){b6.delegateCount--}if(cf.remove){cf.remove.call(b7,ch)}}}if(b9&&!b6.length){if(!cf.teardown||cf.teardown.call(b7,e,ce.handle)===false){bI.removeEvent(b7,cg,ce.handle)}delete ci[cg]}}if(bI.isEmptyObject(ci)){delete ce.handle;bI._removeData(b7,"events")}},trigger:function(b6,cd,b9,ck){var ce,b8,ci,cj,cg,cc,cb,ca=[b9||n],ch=K.call(b6,"type")?b6.type:b6,b7=K.call(b6,"namespace")?b6.namespace.split("."):[];ci=cc=b9=b9||n;if(b9.nodeType===3||b9.nodeType===8){return}if(bC.test(ch+bI.event.triggered)){return}if(ch.indexOf(".")>=0){b7=ch.split(".");ch=b7.shift();b7.sort()}b8=ch.indexOf(":")<0&&"on"+ch;b6=b6[bI.expando]?b6:new bI.Event(ch,typeof b6==="object"&&b6);b6.isTrigger=ck?2:3;b6.namespace=b7.join(".");b6.namespace_re=b6.namespace?new RegExp("(^|\\.)"+b7.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;b6.result=undefined;if(!b6.target){b6.target=b9}cd=cd==null?[b6]:bI.makeArray(cd,[b6]);cg=bI.event.special[ch]||{};if(!ck&&cg.trigger&&cg.trigger.apply(b9,cd)===false){return}if(!ck&&!cg.noBubble&&!bI.isWindow(b9)){cj=cg.delegateType||ch;if(!bC.test(cj+ch)){ci=ci.parentNode}for(;ci;ci=ci.parentNode){ca.push(ci);cc=ci}if(cc===(b9.ownerDocument||n)){ca.push(cc.defaultView||cc.parentWindow||a5)}}cb=0;while((ci=ca[cb++])&&!b6.isPropagationStopped()){b6.type=cb>1?cj:cg.bindType||ch;ce=(bI._data(ci,"events")||{})[b6.type]&&bI._data(ci,"handle");if(ce){ce.apply(ci,cd)}ce=b8&&ci[b8];if(ce&&ce.apply&&bI.acceptData(ci)){b6.result=ce.apply(ci,cd);if(b6.result===false){b6.preventDefault()}}}b6.type=ch;if(!ck&&!b6.isDefaultPrevented()){if((!cg._default||cg._default.apply(ca.pop(),cd)===false)&&bI.acceptData(b9)){if(b8&&b9[ch]&&!bI.isWindow(b9)){cc=b9[b8];if(cc){b9[b8]=null}bI.event.triggered=ch;try{b9[ch]()}catch(cf){}bI.event.triggered=undefined;if(cc){b9[b8]=cc}}}}return b6.result},dispatch:function(e){e=bI.event.fix(e);var b9,ca,ce,b6,b8,cd=[],cc=P.call(arguments),b7=(bI._data(this,"events")||{})[e.type]||[],cb=bI.event.special[e.type]||{};cc[0]=e;e.delegateTarget=this;if(cb.preDispatch&&cb.preDispatch.call(this,e)===false){return}cd=bI.event.handlers.call(this,e,b7);b9=0;while((b6=cd[b9++])&&!e.isPropagationStopped()){e.currentTarget=b6.elem;b8=0;while((ce=b6.handlers[b8++])&&!e.isImmediatePropagationStopped()){if(!e.namespace_re||e.namespace_re.test(ce.namespace)){e.handleObj=ce;e.data=ce.data;ca=((bI.event.special[ce.origType]||{}).handle||ce.handler).apply(b6.elem,cc);if(ca!==undefined){if((e.result=ca)===false){e.preventDefault();e.stopPropagation()}}}}}if(cb.postDispatch){cb.postDispatch.call(this,e)}return e.result},handlers:function(e,b7){var b6,cc,ca,b9,cb=[],b8=b7.delegateCount,cd=e.target;if(b8&&cd.nodeType&&(!e.button||e.type!=="click")){for(;cd!=this;cd=cd.parentNode||this){if(cd.nodeType===1&&(cd.disabled!==true||e.type!=="click")){ca=[];for(b9=0;b9=0:bI.find(b6,this,null,[cd]).length}if(ca[b6]){ca.push(cc)}}if(ca.length){cb.push({elem:cd,handlers:ca})}}}}if(b8]","i"),b5=/^\s+/,aH=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,o=/<([\w:]+)/,b0=/\s*$/g,W={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:D.htmlSerialize?[0,"",""]:[1,"X
","
"]},aT=B(n),k=aT.appendChild(n.createElement("div"));W.optgroup=W.option;W.tbody=W.tfoot=W.colgroup=W.caption=W.thead;W.th=W.td;function l(b8,e){var b6,b9,b7=0,ca=typeof b8.getElementsByTagName!==aC?b8.getElementsByTagName(e||"*"):typeof b8.querySelectorAll!==aC?b8.querySelectorAll(e||"*"):undefined;if(!ca){for(ca=[],b6=b8.childNodes||b8;(b9=b6[b7])!=null;b7++){if(!e||bI.nodeName(b9,e)){ca.push(b9)}else{bI.merge(ca,l(b9,e))}}}return e===undefined||e&&bI.nodeName(b8,e)?bI.merge([b8],ca):ca}function bY(e){if(aM.test(e.type)){e.defaultChecked=e.checked}}function a3(i,e){return bI.nodeName(i,"table")&&bI.nodeName(e.nodeType!==11?e:e.firstChild,"tr")?i.getElementsByTagName("tbody")[0]||i.appendChild(i.ownerDocument.createElement("tbody")):i}function u(e){e.type=(bI.find.attr(e,"type")!==null)+"/"+e.type;return e}function bf(i){var e=ar.exec(i.type);if(e){i.type=e[1]}else{i.removeAttribute("type")}return i}function bu(e,b7){var b8,b6=0;for(;(b8=e[b6])!=null;b6++){bI._data(b8,"globalEval",!b7||bI._data(b7[b6],"globalEval"))}}function at(cc,b6){if(b6.nodeType!==1||!bI.hasData(cc)){return}var b9,b8,e,cb=bI._data(cc),ca=bI._data(b6,cb),b7=cb.events;if(b7){delete ca.handle;ca.events={};for(b9 in b7){for(b8=0,e=b7[b9].length;b8")){cd=b6.cloneNode(true)}else{k.innerHTML=b6.outerHTML;k.removeChild(cd=k.firstChild)}if((!D.noCloneEvent||!D.noCloneChecked)&&(b6.nodeType===1||b6.nodeType===11)&&!bI.isXMLDoc(b6)){ca=l(cd);cb=l(b6);for(b9=0;(b7=cb[b9])!=null;++b9){if(ca[b9]){T(b7,ca[b9])}}}if(b8){if(e){cb=cb||l(b6);ca=ca||l(cd);for(b9=0;(b7=cb[b9])!=null;b9++){at(b7,ca[b9])}}else{at(b6,cd)}}ca=l(cd,"script");if(ca.length>0){bu(ca,!cc&&l(b6,"script"))}ca=cb=b7=null;return cd},buildFragment:function(b6,b8,cd,ci){var ce,ca,cc,ch,cj,cg,b7,cb=b6.length,b9=B(b8),e=[],cf=0;for(;cf")+b7[2];ce=b7[0];while(ce--){ch=ch.lastChild}if(!D.leadingWhitespace&&b5.test(ca)){e.push(b8.createTextNode(b5.exec(ca)[0]))}if(!D.tbody){ca=cj==="table"&&!b0.test(ca)?ch.firstChild:b7[1]===""&&!b0.test(ca)?ch:0;ce=ca&&ca.childNodes.length;while(ce--){if(bI.nodeName((cg=ca.childNodes[ce]),"tbody")&&!cg.childNodes.length){ca.removeChild(cg)}}}bI.merge(e,ch.childNodes);ch.textContent="";while(ch.firstChild){ch.removeChild(ch.firstChild)}ch=b9.lastChild}}}}if(ch){b9.removeChild(ch)}if(!D.appendChecked){bI.grep(l(e,"input"),bY)}cf=0;while((ca=e[cf++])){if(ci&&bI.inArray(ca,ci)!==-1){continue}cc=bI.contains(ca.ownerDocument,ca);ch=l(b9.appendChild(ca),"script");if(cc){bu(ch)}if(cd){ce=0;while((ca=ch[ce++])){if(bB.test(ca.type||"")){cd.push(ca)}}}}ch=null;return b9},cleanData:function(b6,ce){var b8,cd,b7,b9,ca=0,cf=bI.expando,e=bI.cache,cb=D.deleteExpando,cc=bI.event.special;for(;(b8=b6[ca])!=null;ca++){if(ce||bI.acceptData(b8)){b7=b8[cf];b9=b7&&e[b7];if(b9){if(b9.events){for(cd in b9.events){if(cc[cd]){bI.event.remove(b8,cd)}else{bI.removeEvent(b8,cd,b9.handle)}}}if(e[b7]){delete e[b7];if(cb){delete b8[cf]}else{if(typeof b8.removeAttribute!==aC){b8.removeAttribute(cf)}else{b8[cf]=null}}aP.push(b7)}}}}}});bI.fn.extend({text:function(e){return aB(this,function(i){return i===undefined?bI.text(this):this.empty().append((this[0]&&this[0].ownerDocument||n).createTextNode(i))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var i=a3(this,e);i.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var i=a3(this,e);i.insertBefore(e,i.firstChild)}})},before:function(){return this.domManip(arguments,function(e){if(this.parentNode){this.parentNode.insertBefore(e,this)}})},after:function(){return this.domManip(arguments,function(e){if(this.parentNode){this.parentNode.insertBefore(e,this.nextSibling)}})},remove:function(e,b9){var b8,b6=e?bI.filter(e,this):this,b7=0;for(;(b8=b6[b7])!=null;b7++){if(!b9&&b8.nodeType===1){bI.cleanData(l(b8))}if(b8.parentNode){if(b9&&bI.contains(b8.ownerDocument,b8)){bu(l(b8,"script"))}b8.parentNode.removeChild(b8)}}return this},empty:function(){var b6,e=0;for(;(b6=this[e])!=null;e++){if(b6.nodeType===1){bI.cleanData(l(b6,false))}while(b6.firstChild){b6.removeChild(b6.firstChild)}if(b6.options&&bI.nodeName(b6,"select")){b6.options.length=0}}return this},clone:function(i,e){i=i==null?false:i;e=e==null?i:e;return this.map(function(){return bI.clone(this,i,e)})},html:function(e){return aB(this,function(b9){var b8=this[0]||{},b7=0,b6=this.length;if(b9===undefined){return b8.nodeType===1?b8.innerHTML.replace(aD,""):undefined}if(typeof b9==="string"&&!an.test(b9)&&(D.htmlSerialize||!M.test(b9))&&(D.leadingWhitespace||!b5.test(b9))&&!W[(o.exec(b9)||["",""])[1].toLowerCase()]){b9=b9.replace(aH,"<$1>");try{for(;b71&&typeof ce==="string"&&!D.checkClone&&bW.test(ce))){return this.each(function(cj){var i=cf.eq(cj);if(b6){cd[0]=ce.call(this,cj,i.html())}i.domManip(cd,ci)})}if(b8){cc=bI.buildFragment(cd,this[0].ownerDocument,false,this);cb=cc.firstChild;if(cc.childNodes.length===1){cc=cb}if(cb){b9=bI.map(l(cc,"script"),u);e=b9.length;for(;ca")).appendTo(i.documentElement);i=(aI[0].contentWindow||aI[0].contentDocument).document;i.write();i.close();e=a4(b6,i);aI.detach()}bl[b6]=e}return e}(function(){var e;D.shrinkWrapBlocks=function(){if(e!=null){return e}e=false;var b7,i,b6;i=n.getElementsByTagName("body")[0];if(!i||!i.style){return}b7=n.createElement("div");b6=n.createElement("div");b6.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(b6).appendChild(b7);if(typeof b7.style.zoom!==aC){b7.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1";b7.appendChild(n.createElement("div")).style.width="5px";e=b7.offsetWidth!==3}i.removeChild(b6);return e}})();var aZ=(/^margin/);var Y=new RegExp("^("+aE+")(?!px)[a-z%]+$","i");var bq,G,bo=/^(top|right|bottom|left)$/;if(a5.getComputedStyle){bq=function(e){if(e.ownerDocument.defaultView.opener){return e.ownerDocument.defaultView.getComputedStyle(e,null)}return a5.getComputedStyle(e,null)};G=function(cb,i,ca){var b8,b7,b9,e,b6=cb.style;ca=ca||bq(cb);e=ca?ca.getPropertyValue(i)||ca[i]:undefined;if(ca){if(e===""&&!bI.contains(cb.ownerDocument,cb)){e=bI.style(cb,i)}if(Y.test(e)&&aZ.test(i)){b8=b6.width;b7=b6.minWidth;b9=b6.maxWidth;b6.minWidth=b6.maxWidth=b6.width=e;e=ca.width;b6.width=b8;b6.minWidth=b7;b6.maxWidth=b9}}return e===undefined?e:e+""}}else{if(n.documentElement.currentStyle){bq=function(e){return e.currentStyle};G=function(ca,b7,b9){var cb,i,e,b6,b8=ca.style;b9=b9||bq(ca);b6=b9?b9[b7]:undefined;if(b6==null&&b8&&b8[b7]){b6=b8[b7]}if(Y.test(b6)&&!bo.test(b7)){cb=b8.left;i=ca.runtimeStyle;e=i&&i.left;if(e){i.left=ca.currentStyle.left}b8.left=b7==="fontSize"?"1em":b6;b6=b8.pixelLeft+"px";b8.left=cb;if(e){i.left=e}}return b6===undefined?b6:b6+""||"auto"}}}function a7(e,i){return{get:function(){var b6=e();if(b6==null){return}if(b6){delete this.get;return}return(this.get=i).apply(this,arguments)}}}(function(){var cb,b9,b7,ca,b6,b8,i;cb=n.createElement("div");cb.innerHTML="
a";b7=cb.getElementsByTagName("a")[0];b9=b7&&b7.style;if(!b9){return}b9.cssText="float:left;opacity:.5";D.opacity=b9.opacity==="0.5";D.cssFloat=!!b9.cssFloat;cb.style.backgroundClip="content-box";cb.cloneNode(true).style.backgroundClip="";D.clearCloneStyle=cb.style.backgroundClip==="content-box";D.boxSizing=b9.boxSizing===""||b9.MozBoxSizing===""||b9.WebkitBoxSizing==="";bI.extend(D,{reliableHiddenOffsets:function(){if(b8==null){e()}return b8},boxSizingReliable:function(){if(b6==null){e()}return b6},pixelPosition:function(){if(ca==null){e()}return ca},reliableMarginRight:function(){if(i==null){e()}return i}});function e(){var cf,cc,cd,ce;cc=n.getElementsByTagName("body")[0];if(!cc||!cc.style){return}cf=n.createElement("div");cd=n.createElement("div");cd.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";cc.appendChild(cd).appendChild(cf);cf.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";ca=b6=false;i=true;if(a5.getComputedStyle){ca=(a5.getComputedStyle(cf,null)||{}).top!=="1%";b6=(a5.getComputedStyle(cf,null)||{width:"4px"}).width==="4px";ce=cf.appendChild(n.createElement("div"));ce.style.cssText=cf.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";ce.style.marginRight=ce.style.width="0";cf.style.width="1px";i=!parseFloat((a5.getComputedStyle(ce,null)||{}).marginRight);cf.removeChild(ce)}cf.innerHTML="
t
";ce=cf.getElementsByTagName("td");ce[0].style.cssText="margin:0;border:0;padding:0;display:none";b8=ce[0].offsetHeight===0;if(b8){ce[0].style.display="";ce[1].style.display="none";b8=ce[0].offsetHeight===0}cc.removeChild(cd)}})();bI.swap=function(b9,b8,ca,b7){var b6,i,e={};for(i in b8){e[i]=b9.style[i];b9.style[i]=b8[i]}b6=ca.apply(b9,b7||[]);for(i in b8){b9.style[i]=e[i]}return b6};var bj=/alpha\([^)]*\)/i,aU=/opacity\s*=\s*([^)]*)/,H=/^(none|table(?!-c[ea]).+)/,bb=new RegExp("^("+aE+")(.*)$","i"),V=new RegExp("^([+-])=("+aE+")","i"),be={position:"absolute",visibility:"hidden",display:"block"},bD={letterSpacing:"0",fontWeight:"400"},aw=["Webkit","O","Moz","ms"];function c(b8,b6){if(b6 in b8){return b6}var b9=b6.charAt(0).toUpperCase()+b6.slice(1),e=b6,b7=aw.length;while(b7--){b6=aw[b7]+b9;if(b6 in b8){return b6}}return e}function s(ca,e){var cb,b8,b9,i=[],b6=0,b7=ca.length;for(;b6=1||b9==="")&&bI.trim(b6.replace(bj,""))===""&&b7.removeAttribute){b7.removeAttribute("filter");if(b9===""||i&&!i.filter){return}}b7.filter=bj.test(b6)?b6.replace(bj,e):b6+" "+e}}}bI.cssHooks.marginRight=a7(D.reliableMarginRight,function(i,e){if(e){return bI.swap(i,{display:"inline-block"},G,[i,"marginRight"])}});bI.each({margin:"",padding:"",border:"Width"},function(e,i){bI.cssHooks[e+i]={expand:function(b8){var b7=0,b6={},b9=typeof b8==="string"?b8.split(" "):[b8];for(;b7<4;b7++){b6[e+bT[b7]+i]=b9[b7]||b9[b7-2]||b9[0]}return b6}};if(!aZ.test(e)){bI.cssHooks[e+i].set=aN}});bI.fn.extend({css:function(e,i){return aB(this,function(ca,b7,cb){var b9,b6,cc={},b8=0;if(bI.isArray(b7)){b9=bq(ca);b6=b7.length;for(;b81)},show:function(){return s(this,true)},hide:function(){return s(this)},toggle:function(e){if(typeof e==="boolean"){return e?this.show():this.hide()}return this.each(function(){if(S(this)){bI(this).show()}else{bI(this).hide()}})}});function J(b6,i,b8,e,b7){return new J.prototype.init(b6,i,b8,e,b7)}bI.Tween=J;J.prototype={constructor:J,init:function(b7,i,b9,e,b8,b6){this.elem=b7;this.prop=b9;this.easing=b8||"swing";this.options=i;this.start=this.now=this.cur();this.end=e;this.unit=b6||(bI.cssNumber[b9]?"":"px")},cur:function(){var e=J.propHooks[this.prop];return e&&e.get?e.get(this):J.propHooks._default.get(this)},run:function(b6){var i,e=J.propHooks[this.prop];if(this.options.duration){this.pos=i=bI.easing[this.easing](b6,this.options.duration*b6,0,1,this.options.duration)}else{this.pos=i=b6}this.now=(this.end-this.start)*i+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(e&&e.set){e.set(this)}else{J.propHooks._default.set(this)}return this}};J.prototype.init.prototype=J.prototype;J.propHooks={_default:{get:function(i){var e;if(i.elem[i.prop]!=null&&(!i.elem.style||i.elem.style[i.prop]==null)){return i.elem[i.prop]}e=bI.css(i.elem,i.prop,"");return !e||e==="auto"?0:e},set:function(e){if(bI.fx.step[e.prop]){bI.fx.step[e.prop](e)}else{if(e.elem.style&&(e.elem.style[bI.cssProps[e.prop]]!=null||bI.cssHooks[e.prop])){bI.style(e.elem,e.prop,e.now+e.unit)}else{e.elem[e.prop]=e.now}}}}};J.propHooks.scrollTop=J.propHooks.scrollLeft={set:function(e){if(e.elem.nodeType&&e.elem.parentNode){e.elem[e.prop]=e.now}}};bI.easing={linear:function(e){return e},swing:function(e){return 0.5-Math.cos(e*Math.PI)/2}};bI.fx=J.prototype.init;bI.fx.step={};var N,ae,bR=/^(?:toggle|show|hide)$/,bJ=new RegExp("^(?:([+-])=|)("+aE+")([a-z%]*)$","i"),bP=/queueHooks$/,aG=[h],a2={"*":[function(e,ca){var cc=this.createTween(e,ca),b8=cc.cur(),b7=bJ.exec(ca),cb=b7&&b7[3]||(bI.cssNumber[e]?"":"px"),i=(bI.cssNumber[e]||cb!=="px"&&+b8)&&bJ.exec(bI.css(cc.elem,e)),b6=1,b9=20;if(i&&i[3]!==cb){cb=cb||i[3];b7=b7||[];i=+b8||1;do{b6=b6||".5";i=i/b6;bI.style(cc.elem,e,i+cb)}while(b6!==(b6=cc.cur()/b8)&&b6!==1&&--b9)}if(b7){i=cc.start=+i||+b8||0;cc.unit=cb;cc.end=b7[1]?i+(b7[1]+1)*b7[2]:+b7[2]}return cc}]};function bn(){setTimeout(function(){N=undefined});return(N=bI.now())}function bH(b7,b9){var b8,e={height:b7},b6=0;b9=b9?1:0;for(;b6<4;b6+=2-b9){b8=bT[b6];e["margin"+b8]=e["padding"+b8]=b7}if(b9){e.opacity=e.width=b7}return e}function bd(b8,ca,b7){var i,b9=(a2[ca]||[]).concat(a2["*"]),e=0,b6=b9.length;for(;e
a";i=b8.getElementsByTagName("a")[0];e=n.createElement("select");b7=e.appendChild(n.createElement("option"));b6=b8.getElementsByTagName("input")[0];i.style.cssText="top:1px";D.getSetAttribute=b8.className!=="t";D.style=/top/.test(i.getAttribute("style"));D.hrefNormalized=i.getAttribute("href")==="/a";D.checkOn=!!b6.value;D.optSelected=b7.selected;D.enctype=!!n.createElement("form").enctype;e.disabled=true;D.optDisabled=!b7.disabled;b6=n.createElement("input");b6.setAttribute("value","");D.input=b6.getAttribute("value")==="";b6.value="t";b6.setAttribute("type","radio");D.radioValue=b6.value==="t"})();var al=/\r/g;bI.fn.extend({val:function(b7){var e,i,b8,b6=this[0];if(!arguments.length){if(b6){e=bI.valHooks[b6.type]||bI.valHooks[b6.nodeName.toLowerCase()];if(e&&"get" in e&&(i=e.get(b6,"value"))!==undefined){return i}i=b6.value;return typeof i==="string"?i.replace(al,""):i==null?"":i}return}b8=bI.isFunction(b7);return this.each(function(b9){var ca;if(this.nodeType!==1){return}if(b8){ca=b7.call(this,b9,bI(this).val())}else{ca=b7}if(ca==null){ca=""}else{if(typeof ca==="number"){ca+=""}else{if(bI.isArray(ca)){ca=bI.map(ca,function(cb){return cb==null?"":cb+""})}}}e=bI.valHooks[this.type]||bI.valHooks[this.nodeName.toLowerCase()];if(!e||!("set" in e)||e.set(this,ca,"value")===undefined){this.value=ca}})}});bI.extend({valHooks:{option:{get:function(e){var i=bI.find.attr(e,"value");return i!=null?i:bI.trim(bI.text(e))}},select:{get:function(e){var cb,b7,cd=e.options,b9=e.selectedIndex,b8=e.type==="select-one"||b9<0,cc=b8?null:[],ca=b8?b9+1:cd.length,b6=b9<0?ca:b8?b9:0;for(;b6=0){try{b9.selected=cc=true}catch(b6){b9.scrollHeight}}else{b9.selected=false}}if(!cc){ca.selectedIndex=-1}return b7}}}});bI.each(["radio","checkbox"],function(){bI.valHooks[this]={set:function(e,i){if(bI.isArray(i)){return(e.checked=bI.inArray(bI(e).val(),i)>=0)}}};if(!D.checkOn){bI.valHooks[this].get=function(e){return e.getAttribute("value")===null?"on":e.value}}});var ba,b3,bO=bI.expr.attrHandle,aq=/^(?:checked|selected)$/i,bN=D.getSetAttribute,bF=D.input;bI.fn.extend({attr:function(e,i){return aB(this,bI.attr,e,i,arguments.length>1)},removeAttr:function(e){return this.each(function(){bI.removeAttr(this,e)})}});bI.extend({attr:function(b8,b7,b9){var e,b6,i=b8.nodeType;if(!b8||i===3||i===8||i===2){return}if(typeof b8.getAttribute===aC){return bI.prop(b8,b7,b9)}if(i!==1||!bI.isXMLDoc(b8)){b7=b7.toLowerCase();e=bI.attrHooks[b7]||(bI.expr.match.bool.test(b7)?b3:ba)}if(b9!==undefined){if(b9===null){bI.removeAttr(b8,b7)}else{if(e&&"set" in e&&(b6=e.set(b8,b9,b7))!==undefined){return b6}else{b8.setAttribute(b7,b9+"");return b9}}}else{if(e&&"get" in e&&(b6=e.get(b8,b7))!==null){return b6}else{b6=bI.find.attr(b8,b7);return b6==null?undefined:b6}}},removeAttr:function(b7,b9){var e,b8,b6=0,ca=b9&&b9.match(aF);if(ca&&b7.nodeType===1){while((e=ca[b6++])){b8=bI.propFix[e]||e;if(bI.expr.match.bool.test(e)){if(bF&&bN||!aq.test(e)){b7[b8]=false}else{b7[bI.camelCase("default-"+e)]=b7[b8]=false}}else{bI.attr(b7,e,"")}b7.removeAttribute(bN?e:b8)}}},attrHooks:{type:{set:function(e,i){if(!D.radioValue&&i==="radio"&&bI.nodeName(e,"input")){var b6=e.value;e.setAttribute("type",i);if(b6){e.value=b6}return i}}}}});b3={set:function(i,b6,e){if(b6===false){bI.removeAttr(i,e)}else{if(bF&&bN||!aq.test(e)){i.setAttribute(!bN&&bI.propFix[e]||e,e)}else{i[bI.camelCase("default-"+e)]=i[e]=true}}return e}};bI.each(bI.expr.match.bool.source.match(/\w+/g),function(b7,b6){var e=bO[b6]||bI.find.attr;bO[b6]=bF&&bN||!aq.test(b6)?function(b9,b8,cb){var i,ca;if(!cb){ca=bO[b8];bO[b8]=i;i=e(b9,b8,cb)!=null?b8.toLowerCase():null;bO[b8]=ca}return i}:function(b8,i,b9){if(!b9){return b8[bI.camelCase("default-"+i)]?i.toLowerCase():null}}});if(!bF||!bN){bI.attrHooks.value={set:function(i,b6,e){if(bI.nodeName(i,"input")){i.defaultValue=b6}else{return ba&&ba.set(i,b6,e)}}}}if(!bN){ba={set:function(b6,b7,i){var e=b6.getAttributeNode(i);if(!e){b6.setAttributeNode((e=b6.ownerDocument.createAttribute(i)))}e.value=b7+="";if(i==="value"||b7===b6.getAttribute(i)){return b7}}};bO.id=bO.name=bO.coords=function(b6,i,b7){var e;if(!b7){return(e=b6.getAttributeNode(i))&&e.value!==""?e.value:null}};bI.valHooks.button={get:function(b6,i){var e=b6.getAttributeNode(i);if(e&&e.specified){return e.value}},set:ba.set};bI.attrHooks.contenteditable={set:function(i,b6,e){ba.set(i,b6===""?false:b6,e)}};bI.each(["width","height"],function(b6,e){bI.attrHooks[e]={set:function(i,b7){if(b7===""){i.setAttribute(e,"auto");return b7}}}})}if(!D.style){bI.attrHooks.style={get:function(e){return e.style.cssText||undefined},set:function(e,i){return(e.style.cssText=i+"")}}}var aJ=/^(?:input|select|textarea|button|object)$/i,F=/^(?:a|area)$/i;bI.fn.extend({prop:function(e,i){return aB(this,bI.prop,e,i,arguments.length>1)},removeProp:function(e){e=bI.propFix[e]||e;return this.each(function(){try{this[e]=undefined;delete this[e]}catch(i){}})}});bI.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(b9,b7,ca){var b6,e,b8,i=b9.nodeType;if(!b9||i===3||i===8||i===2){return}b8=i!==1||!bI.isXMLDoc(b9);if(b8){b7=bI.propFix[b7]||b7;e=bI.propHooks[b7]}if(ca!==undefined){return e&&"set" in e&&(b6=e.set(b9,ca,b7))!==undefined?b6:(b9[b7]=ca)}else{return e&&"get" in e&&(b6=e.get(b9,b7))!==null?b6:b9[b7]}},propHooks:{tabIndex:{get:function(i){var e=bI.find.attr(i,"tabindex");return e?parseInt(e,10):aJ.test(i.nodeName)||F.test(i.nodeName)&&i.href?0:-1}}}});if(!D.hrefNormalized){bI.each(["href","src"],function(b6,e){bI.propHooks[e]={get:function(i){return i.getAttribute(e,4)}}})}if(!D.optSelected){bI.propHooks.selected={get:function(i){var e=i.parentNode;if(e){e.selectedIndex;if(e.parentNode){e.parentNode.selectedIndex}}return null}}}bI.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){bI.propFix[this.toLowerCase()]=this});if(!D.enctype){bI.propFix.enctype="encoding"}var bL=/[\t\r\n\f]/g;bI.fn.extend({addClass:function(cd){var b7,b6,ce,cb,b8,e,b9=0,ca=this.length,cc=typeof cd==="string"&&cd;if(bI.isFunction(cd)){return this.each(function(i){bI(this).addClass(cd.call(this,i,this.className))})}if(cc){b7=(cd||"").match(aF)||[];for(;b9=0){ce=ce.replace(" "+cb+" "," ")}}e=cd?bI.trim(ce):"";if(b6.className!==e){b6.className=e}}}}return this},toggleClass:function(b6,e){var i=typeof b6;if(typeof e==="boolean"&&i==="string"){return e?this.addClass(b6):this.removeClass(b6)}if(bI.isFunction(b6)){return this.each(function(b7){bI(this).toggleClass(b6.call(this,b7,this.className,e),e)})}return this.each(function(){if(i==="string"){var b9,b8=0,b7=bI(this),ca=b6.match(aF)||[];while((b9=ca[b8++])){if(b7.hasClass(b9)){b7.removeClass(b9)}else{b7.addClass(b9)}}}else{if(i===aC||i==="boolean"){if(this.className){bI._data(this,"__className__",this.className)}this.className=this.className||b6===false?"":bI._data(this,"__className__")||""}}})},hasClass:function(e){var b8=" "+e+" ",b7=0,b6=this.length;for(;b7=0){return true}}return false}});bI.each(("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu").split(" "),function(b6,e){bI.fn[e]=function(b7,i){return arguments.length>0?this.on(e,null,b7,i):this.trigger(e)}});bI.fn.extend({hover:function(e,i){return this.mouseenter(e).mouseleave(i||e)},bind:function(e,b6,i){return this.on(e,null,b6,i)},unbind:function(e,i){return this.off(e,null,i)},delegate:function(e,i,b7,b6){return this.on(i,e,b7,b6)},undelegate:function(e,i,b6){return arguments.length===1?this.off(e,"**"):this.off(i,e||"**",b6)}});var bp=bI.now();var bQ=(/\?/);var a1=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;bI.parseJSON=function(e){if(a5.JSON&&a5.JSON.parse){return a5.JSON.parse(e+"")}var b7,b6=null,i=bI.trim(e+"");return i&&!bI.trim(i.replace(a1,function(ca,b8,b9,cb){if(b7&&b8){b6=0}if(b6===0){return ca}b7=b9||b8;b6+=!cb-!b9;return""}))?(Function("return "+i))():bI.error("Invalid JSON: "+e)};bI.parseXML=function(b7){var i,b6;if(!b7||typeof b7!=="string"){return null}try{if(a5.DOMParser){b6=new DOMParser();i=b6.parseFromString(b7,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(b7)}}catch(b8){i=undefined}if(!i||!i.documentElement||i.getElementsByTagName("parsererror").length){bI.error("Invalid XML: "+b7)}return i};var b4,aa,ap=/#.*$/,R=/([?&])_=[^&]*/,ah=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,C=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,r=/^(?:GET|HEAD)$/,aK=/^\/\//,aV=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,w={},a9={},aX="*/".concat("*");try{aa=location.href}catch(bi){aa=n.createElement("a");aa.href="";aa=aa.href}b4=aV.exec(aa.toLowerCase())||[];function bK(e){return function(b9,ca){if(typeof b9!=="string"){ca=b9;b9="*"}var b6,b7=0,b8=b9.toLowerCase().match(aF)||[];if(bI.isFunction(ca)){while((b6=b8[b7++])){if(b6.charAt(0)==="+"){b6=b6.slice(1)||"*";(e[b6]=e[b6]||[]).unshift(ca)}else{(e[b6]=e[b6]||[]).push(ca)}}}}}function p(e,b6,ca,b7){var i={},b8=(e===a9);function b9(cb){var cc;i[cb]=true;bI.each(e[cb]||[],function(ce,cd){var cf=cd(b6,ca,b7);if(typeof cf==="string"&&!b8&&!i[cf]){b6.dataTypes.unshift(cf);b9(cf);return false}else{if(b8){return !(cc=cf)}}});return cc}return b9(b6.dataTypes[0])||!i["*"]&&b9("*")}function t(b6,b7){var e,i,b8=bI.ajaxSettings.flatOptions||{};for(i in b7){if(b7[i]!==undefined){(b8[i]?b6:(e||(e={})))[i]=b7[i]}}if(e){bI.extend(true,b6,e)}return b6}function g(cc,cb,b8){var e,b7,b6,b9,i=cc.contents,ca=cc.dataTypes;while(ca[0]==="*"){ca.shift();if(b7===undefined){b7=cc.mimeType||cb.getResponseHeader("Content-Type")}}if(b7){for(b9 in i){if(i[b9]&&i[b9].test(b7)){ca.unshift(b9);break}}}if(ca[0] in b8){b6=ca[0]}else{for(b9 in b8){if(!ca[0]||cc.converters[b9+" "+ca[0]]){b6=b9;break}if(!e){e=b9}}b6=b6||e}if(b6){if(b6!==ca[0]){ca.unshift(b6)}return b8[b6]}}function ag(cg,b8,cd,b6){var i,cb,ce,b9,b7,cf={},cc=cg.dataTypes.slice();if(cc[1]){for(ce in cg.converters){cf[ce.toLowerCase()]=cg.converters[ce]}}cb=cc.shift();while(cb){if(cg.responseFields[cb]){cd[cg.responseFields[cb]]=b8}if(!b7&&b6&&cg.dataFilter){b8=cg.dataFilter(b8,cg.dataType)}b7=cb;cb=cc.shift();if(cb){if(cb==="*"){cb=b7}else{if(b7!=="*"&&b7!==cb){ce=cf[b7+" "+cb]||cf["* "+cb];if(!ce){for(i in cf){b9=i.split(" ");if(b9[1]===cb){ce=cf[b7+" "+b9[0]]||cf["* "+b9[0]];if(ce){if(ce===true){ce=cf[i]}else{if(cf[i]!==true){cb=b9[0];cc.unshift(b9[1])}}break}}}}if(ce!==true){if(ce&&cg["throws"]){b8=ce(b8)}else{try{b8=ce(b8)}catch(ca){return{state:"parsererror",error:ce?ca:"No conversion from "+b7+" to "+cb}}}}}}}}return{state:"success",data:b8}}bI.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:aa,type:"GET",isLocal:C.test(b4[1]),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":aX,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":true,"text json":bI.parseJSON,"text xml":bI.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(i,e){return e?t(t(i,bI.ajaxSettings),e):t(bI.ajaxSettings,i)},ajaxPrefilter:bK(w),ajaxTransport:bK(a9),ajax:function(ca,b7){if(typeof ca==="object"){b7=ca;ca=undefined}b7=b7||{};var cj,cl,cb,cq,cf,b6,cm,b8,ce=bI.ajaxSetup({},b7),cs=ce.context||ce,ch=ce.context&&(cs.nodeType||cs.jquery)?bI(cs):bI.event,cr=bI.Deferred(),co=bI.Callbacks("once memory"),cc=ce.statusCode||{},ci={},cp={},b9=0,cd="canceled",ck={readyState:0,getResponseHeader:function(i){var e;if(b9===2){if(!b8){b8={};while((e=ah.exec(cq))){b8[e[1].toLowerCase()]=e[2]}}e=b8[i.toLowerCase()]}return e==null?null:e},getAllResponseHeaders:function(){return b9===2?cq:null},setRequestHeader:function(i,ct){var e=i.toLowerCase();if(!b9){i=cp[e]=cp[e]||i;ci[i]=ct}return this},overrideMimeType:function(e){if(!b9){ce.mimeType=e}return this},statusCode:function(i){var e;if(i){if(b9<2){for(e in i){cc[e]=[cc[e],i[e]]}}else{ck.always(i[ck.status])}}return this},abort:function(i){var e=i||cd;if(cm){cm.abort(e)}cg(0,e);return this}};cr.promise(ck).complete=co.add;ck.success=ck.done;ck.error=ck.fail;ce.url=((ca||ce.url||aa)+"").replace(ap,"").replace(aK,b4[1]+"//");ce.type=b7.method||b7.type||ce.method||ce.type;ce.dataTypes=bI.trim(ce.dataType||"*").toLowerCase().match(aF)||[""];if(ce.crossDomain==null){cj=aV.exec(ce.url.toLowerCase());ce.crossDomain=!!(cj&&(cj[1]!==b4[1]||cj[2]!==b4[2]||(cj[3]||(cj[1]==="http:"?"80":"443"))!==(b4[3]||(b4[1]==="http:"?"80":"443"))))}if(ce.data&&ce.processData&&typeof ce.data!=="string"){ce.data=bI.param(ce.data,ce.traditional)}p(w,ce,b7,ck);if(b9===2){return ck}b6=bI.event&&ce.global;if(b6&&bI.active++===0){bI.event.trigger("ajaxStart")}ce.type=ce.type.toUpperCase();ce.hasContent=!r.test(ce.type);cb=ce.url;if(!ce.hasContent){if(ce.data){cb=(ce.url+=(bQ.test(cb)?"&":"?")+ce.data);delete ce.data}if(ce.cache===false){ce.url=R.test(cb)?cb.replace(R,"$1_="+bp++):cb+(bQ.test(cb)?"&":"?")+"_="+bp++}}if(ce.ifModified){if(bI.lastModified[cb]){ck.setRequestHeader("If-Modified-Since",bI.lastModified[cb])}if(bI.etag[cb]){ck.setRequestHeader("If-None-Match",bI.etag[cb])}}if(ce.data&&ce.hasContent&&ce.contentType!==false||b7.contentType){ck.setRequestHeader("Content-Type",ce.contentType)}ck.setRequestHeader("Accept",ce.dataTypes[0]&&ce.accepts[ce.dataTypes[0]]?ce.accepts[ce.dataTypes[0]]+(ce.dataTypes[0]!=="*"?", "+aX+"; q=0.01":""):ce.accepts["*"]);for(cl in ce.headers){ck.setRequestHeader(cl,ce.headers[cl])}if(ce.beforeSend&&(ce.beforeSend.call(cs,ck,ce)===false||b9===2)){return ck.abort()}cd="abort";for(cl in {success:1,error:1,complete:1}){ck[cl](ce[cl])}cm=p(a9,ce,b7,ck);if(!cm){cg(-1,"No Transport")}else{ck.readyState=1;if(b6){ch.trigger("ajaxSend",[ck,ce])}if(ce.async&&ce.timeout>0){cf=setTimeout(function(){ck.abort("timeout")},ce.timeout)}try{b9=1;cm.send(ci,cg)}catch(cn){if(b9<2){cg(-1,cn)}else{throw cn}}}function cg(cw,i,cx,cu){var e,cA,cy,cv,cz,ct=i;if(b9===2){return}b9=2;if(cf){clearTimeout(cf)}cm=undefined;cq=cu||"";ck.readyState=cw>0?4:0;e=cw>=200&&cw<300||cw===304;if(cx){cv=g(ce,ck,cx)}cv=ag(ce,cv,ck,e);if(e){if(ce.ifModified){cz=ck.getResponseHeader("Last-Modified");if(cz){bI.lastModified[cb]=cz}cz=ck.getResponseHeader("etag");if(cz){bI.etag[cb]=cz}}if(cw===204||ce.type==="HEAD"){ct="nocontent"}else{if(cw===304){ct="notmodified"}else{ct=cv.state;cA=cv.data;cy=cv.error;e=!cy}}}else{cy=ct;if(cw||!ct){ct="error";if(cw<0){cw=0}}}ck.status=cw;ck.statusText=(i||ct)+"";if(e){cr.resolveWith(cs,[cA,ct,ck])}else{cr.rejectWith(cs,[ck,ct,cy])}ck.statusCode(cc);cc=undefined;if(b6){ch.trigger(e?"ajaxSuccess":"ajaxError",[ck,ce,e?cA:cy])}co.fireWith(cs,[ck,ct]);if(b6){ch.trigger("ajaxComplete",[ck,ce]);if(!(--bI.active)){bI.event.trigger("ajaxStop")}}}return ck},getJSON:function(e,i,b6){return bI.get(e,i,b6,"json")},getScript:function(e,i){return bI.get(e,undefined,i,"script")}});bI.each(["get","post"],function(e,b6){bI[b6]=function(i,b8,b9,b7){if(bI.isFunction(b8)){b7=b7||b9;b9=b8;b8=undefined}return bI.ajax({url:i,type:b6,dataType:b7,data:b8,success:b9})}});bI._evalUrl=function(e){return bI.ajax({url:e,type:"GET",dataType:"script",async:false,global:false,"throws":true})};bI.fn.extend({wrapAll:function(e){if(bI.isFunction(e)){return this.each(function(b6){bI(this).wrapAll(e.call(this,b6))})}if(this[0]){var i=bI(e,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){i.insertBefore(this[0])}i.map(function(){var b6=this;while(b6.firstChild&&b6.firstChild.nodeType===1){b6=b6.firstChild}return b6}).append(this)}return this},wrapInner:function(e){if(bI.isFunction(e)){return this.each(function(b6){bI(this).wrapInner(e.call(this,b6))})}return this.each(function(){var i=bI(this),b6=i.contents();if(b6.length){b6.wrapAll(e)}else{i.append(e)}})},wrap:function(e){var i=bI.isFunction(e);return this.each(function(b6){bI(this).wrapAll(i?e.call(this,b6):e)})},unwrap:function(){return this.parent().each(function(){if(!bI.nodeName(this,"body")){bI(this).replaceWith(this.childNodes)}}).end()}});bI.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||(!D.reliableHiddenOffsets()&&((e.style&&e.style.display)||bI.css(e,"display"))==="none")};bI.expr.filters.visible=function(e){return !bI.expr.filters.hidden(e)};var bw=/%20/g,aS=/\[\]$/,X=/\r?\n/g,b=/^(?:submit|button|image|reset|file)$/i,au=/^(?:input|select|textarea|keygen)/i;function j(b6,b8,i,b7){var e;if(bI.isArray(b8)){bI.each(b8,function(ca,b9){if(i||aS.test(b6)){b7(b6,b9)}else{j(b6+"["+(typeof b9==="object"?ca:"")+"]",b9,i,b7)}})}else{if(!i&&bI.type(b8)==="object"){for(e in b8){j(b6+"["+e+"]",b8[e],i,b7)}}else{b7(b6,b8)}}}bI.param=function(e,b6){var b7,i=[],b8=function(b9,ca){ca=bI.isFunction(ca)?ca():(ca==null?"":ca);i[i.length]=encodeURIComponent(b9)+"="+encodeURIComponent(ca)};if(b6===undefined){b6=bI.ajaxSettings&&bI.ajaxSettings.traditional}if(bI.isArray(e)||(e.jquery&&!bI.isPlainObject(e))){bI.each(e,function(){b8(this.name,this.value)})}else{for(b7 in e){j(b7,e[b7],b6,b8)}}return i.join("&").replace(bw,"+")};bI.fn.extend({serialize:function(){return bI.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=bI.prop(this,"elements");return e?bI.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!bI(this).is(":disabled")&&au.test(this.nodeName)&&!b.test(e)&&(this.checked||!aM.test(e))}).map(function(e,b6){var b7=bI(this).val();return b7==null?null:bI.isArray(b7)?bI.map(b7,function(i){return{name:b6.name,value:i.replace(X,"\r\n")}}):{name:b6.name,value:b7.replace(X,"\r\n")}}).get()}});bI.ajaxSettings.xhr=a5.ActiveXObject!==undefined?function(){return !this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&bE()||bg()}:bE;var aA=0,aj={},ay=bI.ajaxSettings.xhr();if(a5.attachEvent){a5.attachEvent("onunload",function(){for(var e in aj){aj[e](undefined,true)}})}D.cors=!!ay&&("withCredentials" in ay);ay=D.ajax=!!ay;if(ay){bI.ajaxTransport(function(e){if(!e.crossDomain||D.cors){var i;return{send:function(b9,b6){var b7,b8=e.xhr(),ca=++aA;b8.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields){for(b7 in e.xhrFields){b8[b7]=e.xhrFields[b7]}}if(e.mimeType&&b8.overrideMimeType){b8.overrideMimeType(e.mimeType)}if(!e.crossDomain&&!b9["X-Requested-With"]){b9["X-Requested-With"]="XMLHttpRequest"}for(b7 in b9){if(b9[b7]!==undefined){b8.setRequestHeader(b7,b9[b7]+"")}}b8.send((e.hasContent&&e.data)||null);i=function(cd,cc){var cb,cg,ce;if(i&&(cc||b8.readyState===4)){delete aj[ca];i=undefined;b8.onreadystatechange=bI.noop;if(cc){if(b8.readyState!==4){b8.abort()}}else{ce={};cb=b8.status;if(typeof b8.responseText==="string"){ce.text=b8.responseText}try{cg=b8.statusText}catch(cf){cg=""}if(!cb&&e.isLocal&&!e.crossDomain){cb=ce.text?200:404}else{if(cb===1223){cb=204}}}}if(ce){b6(cb,cg,ce,b8.getAllResponseHeaders())}};if(!e.async){i()}else{if(b8.readyState===4){setTimeout(i)}else{b8.onreadystatechange=aj[ca]=i}}},abort:function(){if(i){i(undefined,true)}}}}})}function bE(){try{return new a5.XMLHttpRequest()}catch(i){}}function bg(){try{return new a5.ActiveXObject("Microsoft.XMLHTTP")}catch(i){}}bI.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){bI.globalEval(e);return e}}});bI.ajaxPrefilter("script",function(e){if(e.cache===undefined){e.cache=false}if(e.crossDomain){e.type="GET";e.global=false}});bI.ajaxTransport("script",function(b6){if(b6.crossDomain){var e,i=n.head||bI("head")[0]||n.documentElement;return{send:function(b7,b8){e=n.createElement("script");e.async=true;if(b6.scriptCharset){e.charset=b6.scriptCharset}e.src=b6.url;e.onload=e.onreadystatechange=function(ca,b9){if(b9||!e.readyState||/loaded|complete/.test(e.readyState)){e.onload=e.onreadystatechange=null;if(e.parentNode){e.parentNode.removeChild(e)}e=null;if(!b9){b8(200,"success")}}};i.insertBefore(e,i.firstChild)},abort:function(){if(e){e.onload(undefined,true)}}}}});var bs=[],a8=/(=)\?(?=&|$)|\?\?/;bI.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=bs.pop()||(bI.expando+"_"+(bp++));this[e]=true;return e}});bI.ajaxPrefilter("json jsonp",function(b7,e,b8){var ca,i,b6,b9=b7.jsonp!==false&&(a8.test(b7.url)?"url":typeof b7.data==="string"&&!(b7.contentType||"").indexOf("application/x-www-form-urlencoded")&&a8.test(b7.data)&&"data");if(b9||b7.dataTypes[0]==="jsonp"){ca=b7.jsonpCallback=bI.isFunction(b7.jsonpCallback)?b7.jsonpCallback():b7.jsonpCallback;if(b9){b7[b9]=b7[b9].replace(a8,"$1"+ca)}else{if(b7.jsonp!==false){b7.url+=(bQ.test(b7.url)?"&":"?")+b7.jsonp+"="+ca}}b7.converters["script json"]=function(){if(!b6){bI.error(ca+" was not called")}return b6[0]};b7.dataTypes[0]="json";i=a5[ca];a5[ca]=function(){b6=arguments};b8.always(function(){a5[ca]=i;if(b7[ca]){b7.jsonpCallback=e.jsonpCallback;bs.push(ca)}if(b6&&bI.isFunction(i)){i(b6[0])}b6=i=undefined});return"script"}});bI.parseHTML=function(b8,b6,b7){if(!b8||typeof b8!=="string"){return null}if(typeof b6==="boolean"){b7=b6;b6=false}b6=b6||n;var i=a.exec(b8),e=!b7&&[];if(i){return[b6.createElement(i[1])]}i=bI.buildFragment([b8],b6,e);if(e&&e.length){bI(e).remove()}return bI.merge([],i.childNodes)};var b1=bI.fn.load;bI.fn.load=function(b7,ca,cb){if(typeof b7!=="string"&&b1){return b1.apply(this,arguments)}var e,b6,b8,i=this,b9=b7.indexOf(" ");if(b9>=0){e=bI.trim(b7.slice(b9,b7.length));b7=b7.slice(0,b9)}if(bI.isFunction(ca)){cb=ca;ca=undefined}else{if(ca&&typeof ca==="object"){b8="POST"}}if(i.length>0){bI.ajax({url:b7,type:b8,dataType:"html",data:ca}).done(function(cc){b6=arguments;i.html(e?bI("
").append(bI.parseHTML(cc)).find(e):cc)}).complete(cb&&function(cd,cc){i.each(cb,b6||[cd.responseText,cc,cd])})}return this};bI.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,b6){bI.fn[b6]=function(i){return this.on(b6,i)}});bI.expr.filters.animated=function(e){return bI.grep(bI.timers,function(i){return e===i.elem}).length};var bX=a5.document.documentElement;function br(e){return bI.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}bI.offset={setOffset:function(b7,ch,cb){var cd,ca,e,b8,b6,cf,cg,cc=bI.css(b7,"position"),b9=bI(b7),ce={};if(cc==="static"){b7.style.position="relative"}b6=b9.offset();e=bI.css(b7,"top");cf=bI.css(b7,"left");cg=(cc==="absolute"||cc==="fixed")&&bI.inArray("auto",[e,cf])>-1;if(cg){cd=b9.position();b8=cd.top;ca=cd.left}else{b8=parseFloat(e)||0;ca=parseFloat(cf)||0}if(bI.isFunction(ch)){ch=ch.call(b7,cb,b6)}if(ch.top!=null){ce.top=(ch.top-b6.top)+b8}if(ch.left!=null){ce.left=(ch.left-b6.left)+ca}if("using" in ch){ch.using.call(b7,ce)}else{b9.css(ce)}}};bI.fn.extend({offset:function(i){if(arguments.length){return i===undefined?this:this.each(function(ca){bI.offset.setOffset(this,i,ca)})}var e,b9,b7={top:0,left:0},b6=this[0],b8=b6&&b6.ownerDocument;if(!b8){return}e=b8.documentElement;if(!bI.contains(e,b6)){return b7}if(typeof b6.getBoundingClientRect!==aC){b7=b6.getBoundingClientRect()}b9=br(b8);return{top:b7.top+(b9.pageYOffset||e.scrollTop)-(e.clientTop||0),left:b7.left+(b9.pageXOffset||e.scrollLeft)-(e.clientLeft||0)}},position:function(){if(!this[0]){return}var b6,b7,e={top:0,left:0},i=this[0];if(bI.css(i,"position")==="fixed"){b7=i.getBoundingClientRect()}else{b6=this.offsetParent();b7=this.offset();if(!bI.nodeName(b6[0],"html")){e=b6.offset()}e.top+=bI.css(b6[0],"borderTopWidth",true);e.left+=bI.css(b6[0],"borderLeftWidth",true)}return{top:b7.top-e.top-bI.css(i,"marginTop",true),left:b7.left-e.left-bI.css(i,"marginLeft",true)}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||bX;while(e&&(!bI.nodeName(e,"html")&&bI.css(e,"position")==="static")){e=e.offsetParent}return e||bX})}});bI.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b6,i){var e=/Y/.test(i);bI.fn[b6]=function(b7){return aB(this,function(b8,cb,ca){var b9=br(b8);if(ca===undefined){return b9?(i in b9)?b9[i]:b9.document.documentElement[cb]:b8[cb]}if(b9){b9.scrollTo(!e?ca:bI(b9).scrollLeft(),e?ca:bI(b9).scrollTop())}else{b8[cb]=ca}},b6,b7,arguments.length,null)}});bI.each(["top","left"],function(e,b6){bI.cssHooks[b6]=a7(D.pixelPosition,function(b7,i){if(i){i=G(b7,b6);return Y.test(i)?bI(b7).position()[b6]+"px":i}})});bI.each({Height:"height",Width:"width"},function(e,i){bI.each({padding:"inner"+e,content:i,"":"outer"+e},function(b6,b7){bI.fn[b7]=function(cb,ca){var b9=arguments.length&&(b6||typeof cb!=="boolean"),b8=b6||(cb===true||ca===true?"margin":"border");return aB(this,function(cd,cc,ce){var cf;if(bI.isWindow(cd)){return cd.document.documentElement["client"+e]}if(cd.nodeType===9){cf=cd.documentElement;return Math.max(cd.body["scroll"+e],cf["scroll"+e],cd.body["offset"+e],cf["offset"+e],cf["client"+e])}return ce===undefined?bI.css(cd,cc,b8):bI.style(cd,cc,ce,b8)},i,b9?cb:undefined,b9,null)}})});bI.fn.size=function(){return this.length};bI.fn.andSelf=bI.fn.addBack;if(typeof define==="function"&&define.amd){define("jquery",[],function(){return bI})}var bk=a5.jQuery,I=a5.$;bI.noConflict=function(e){if(a5.$===bI){a5.$=I}if(e&&a5.jQuery===bI){a5.jQuery=bk}return bI};if(typeof av===aC){a5.jQuery=a5.$=bI}return bI}));!function(a){a(function(){a.support.transition=(function(){var b=(function(){var e=document.createElement("bootstrap"),d={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in d){if(e.style[c]!==undefined){return d[c]}}}());return b&&{end:b}})()})}(window.jQuery);!function(d){var c='[data-dismiss="alert"]',b=function(e){d(e).on("click",c,this.close)};b.prototype.close=function(j){var i=d(this),g=i.attr("data-target"),h;if(!g){g=i.attr("href");g=g&&g.replace(/.*(?=#[^\s]*$)/,"")}h=d(g);j&&j.preventDefault();h.length||(h=i.hasClass("alert")?i:i.parent());h.trigger(j=d.Event("close"));if(j.isDefaultPrevented()){return}h.removeClass("in");function f(){h.trigger("closed").remove()}d.support.transition&&h.hasClass("fade")?h.on(d.support.transition.end,f):f()};var a=d.fn.alert;d.fn.alert=function(e){return this.each(function(){var g=d(this),f=g.data("alert");if(!f){g.data("alert",(f=new b(this)))}if(typeof e=="string"){f[e].call(g)}})};d.fn.alert.Constructor=b;d.fn.alert.noConflict=function(){d.fn.alert=a;return this};d(document).on("click.alert.data-api",c,b.prototype.close)}(window.jQuery);!function(c){var b=function(e,d){this.$element=c(e);this.options=c.extend({},c.fn.button.defaults,d)};b.prototype.setState=function(g){var i="disabled",e=this.$element,f=e.data(),h=e.is("input")?"val":"html";g=g+"Text";f.resetText||e.data("resetText",e[h]());e[h](f[g]||this.options[g]);setTimeout(function(){g=="loadingText"?e.addClass(i).attr(i,i):e.removeClass(i).removeAttr(i)},0)};b.prototype.toggle=function(){var d=this.$element.closest('[data-toggle="buttons-radio"]');d&&d.find(".active").removeClass("active");this.$element.toggleClass("active")};var a=c.fn.button;c.fn.button=function(d){return this.each(function(){var g=c(this),f=g.data("button"),e=typeof d=="object"&&d;if(!f){g.data("button",(f=new b(this,e)))}if(d=="toggle"){f.toggle()}else{if(d){f.setState(d)}}})};c.fn.button.defaults={loadingText:"loading..."};c.fn.button.Constructor=b;c.fn.button.noConflict=function(){c.fn.button=a;return this};c(document).on("click.button.data-api","[data-toggle^=button]",function(f){var d=c(f.target);if(!d.hasClass("btn")){d=d.closest(".btn")}d.button("toggle")})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.$indicators=this.$element.find(".carousel-indicators");this.options=d;this.options.pause=="hover"&&this.$element.on("mouseenter",b.proxy(this.pause,this)).on("mouseleave",b.proxy(this.cycle,this))};c.prototype={cycle:function(d){if(!d){this.paused=false}if(this.interval){clearInterval(this.interval)}this.options.interval&&!this.paused&&(this.interval=setInterval(b.proxy(this.next,this),this.options.interval));return this},getActiveIndex:function(){this.$active=this.$element.find(".item.active");this.$items=this.$active.parent().children();return this.$items.index(this.$active)},to:function(f){var d=this.getActiveIndex(),e=this;if(f>(this.$items.length-1)||f<0){return}if(this.sliding){return this.$element.one("slid",function(){e.to(f)})}if(d==f){return this.pause().cycle()}return this.slide(f>d?"next":"prev",b(this.$items[f]))},pause:function(d){if(!d){this.paused=true}if(this.$element.find(".next, .prev").length&&b.support.transition.end){this.$element.trigger(b.support.transition.end);this.cycle(true)}clearInterval(this.interval);this.interval=null;return this},next:function(){if(this.sliding){return}return this.slide("next")},prev:function(){if(this.sliding){return}return this.slide("prev")},slide:function(k,f){var m=this.$element.find(".item.active"),d=f||m[k](),j=this.interval,l=k=="next"?"left":"right",g=k=="next"?"first":"last",h=this,i;this.sliding=true;j&&this.pause();d=d.length?d:this.$element.find(".item")[g]();i=b.Event("slide",{relatedTarget:d[0],direction:l});if(d.hasClass("active")){return}if(this.$indicators.length){this.$indicators.find(".active").removeClass("active");this.$element.one("slid",function(){var e=b(h.$indicators.children()[h.getActiveIndex()]);e&&e.addClass("active")})}if(b.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(i);if(i.isDefaultPrevented()){return}d.addClass(k);d[0].offsetWidth;m.addClass(l);d.addClass(l);this.$element.one(b.support.transition.end,function(){d.removeClass([k,l].join(" ")).addClass("active");m.removeClass(["active",l].join(" "));h.sliding=false;setTimeout(function(){h.$element.trigger("slid")},0)})}else{this.$element.trigger(i);if(i.isDefaultPrevented()){return}m.removeClass("active");d.addClass("active");this.sliding=false;this.$element.trigger("slid")}j&&this.cycle();return this}};var a=b.fn.carousel;b.fn.carousel=function(d){return this.each(function(){var h=b(this),g=h.data("carousel"),e=b.extend({},b.fn.carousel.defaults,typeof d=="object"&&d),f=typeof d=="string"?d:e.slide;if(!g){h.data("carousel",(g=new c(this,e)))}if(typeof d=="number"){g.to(d)}else{if(f){g[f]()}else{if(e.interval){g.pause().cycle()}}}})};b.fn.carousel.defaults={interval:5000,pause:"hover"};b.fn.carousel.Constructor=c;b.fn.carousel.noConflict=function(){b.fn.carousel=a;return this};b(document).on("click.carousel.data-api","[data-slide], [data-slide-to]",function(j){var i=b(this),f,d=b(i.attr("data-target")||(f=i.attr("href"))&&f.replace(/.*(?=#[^\s]+$)/,"")),g=b.extend({},d.data(),i.data()),h;d.carousel(g);if(h=i.attr("data-slide-to")){d.data("carousel").pause().to(h).cycle()}j.preventDefault()})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.options=b.extend({},b.fn.collapse.defaults,d);if(this.options.parent){this.$parent=b(this.options.parent)}this.options.toggle&&this.toggle()};c.prototype={constructor:c,dimension:function(){var d=this.$element.hasClass("width");return d?"width":"height"},show:function(){var g,d,f,e;if(this.transitioning||this.$element.hasClass("in")){return}g=this.dimension();d=b.camelCase(["scroll",g].join("-"));f=this.$parent&&this.$parent.find("> .accordion-group > .in");if(f&&f.length){e=f.data("collapse");if(e&&e.transitioning){return}f.collapse("hide");e||f.data("collapse",null)}this.$element[g](0);this.transition("addClass",b.Event("show"),"shown");b.support.transition&&this.$element[g](this.$element[0][d])},hide:function(){var d;if(this.transitioning||!this.$element.hasClass("in")){return}d=this.dimension();this.reset(this.$element[d]());this.transition("removeClass",b.Event("hide"),"hidden");this.$element[d](0)},reset:function(d){var e=this.dimension();this.$element.removeClass("collapse")[e](d||"auto")[0].offsetWidth;this.$element[d!==null?"addClass":"removeClass"]("collapse");return this},transition:function(h,e,f){var g=this,d=function(){if(e.type=="show"){g.reset()}g.transitioning=0;g.$element.trigger(f)};this.$element.trigger(e);if(e.isDefaultPrevented()){return}this.transitioning=1;this.$element[h]("in");b.support.transition&&this.$element.hasClass("collapse")?this.$element.one(b.support.transition.end,d):d()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var a=b.fn.collapse;b.fn.collapse=function(d){return this.each(function(){var g=b(this),f=g.data("collapse"),e=b.extend({},b.fn.collapse.defaults,g.data(),typeof d=="object"&&d);if(!f){g.data("collapse",(f=new c(this,e)))}if(typeof d=="string"){f[d]()}})};b.fn.collapse.defaults={toggle:true};b.fn.collapse.Constructor=c;b.fn.collapse.noConflict=function(){b.fn.collapse=a;return this};b(document).on("click.collapse.data-api","[data-toggle=collapse]",function(i){var h=b(this),d,g=h.attr("data-target")||i.preventDefault()||(d=h.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),f=b(g).data("collapse")?"toggle":h.data();h[b(g).hasClass("in")?"addClass":"removeClass"]("collapsed");b(g).collapse(f)})}(window.jQuery);!function(f){var b="[data-toggle=dropdown]",a=function(h){var g=f(h).on("click.dropdown.data-api",this.toggle);f("html").on("click.dropdown.data-api",function(){g.parent().removeClass("open")})};a.prototype={constructor:a,toggle:function(j){var i=f(this),h,g;if(i.is(".disabled, :disabled")){return}h=e(i);g=h.hasClass("open");d();if(!g){if("ontouchstart" in document.documentElement){f(' + +
+ + + + + +
+
+ +
+ + +
+ +
+

Java Project with JUnit Tests

+
+
+

Sample minimal configuration for Java Project with JUnit tests.

+
+
+

Test dependencies for generated contract verification tests

+
+
+
                <dependency>
+                        <groupId>org.springframework.cloud</groupId>
+                        <artifactId>spring-cloud-starter-contract-verifier</artifactId>
+                        <version>${it-plugin.version}</version>
+                        <scope>test</scope>
+                </dependency>
+
+
+
+
+

Project configuration for Spring Cloud Contract Verifier with JUnit tests and stub publishing

+
+
+
                        <plugin>
+                                <groupId>org.springframework.cloud</groupId>
+                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                <version>${spring-cloud-verifier-plugin.version}</version>
+                                <extensions>true</extensions>
+                                <configuration>
+                                        <baseClassForTests>hello.BaseAccurest</baseClassForTests>
+                                </configuration>
+                        </plugin>
+
+
+
+
+

Base Test class

+
+
+
/*
+ * Copyright 2013-2019 the original author or 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.
+ */package hello;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+
+public class BaseAccurest {
+
+        @Before
+        public void setup() {
+                RestAssuredMockMvc.standaloneSetup(new GreetingController());
+        }
+
+}
+
+
+
+ +
+
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/licenses.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/licenses.html new file mode 100644 index 00000000..14e2803b --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/licenses.html @@ -0,0 +1,969 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Project Licenses + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + +
+ +
+ + + + + +
+
+ +
+ + +
+ +
+

Overview

+

Typically the licenses listed for the project are that of the project itself, and not of dependencies.

+
+

Project Licenses

+
+

Apache License, Version 2.0

+

Copyright 2014-2015 the original author or 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.

[Original text] +

Copy of the license follows:

+ +
+ +
+ +
+
+ ApacheCon is Coming 9-12 Sept. 2019 - Las Vegas + The Apache Software Foundation +
+ +
+ Apache Support Logo +
+
+
+

Apache License, Version 2.0

+ +

The 2.0 version of the Apache License, approved by the ASF in 2004, helps us achieve our goal of providing +reliable and long-lived software products through collaborative open source software development.

+

All packages produced by the ASF are implicitly licensed under the Apache +License, Version 2.0, unless otherwise explicitly stated.

+
+ +

+Apache License

Version 2.0, January 2004

+http://www.apache.org/licenses/ +

+ +

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

+ +

1. Definitions.

+ +
+ +

"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document.

+ +

"Licensor" shall mean the copyright owner or entity authorized by the +copyright owner that is granting the License.

+ +

"Legal Entity" shall mean the union of the acting entity and all other +entities that control, are controlled by, or are under common control with +that entity. For the purposes of this definition, "control" means (i) the +power, direct or indirect, to cause the direction or management of such +entity, whether by contract or otherwise, or (ii) ownership of fifty +percent (50%) or more of the outstanding shares, or (iii) beneficial +ownership of such entity.

+ +

"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License.

+ +

"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation source, +and configuration files.

+ +

"Object" form shall mean any form resulting from mechanical transformation +or translation of a Source form, including but not limited to compiled +object code, generated documentation, and conversions to other media types.

+ +

"Work" shall mean the work of authorship, whether in Source or Object form, +made available under the License, as indicated by a copyright notice that +is included in or attached to the work (an example is provided in the +Appendix below).

+ +

"Derivative Works" shall mean any work, whether in Source or Object form, +that is based on (or derived from) the Work and for which the editorial +revisions, annotations, elaborations, or other modifications represent, as +a whole, an original work of authorship. For the purposes of this License, +Derivative Works shall not include works that remain separable from, or +merely link (or bind by name) to the interfaces of, the Work and Derivative +Works thereof.

+ +

"Contribution" shall mean any work of authorship, including the original +version of the Work and any modifications or additions to that Work or +Derivative Works thereof, that is intentionally submitted to Licensor for +inclusion in the Work by the copyright owner or by an individual or Legal +Entity authorized to submit on behalf of the copyright owner. For the +purposes of this definition, "submitted" means any form of electronic, +verbal, or written communication sent to the Licensor or its +representatives, including but not limited to communication on electronic +mailing lists, source code control systems, and issue tracking systems that +are managed by, or on behalf of, the Licensor for the purpose of discussing +and improving the Work, but excluding communication that is conspicuously +marked or otherwise designated in writing by the copyright owner as "Not a +Contribution."

+ +

"Contributor" shall mean Licensor and any individual or Legal Entity on +behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work.

+ +
+ +

2. Grant of Copyright License. Subject to the +terms and conditions of this License, each Contributor hereby grants to You +a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, publicly +display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form.

+ +

3. Grant of Patent License. Subject to the terms +and conditions of this License, each Contributor hereby grants to You a +perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, use, +offer to sell, sell, import, and otherwise transfer the Work, where such +license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by +combination of their Contribution(s) with the Work to which such +Contribution(s) was submitted. If You institute patent litigation against +any entity (including a cross-claim or counterclaim in a lawsuit) alleging +that the Work or a Contribution incorporated within the Work constitutes +direct or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate as of the +date such litigation is filed.

+ +

4. Redistribution. You may reproduce and +distribute copies of the Work or Derivative Works thereof in any medium, +with or without modifications, and in Source or Object form, provided that +You meet the following conditions:

+ +
    +
  1. You must give any other recipients of the Work or Derivative Works a +copy of this License; and
  2. + +
  3. You must cause any modified files to carry prominent notices stating +that You changed the files; and
  4. + +
  5. You must retain, in the Source form of any Derivative Works that You +distribute, all copyright, patent, trademark, and attribution notices from +the Source form of the Work, excluding those notices that do not pertain to +any part of the Derivative Works; and
  6. + +
  7. If the Work includes a "NOTICE" text file as part of its distribution, +then any Derivative Works that You distribute must include a readable copy +of the attribution notices contained within such NOTICE file, excluding +those notices that do not pertain to any part of the Derivative Works, in +at least one of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or documentation, +if provided along with the Derivative Works; or, within a display generated +by the Derivative Works, if and wherever such third-party notices normally +appear. The contents of the NOTICE file are for informational purposes only +and do not modify the License. You may add Your own attribution notices +within Derivative Works that You distribute, alongside or as an addendum to +the NOTICE text from the Work, provided that such additional attribution +notices cannot be construed as modifying the License. +
    +
    +You may add Your own copyright statement to Your modifications and may +provide additional or different license terms and conditions for use, +reproduction, or distribution of Your modifications, or for any such +Derivative Works as a whole, provided Your use, reproduction, and +distribution of the Work otherwise complies with the conditions stated in +this License. +
  8. + +
+ +

5. Submission of Contributions. Unless You +explicitly state otherwise, any Contribution intentionally submitted for +inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the +terms of any separate license agreement you may have executed with Licensor +regarding such Contributions.

+ +

6. Trademarks. This License does not grant +permission to use the trade names, trademarks, service marks, or product +names of the Licensor, except as required for reasonable and customary use +in describing the origin of the Work and reproducing the content of the +NOTICE file.

+ +

7. Disclaimer of Warranty. Unless required by +applicable law or agreed to in writing, Licensor provides the Work (and +each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, +without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You +are solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise +of permissions under this License.

+ +

8. Limitation of Liability. In no event and +under no legal theory, whether in tort (including negligence), contract, or +otherwise, unless required by applicable law (such as deliberate and +grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a result +of this License or out of the use or inability to use the Work (including +but not limited to damages for loss of goodwill, work stoppage, computer +failure or malfunction, or any and all other commercial damages or losses), +even if such Contributor has been advised of the possibility of such +damages.

+ +

9. Accepting Warranty or Additional Liability. +While redistributing the Work or Derivative Works thereof, You may choose +to offer, and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this License. +However, in accepting such obligations, You may act only on Your own behalf +and on Your sole responsibility, not on behalf of any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor +harmless for any liability incurred by, or claims asserted against, such +Contributor by reason of your accepting any such warranty or additional +liability.

+ +

END OF TERMS AND CONDITIONS

+ +
+ +

How to apply the Apache License to your work

+

To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included +on the same "printed page" as the copyright notice for easier +identification within third-party archives.

+
Copyright [yyyy] [name of copyright owner]
+
+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.
+
+ + + + + + + + + + +
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugin-info.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugin-info.html new file mode 100644 index 00000000..82182be9 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugin-info.html @@ -0,0 +1,371 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Plugin Documentation + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Plugin Documentation

+

Goals available for this plugin:

+ + + + + + + + + + + + + + + + + + + + + +
GoalDescription
spring-cloud-contract:convertConvert Spring Cloud Contract Verifier contracts into WireMock +stubs mappings. +

This goal allows you to generate `stubs-jar` or execute +`spring-cloud-contract:run` with generated WireMock mappings.

spring-cloud-contract:generateStubsPicks the converted .json files and creates a jar. Requires convert +to be executed first.
spring-cloud-contract:generateTestsFrom the provided directory with contracts generates the acceptance +tests on the producer side.
spring-cloud-contract:helpDisplay help information on +spring-cloud-contract-maven-plugin.
+Call mvn spring-cloud-contract:help -Ddetail=true +-Dgoal=<goal-name> to display parameter details.
spring-cloud-contract:pushStubsToScmThe generated stubs get committed to the SCM repo and pushed to +origin.
spring-cloud-contract:runMojo for running stubs.
+
+

System Requirements

+

The following specifies the minimum requirements to run this Maven plugin:

+ + + + + + + + + + + + +
Maven3.2.5
JDK1.8
MemoryNo minimum requirement.
Disk SpaceNo minimum requirement.
+
+

Usage

+

You should specify the version in your project's plugin configuration:

+
<project>
+  ...
+  <build>
+    <!-- To define the plugin version in your parent POM -->
+    <pluginManagement>
+      <plugins>
+        <plugin>
+          <groupId>org.springframework.cloud</groupId>
+          <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+          <version>2.1.2.RELEASE</version>
+        </plugin>
+        ...
+      </plugins>
+    </pluginManagement>
+    <!-- To use the plugin goals in your POM or parent POM -->
+    <plugins>
+      <plugin>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+        <version>2.1.2.RELEASE</version>
+      </plugin>
+      ...
+    </plugins>
+  </build>
+  ...
+</project>
+
+

For more information, see "Guide to Configuring Plug-ins"

+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugin-management.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugin-management.html new file mode 100644 index 00000000..c5da48e7 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugin-management.html @@ -0,0 +1,428 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Project Plugin Management + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Project Plugin Management

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GroupIdArtifactIdVersion
io.spring.javaformatspring-javaformat-maven-plugin0.0.7
org.apache.maven.pluginsmaven-antrun-plugin1.8
org.apache.maven.pluginsmaven-assembly-plugin2.2-beta-5
org.apache.maven.pluginsmaven-checkstyle-plugin3.0.0
org.apache.maven.pluginsmaven-compiler-plugin3.8.0
org.apache.maven.pluginsmaven-dependency-plugin2.8
org.apache.maven.pluginsmaven-eclipse-plugin2.10
org.apache.maven.pluginsmaven-enforcer-plugin3.0.0-M2
org.apache.maven.pluginsmaven-failsafe-plugin2.22.0
org.apache.maven.pluginsmaven-jar-plugin3.1.0
org.apache.maven.pluginsmaven-release-plugin2.5.3
org.apache.maven.pluginsmaven-resources-plugin3.1.0
org.apache.maven.pluginsmaven-shade-plugin3.1.1
org.apache.maven.pluginsmaven-surefire-plugin3.0.0-M3
org.apache.maven.pluginsmaven-war-plugin3.2.2
org.codehaus.gmavenplusgmavenplus-plugin1.6.3
org.codehaus.mojoexec-maven-plugin1.6.0
org.eclipse.m2elifecycle-mapping1.0.0
org.springframework.bootspring-boot-maven-plugin2.1.6.RELEASE
pl.project13.mavengit-commit-id-plugin2.2.4
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugins.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugins.html new file mode 100644 index 00000000..c4767b82 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/plugins.html @@ -0,0 +1,451 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Project Plugins + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Project Build Plugins

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GroupIdArtifactIdVersion
io.spring.javaformatspring-javaformat-maven-plugin0.0.7
io.takari.maven.pluginstakari-lifecycle-plugin1.13.7
org.apache.maven.pluginsmaven-checkstyle-plugin3.0.0
org.apache.maven.pluginsmaven-clean-plugin3.0.0
org.apache.maven.pluginsmaven-compiler-plugin3.8.0
org.apache.maven.pluginsmaven-deploy-plugin2.7
org.apache.maven.pluginsmaven-failsafe-plugin2.22.0
org.apache.maven.pluginsmaven-gpg-plugin1.6
org.apache.maven.pluginsmaven-install-plugin2.4
org.apache.maven.pluginsmaven-jar-plugin3.1.0
org.apache.maven.pluginsmaven-javadoc-plugin3.0.1
org.apache.maven.pluginsmaven-plugin-plugin3.5
org.apache.maven.pluginsmaven-resources-plugin3.1.0
org.apache.maven.pluginsmaven-scm-publish-plugin3.0.0
org.apache.maven.pluginsmaven-site-plugin3.7.1
org.apache.maven.pluginsmaven-source-plugin3.0.1
org.apache.maven.pluginsmaven-surefire-plugin3.0.0-M3
org.codehaus.gmavenplusgmavenplus-plugin1.6.3
org.codehaus.plexusplexus-component-metadata1.7.1
org.eluder.coverallscoveralls-maven-plugin4.3.0
org.jacocojacoco-maven-plugin0.8.2
+
+

Project Report Plugins

+ + + + + + + + + + + + + + + + +
GroupIdArtifactIdVersion
org.apache.maven.pluginsmaven-checkstyle-plugin3.0.0
org.apache.maven.pluginsmaven-plugin-plugin3.5
org.apache.maven.pluginsmaven-project-info-reports-plugin3.0.0
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/project-info.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/project-info.html new file mode 100644 index 00000000..c8925d4b --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/project-info.html @@ -0,0 +1,377 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Project Information + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Project Information

+

This document provides an overview of the various documents and links that are part of this project's general information. All of this content is automatically generated by Maven on behalf of the project.

+
+

Overview

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DocumentDescription
CI ManagementThis is a link to the definitions of all continuous integration processes that builds and tests code on a frequent, regular basis.
AboutSpring Cloud Contract Maven Plugin
Issue ManagementThis document provides information on the issue management system used in this project.
LicensesThis document lists the project license(s).
Plugin ManagementThis document lists the plugins that are defined through pluginManagement.
PluginsThis document lists the build plugins and the report plugins used by this project.
TeamThis document provides information on the members of this project. These are the individuals who have contributed to the project in one form or another.
Source Code ManagementThis document lists ways to access the online source repository.
SummaryThis document lists other related information of this project
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/project-reports.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/project-reports.html new file mode 100644 index 00000000..ba7b6a99 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/project-reports.html @@ -0,0 +1,307 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Generated Reports + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Generated Reports

+

This document provides an overview of the various reports that are automatically generated by Maven . Each report is briefly described below.

+
+

Overview

+ + + + + + + + + +
DocumentDescription
CheckstyleReport on coding style conventions.
Plugin DocumentationThis report provides goals and parameters documentation of a plugin.
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/pushStubsToScm-mojo.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/pushStubsToScm-mojo.html new file mode 100644 index 00000000..6e2fe14e --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/pushStubsToScm-mojo.html @@ -0,0 +1,551 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – spring-cloud-contract:pushStubsToScm + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ + + +
+

spring-cloud-contract:pushStubsToScm

+ +

Full name:

+ +

org.springframework.cloud:spring-cloud-contract-maven-plugin:2.1.2.RELEASE:pushStubsToScm

+ +

Description:

+ +
The generated stubs get committed to the SCM repo and pushed to +origin.
+ +

Attributes:

+ +
    + +
  • Requires a Maven project to be executed.
  • +
+ +
+

Optional Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeSinceDescription
contractsModeStubRunnerProperties$StubsMode-Picks the mode in which stubs will be found and registered.
Default value is: CLASSPATH.
User property is: contractsMode.
contractsPropertiesMap-Map of properties that can be passed to custom +StubDownloaderBuilder.
User property is: contractsProperties.
contractsRepositoryPasswordString-The password to be used to connect to the repo with contracts.
User property is: contractsRepositoryPassword.
contractsRepositoryUrlString-The URL from which a contracts should get downloaded. If not +provided but artifactid / coordinates notation was provided then +the current Maven's build repositories will be taken into +consideration.
User property is: contractsRepositoryUrl.
contractsRepositoryUsernameString-The user name to be used to connect to the repo with contracts.
User property is: contractsRepositoryUsername.
deleteStubsAfterTestboolean-If set to false will NOT delete stubs from a temporary +folder after running tests.
Default value is: true.
User property is: deleteStubsAfterTest.
outputDirectoryFile-(no description)
Default value is: ${project.build.directory}/stubs.
User property is: stubsDirectory.
skipboolean-Set this to "true" to bypass the whole Verifier execution.
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
taskSkipboolean-Set this to "true" to bypass only JAR creation.
Default value is: false.
User property is: spring.cloud.contract.verifier.publish-stubs-to-scm.skip.
+
+ +
+

Parameter Details

+ +

contractsMode:

+ +
Picks the mode in which stubs will be found and registered.
+ +
    + +
  • Type: org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties$StubsMode
  • + +
  • Required: No
  • + +
  • User Property: contractsMode
  • + +
  • Default: CLASSPATH
  • +

+

contractsProperties:

+ +
Map of properties that can be passed to custom +StubDownloaderBuilder.
+ +
    + +
  • Type: java.util.Map
  • + +
  • Required: No
  • + +
  • User Property: contractsProperties
  • +

+

contractsRepositoryPassword:

+ +
The password to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryPassword
  • +

+

contractsRepositoryUrl:

+ +
The URL from which a contracts should get downloaded. If not +provided but artifactid / coordinates notation was provided then +the current Maven's build repositories will be taken into +consideration.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryUrl
  • +

+

contractsRepositoryUsername:

+ +
The user name to be used to connect to the repo with contracts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: contractsRepositoryUsername
  • +

+

deleteStubsAfterTest:

+ +
If set to false will NOT delete stubs from a temporary +folder after running tests.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: deleteStubsAfterTest
  • + +
  • Default: true
  • +

+

outputDirectory:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • User Property: stubsDirectory
  • + +
  • Default: ${project.build.directory}/stubs
  • +

+

skip:

+ +
Set this to "true" to bypass the whole Verifier execution.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.skip
  • + +
  • Default: false
  • +

+

taskSkip:

+ +
Set this to "true" to bypass only JAR creation.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.publish-stubs-to-scm.skip
  • + +
  • Default: false
  • +
+
+
+ + +
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/run-mojo.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/run-mojo.html new file mode 100644 index 00000000..3d5d06f5 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/run-mojo.html @@ -0,0 +1,571 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – spring-cloud-contract:run + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ + + +
+

spring-cloud-contract:run

+ +

Full name:

+ +

org.springframework.cloud:spring-cloud-contract-maven-plugin:2.1.2.RELEASE:run

+ +

Description:

+ +
Mojo for running stubs.
+ +

Attributes:

+ +
    + +
  • Requires dependency resolution of artifacts in scope: runtime.
  • +
+ +
+

Optional Parameters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeSinceDescription
destinationFile-(no description)
Default value is: ${basedir}.
User property is: stubsDirectory.
httpPortint-HTTP port for the WireMock server that serves stubs.
Default value is: 8080.
User property is: spring.cloud.contract.verifier.http.port.
maxPortint-Maximal port at which the stub should start.
Default value is: 15000.
User property is: spring.cloud.contract.verifier.http.maxPort.
minPortint-Minimal port at which the stub should start.
Default value is: 10000.
User property is: spring.cloud.contract.verifier.http.minPort.
skipboolean-Set this to "true" to bypass verifier execution.
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
skipTestOnlyboolean-Set this to "true" to bypass verifier test generation.
Default value is: false.
User property is: spring.cloud.contract.verifier.skipTestOnly.
stubsString-List of stubs to be downloaded and ran in a colon separated Ivy +notation.
User property is: spring.cloud.contract.verifier.stubs.
stubsClassifierString-Classifier used by stubs artifacts.
Default value is: stubs.
stubsDirectoryFile-(no description)
Default value is: ${project.build.directory}/stubs/.
waitForKeyPressedboolean-Should the plugin wait for the user to press the key after starting +the stubs.
Default value is: true.
User property is: spring.cloud.contract.verifier.wait-for-key-pressed.
+
+ +
+

Parameter Details

+ +

destination:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • User Property: stubsDirectory
  • + +
  • Default: ${basedir}
  • +

+

httpPort:

+ +
HTTP port for the WireMock server that serves stubs.
+ +
    + +
  • Type: int
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.http.port
  • + +
  • Default: 8080
  • +

+

maxPort:

+ +
Maximal port at which the stub should start.
+ +
    + +
  • Type: int
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.http.maxPort
  • + +
  • Default: 15000
  • +

+

minPort:

+ +
Minimal port at which the stub should start.
+ +
    + +
  • Type: int
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.http.minPort
  • + +
  • Default: 10000
  • +

+

skip:

+ +
Set this to "true" to bypass verifier execution.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.skip
  • + +
  • Default: false
  • +

+

skipTestOnly:

+ +
Set this to "true" to bypass verifier test generation.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.skipTestOnly
  • + +
  • Default: false
  • +

+

stubs:

+ +
List of stubs to be downloaded and ran in a colon separated Ivy +notation.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.stubs
  • +

+

stubsClassifier:

+ +
Classifier used by stubs artifacts.
+ +
    + +
  • Type: java.lang.String
  • + +
  • Required: No
  • + +
  • Default: stubs
  • +

+

stubsDirectory:

+ +
(no description)
+ +
    + +
  • Type: java.io.File
  • + +
  • Required: No
  • + +
  • Default: ${project.build.directory}/stubs/
  • +

+

waitForKeyPressed:

+ +
Should the plugin wait for the user to press the key after starting +the stubs.
+ +
    + +
  • Type: boolean
  • + +
  • Required: No
  • + +
  • User Property: spring.cloud.contract.verifier.wait-for-key-pressed
  • + +
  • Default: true
  • +
+
+
+ + +
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/scm.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/scm.html new file mode 100644 index 00000000..489b5b17 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/scm.html @@ -0,0 +1,359 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Source Code Management + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Overview

+

This project uses Git to manage its source code. Instructions on Git use can be found at https://git-scm.com/documentation.

+
+

Web Browser Access

+

The following is a link to a browsable version of the source repository:

+
+
+

Anonymous Access

+

The source can be checked out anonymously from Git with this command (See https://git-scm.com/docs/git-clone):

+
$ git clone https://github.com/spring-cloud/spring-cloud-contract.git
+
+

Developer Access

+

Only project developers can access the Git tree via this method (See https://git-scm.com/docs/git-clone).

+
$ git clone git@github.com:spring-cloud/spring-cloud-contract.git
+
+

Access from Behind a Firewall

+

Refer to the documentation of the SCM used for more information about access behind a firewall.

+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/sitemap.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/sitemap.html new file mode 100644 index 00000000..020a39d0 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/sitemap.html @@ -0,0 +1,344 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Sitemap + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Sitemap

+ +

This page lists all entries of the navigation menu in expanded form.

+ +
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/spock.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/spock.html new file mode 100644 index 00000000..9173e17e --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/spock.html @@ -0,0 +1,398 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Groovy Project with Spock Specifications

+
+
+

Sample minimal configuration for Groovy Project with Spock Specification

+
+
+

Test dependencies for generated contract verification tests

+
+
+
                <dependency>
+                        <groupId>org.spockframework</groupId>
+                        <artifactId>spock-core</artifactId>
+                        <version>1.0-groovy-2.4</version>
+                        <scope>test</scope>
+                </dependency>
+                <dependency>
+                        <groupId>org.springframework.cloud</groupId>
+                        <artifactId>spring-cloud-starter-contract-verifier</artifactId>
+                        <version>${it-plugin.version}</version>
+                        <scope>test</scope>
+                </dependency>
+
+
+
+
+

Project configuration for Spring Cloud Contract Verifier, Groovy, Spock specifications and stub publishing

+
+
+
                        <plugin>
+                                <groupId>org.springframework.cloud</groupId>
+                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                <version>${spring-cloud-verifier-plugin.version}</version>
+                                <extensions>true</extensions>
+                                <configuration>
+                                        <baseClassForTests>hello.BaseAccurest</baseClassForTests>
+                                        <testFramework>SPOCK</testFramework>
+                                </configuration>
+                        </plugin>
+
+                        <plugin>
+                                <groupId>org.codehaus.gmavenplus</groupId>
+                                <artifactId>gmavenplus-plugin</artifactId>
+                                <executions>
+                                        <execution>
+                                                <goals>
+                                                        <goal>compileTests</goal>
+                                                </goals>
+                                        </execution>
+                                </executions>
+                                <configuration>
+                                        <testSources>
+                                                <testSource>
+                                                        <directory>${project.basedir}/src/test/groovy</directory>
+                                                        <includes>
+                                                                <include>**/*.groovy</include>
+                                                        </includes>
+                                                </testSource>
+                                                <testSource>
+                                                        <directory>
+                                                                ${project.build.directory}/generated-test-sources/contracts
+                                                        </directory>
+                                                        <includes>
+                                                                <include>**/*.groovy</include>
+                                                        </includes>
+                                                </testSource>
+                                        </testSources>
+                                </configuration>
+                        </plugin>
+                        <plugin>
+                                <artifactId>maven-surefire-plugin</artifactId>
+                                <configuration>
+                                        <includes>
+                                                <include>**/*Spec.java</include>
+                                        </includes>
+                                </configuration>
+                        </plugin>
+
+
+
+
+

Base Specification class

+
+
+
/*
+ * Copyright 2013-2019 the original author or 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.
+ */
+package hello
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc
+import spock.lang.Specification
+
+class BaseAccurest extends Specification {
+
+        def setup() {
+                RestAssuredMockMvc.standaloneSetup(new GreetingController())
+        }
+
+}
+
+
+
+ +
+
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/summary.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/summary.html new file mode 100644 index 00000000..e1d8a26e --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/summary.html @@ -0,0 +1,393 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Project Summary + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Project Summary

+
+

Project Information

+ + + + + + + + + + + + +
FieldValue
NameSpring Cloud Contract Maven Plugin
DescriptionSpring Cloud Contract Maven Plugin
Homepagehttps://github.com/spring-cloud/spring-cloud-contract
+
+

Project Organization

+ + + + + + + + + +
FieldValue
NameSpring
URLhttps://spring.io/
+
+

Build Information

+ + + + + + + + + + + + + + + + + + +
FieldValue
GroupIdorg.springframework.cloud
ArtifactIdspring-cloud-contract-maven-plugin
Version2.1.2.RELEASE
Typemaven-plugin
Java Version1.8
+
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/team.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/team.html new file mode 100644 index 00000000..5487bbdd --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/team.html @@ -0,0 +1,377 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – Project Team + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +
+

Project Team

+

A successful project requires many people to play many roles. Some members write code or documentation, while others are valuable as testers, submitting patches and suggestions.

+

The project team is comprised of Members and Contributors. Members have direct access to the source of a project and actively evolve the code-base. Contributors improve the project through submission of patches and suggestions to the Members. The number of Contributors to the project is unbounded. Get involved today. All contributions to the project are greatly appreciated.

+
+

Members

+

The following is a list of developers with commit privileges that have directly contributed to the project in one way or another.

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ImageIdNameEmail
mariuszsMariusz Smykulamariuszs@gmail.com
marcingrzejszczakMarcin Grzejszczakmgrzejszczak@pivotal.io
dsyerDavid Syerdsyer@pivotal.io
OlgaMaciaszekOlga Maciaszek-Sharmaomaciaszeksharma@pivotal.io
+
+

Contributors

+

There are no contributors listed for this project. Please check back again later.

+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/usage.html b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/usage.html new file mode 100644 index 00000000..db9b72a5 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract-maven-plugin/usage.html @@ -0,0 +1,360 @@ + + + + + + + + + Spring Cloud Contract Maven Plugin – + + + + + + + + + + + + + + + + + Fork me on GitHub + + + + + + + + + +
+ + + + + +
+
+ +
+ + +
+ +

Usage

+
+

Converting Spring Cloud Contract DSL into WireMock stub mappings

+
+
+
+
mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert
+
+
+
+

or shortly [1]

+
+
+
+
mvn spring-cloud-contract:convert
+
+
+
+

For more information please go to the Spring Cloud Contract Wiki or Plugin Documentation Site.

+
+
+
+
+

Spring Cloud Contract Stub Runner

+
+
+

Run stubs mappings from current directory:

+
+
+
+
mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:run
+
+
+
+

or shortly [1]

+
+
+
+
mvn spring-cloud-contract:run
+
+
+
+
+
+

Running stubs from repository

+
+
+
+
mvn spring-cloud-contract:run -Dstubs="org.springframework:gs-rest-service"
+
+
+
+

where org.springframework:gs-rest-service is artifact with stubs classifier contains WireMock mappings.

+
+
+

In order for the goal to be executed correctly, target/stubs subdirectory should be added in the directory from which +the command will be executed.

+
+
+
+
+

Project configuration

+
+
+
+
                        <plugin>
+                                <groupId>org.springframework.cloud</groupId>
+                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                <version>${spring-cloud-verifier-plugin.version}</version>
+                                <extensions>true</extensions>
+                                <configuration>
+                                        <baseClassForTests>hello.BaseAccurest</baseClassForTests>
+                                </configuration>
+                        </plugin>
+
+
+
+
+
+
+
+1. Additional configuration inside ~/.m2/settings.xml is required: <pluginGroups><pluginGroup>org.springframework.cloud</pluginGroup></pluginGroups>. +
+
+
+
+
+ +
+ +
+
+
+

Copyright © 2016–2019 + Spring. + All rights reserved. +

+
+ + +
+
+ + diff --git a/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract.xml b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract.xml new file mode 100644 index 00000000..4d326043 --- /dev/null +++ b/spring-cloud-contract/2.1.2.RELEASE/spring-cloud-contract.xml @@ -0,0 +1,10955 @@ + + + + + +Spring Cloud Contract +2019-06-21 + + + +Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, +Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant +2.1.2.RELEASE + + +Spring Cloud Contract +You need confidence when pushing new features to a new application or service in a +distributed system. This project provides support for Consumer Driven Contracts and +service schemas in Spring applications (for both HTTP and message-based interactions), +covering a range of options for writing tests, publishing them as assets, and asserting +that a contract is kept by producers and consumers. + + +Spring Cloud Contract Verifier Introduction +Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture. +Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract +definitions are used to produce the following resources: + + +JSON stub definitions to be used by WireMock when doing integration testing on the +client code (client tests). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier. + + +Messaging routes, if you’re using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations. + + +Acceptance tests (in JUnit 4, JUnit 5 or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (server tests). A full test is generated by +Spring Cloud Contract Verifier. + + +
+History +Before becoming Spring Cloud Contract, this project was called Accurest. +It was created by Marcin Grzejszczak and Jakub Kubrynski +from (Codearte. +The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016. +
+
+Why a Contract Verifier? +Assume that we have a system consisting of multiple microservices: + + + + + +Microservices Architecture + + +
+Testing issues +If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things: + + +Deploy all microservices and perform end-to-end tests. + + +Mock other microservices in unit/integration tests. + + +Both have their advantages but also a lot of disadvantages. +Deploy all microservices and perform end to end tests +Advantages: + + +Simulates production. + + +Tests real communication between services. + + +Disadvantages: + + +To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc. + + +The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime). + + +They take a long time to run. + + +The feedback comes very late in the process. + + +They are extremely hard to debug. + + +Mock other microservices in unit/integration tests +Advantages: + + +They provide very fast feedback. + + +They have no infrastructure requirements. + + +Disadvantages: + + +The implementor of the service creates stubs that might have nothing to do with +reality. + + +You can go to production with passing tests and failing production. + + +To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses. + + + + + +Stubbed Services + + +Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you’re calling. Also, if you can use them, it means that they +were tested against the producer’s side. In short, you can trust those stubs. +
+
+
+Purposes +The main purposes of Spring Cloud Contract Verifier with Stub Runner are: + + +To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does. + + +To promote ATDD method and Microservices architectural style. + + +To provide a way to publish changes in contracts that are immediately visible on both +sides. + + +To generate boilerplate test code to be used on the server side. + + + +Spring Cloud Contract Verifier’s purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. + +
+
+How It Works +This section explores how Spring Cloud Contract Verifier with Stub Runner works. +
+A Three-second Tour +This very brief tour walks through using Spring Cloud Contract: + + + + + + + + +You can find a somewhat longer tour +here. +
+On the Producer Side +To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts. +Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-verifier</artifactId> + <scope>test</scope> +</dependency> +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> +</plugin> +Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +org.springframework.cloud.contract.verifier.tests.. +As the implementation of the functionalities described by the contracts is not yet +present, the tests fail. +To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example RestAssuredMockMvc +controller setup or messaging test setup). +Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository. +
+
+On the Consumer Side +Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service. +To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the +following example: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> + <scope>test</scope> +</dependency> +You can get the Producer-side stubs installed in your Maven repository in either of two +ways: + + +By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands: +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests + +The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail. + + + +By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract +Stub Runner properties, as shown in the following example: +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot + + +Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to +run the collaborators' stubs for you, as shown in the following example: +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. + +Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service. +
+
+
+A Three-minute Tour +This brief tour walks through using Spring Cloud Contract: + + + + + + + + +You can find an even more brief tour +here. +
+On the Producer Side +To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts. +For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract in Groovy DSL: +package contracts + +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'PUT' + url '/fraudcheck' + body([ + "client.id": $(regex('[0-9]{10}')), + loanAmount: 99999 + ]) + headers { + contentType('application/json') + } + } + response { + status OK() + body([ + fraudCheckStatus: "FRAUD", + "rejection.reason": "Amount too high" + ]) + headers { + contentType('application/json') + } + } +} +The same contract expressed in YAML would look like the following example: +request: + method: PUT + url: /fraudcheck + body: + "client.id": 1234567890 + loanAmount: 99999 + headers: + Content-Type: application/json + matchers: + body: + - path: $.['client.id'] + type: by_regex + value: "[0-9]{10}" +response: + status: 200 + body: + fraudCheckStatus: "FRAUD" + "rejection.reason": "Amount too high" + headers: + Content-Type: application/json;charset=UTF-8 +In the case of messaging, you can define: + + +The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header). + + +The methods that should be called after the message is received. + + +The methods that, when called, should trigger a message. + + +The following example shows a Camel messaging contract expressed in Groovy DSL: + def contractDsl = Contract.make { + label 'some_label' + input { + messageFrom('jms:delete') + messageBody([ + bookName: 'foo' + ]) + messageHeaders { + header('sample', 'header') + } + assertThat('bookWasDeleted()') + } + } +The following example shows the same contract expressed in YAML: +label: some_label +input: + messageFrom: jms:delete + messageBody: + bookName: 'foo' + messageHeaders: + sample: header + assertThat: bookWasDeleted() +Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-verifier</artifactId> + <scope>test</scope> +</dependency> +The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> +</plugin> +Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +org.springframework.cloud.contract.verifier.tests.. +The following example shows a sample auto-generated test for an HTTP contract: +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +The preceding example uses Spring’s MockMvc to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, +respectively.) +Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient +run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. +In order to use WebTestClient set testMode to WEBTESTCLIENT. +Here is an example of a test generated in WEBTESTCLIENT test mode: +[source,java,indent=0] +@Test + public void validate_shouldRejectABeerIfTooYoung() throws Exception { + // given: + WebTestClientRequestSpecification request = given() + .header("Content-Type", "application/json") + .body("{\"age\":10}"); + + // when: + WebTestClientResponse response = given().spec(request) + .post("/check"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK"); + } +Apart from the default JUnit 4, you can instead use JUnit 5 or Spock tests, by setting the plugin +testFramework property to either JUNIT5 or Spock. + +You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names. + +The following example shows an auto-generated test in Spock for a messaging stub contract: +[source,groovy,indent=0] +given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + \'\'\'{"bookName":"foo"}\'\'\', + ['sample': 'header'] + ) + +when: + contractVerifierMessaging.send(inputMessage, 'jms:delete') + +then: + noExceptionThrown() + bookWasDeleted() +As the implementation of the functionalities described by the contracts is not yet +present, the tests fail. +To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, RestAssuredMockMvc controller +setup or messaging test setup). +Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example: +[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar +[INFO] +[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar +[INFO] +[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- +[INFO] +[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar +[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +You can now merge the changes and publish both the application and the stub artifacts +in an online repository. +Docker Project +In order to enable working with contracts while creating applications in non-JVM +technologies, the springcloud/spring-cloud-contract Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the /contracts directory and set a few environment variables. +
+
+On the Consumer Side +Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service. +To get started, add the dependency to Spring Cloud Contract Stub Runner: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> + <scope>test</scope> +</dependency> +You can get the Producer-side stubs installed in your Maven repository in either of two +ways: + + +By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands: +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests + +The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail. + + + +Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub +Runner properties, as shown in the following example: +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot + + +Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run +the collaborators' stubs for you, as shown in the following example: +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. + +In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs: +2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version +2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT +2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] +2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] +2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] +2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] +
+
+
+Defining the Contract +As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts. +Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method. + +Groovy DSL + +/* + * Copyright 2013-2019 the original author or 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. + */ + +package contracts + +org.springframework.cloud.contract.spec.Contract.make { + request { // (1) + method 'PUT' // (2) + url '/fraudcheck' // (3) + body([ // (4) + "client.id": $(regex('[0-9]{10}')), + loanAmount : 99999 + ]) + headers { // (5) + contentType('application/json') + } + } + response { // (6) + status OK() // (7) + body([ // (8) + fraudCheckStatus : "FRAUD", + "rejection.reason": "Amount too high" + ]) + headers { // (9) + contentType('application/json') + } + } +} + +/* +From the Consumer perspective, when shooting a request in the integration test: + +(1) - If the consumer sends a request +(2) - With the "PUT" method +(3) - to the URL "/fraudcheck" +(4) - with the JSON body that + * has a field `client.id` that matches a regular expression `[0-9]{10}` + * has a field `loanAmount` that is equal to `99999` +(5) - with header `Content-Type` equal to `application/json` +(6) - then the response will be sent with +(7) - status equal `200` +(8) - and JSON body equal to + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +(9) - with header `Content-Type` equal to `application/json` + +From the Producer perspective, in the autogenerated producer-side test: + +(1) - A request will be sent to the producer +(2) - With the "PUT" method +(3) - to the URL "/fraudcheck" +(4) - with the JSON body that + * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}` + * has a field `loanAmount` that is equal to `99999` +(5) - with header `Content-Type` equal to `application/json` +(6) - then the test will assert if the response has been sent with +(7) - status equal `200` +(8) - and JSON body equal to + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +(9) - with header `Content-Type` matching `application/json.*` + */ + + + +YAML + +request: # (1) + method: PUT # (2) + url: /fraudcheck # (3) + body: # (4) + "client.id": 1234567890 + loanAmount: 99999 + headers: # (5) + Content-Type: application/json + matchers: + body: + - path: $.['client.id'] # (6) + type: by_regex + value: "[0-9]{10}" +response: # (7) + status: 200 # (8) + body: # (9) + fraudCheckStatus: "FRAUD" + "rejection.reason": "Amount too high" + headers: # (10) + Content-Type: application/json;charset=UTF-8 + + +#From the Consumer perspective, when shooting a request in the integration test: +# +#(1) - If the consumer sends a request +#(2) - With the "PUT" method +#(3) - to the URL "/fraudcheck" +#(4) - with the JSON body that +# * has a field `client.id` +# * has a field `loanAmount` that is equal to `99999` +#(5) - with header `Content-Type` equal to `application/json` +#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}` +#(7) - then the response will be sent with +#(8) - status equal `200` +#(9) - and JSON body equal to +# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +#(10) - with header `Content-Type` equal to `application/json` +# +#From the Producer perspective, in the autogenerated producer-side test: +# +#(1) - A request will be sent to the producer +#(2) - With the "PUT" method +#(3) - to the URL "/fraudcheck" +#(4) - with the JSON body that +# * has a field `client.id` `1234567890` +# * has a field `loanAmount` that is equal to `99999` +#(5) - with header `Content-Type` equal to `application/json` +#(7) - then the test will assert if the response has been sent with +#(8) - status equal `200` +#(9) - and JSON body equal to +# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +#(10) - with header `Content-Type` equal to `application/json;charset=UTF-8` + + +
+
+Client Side +Spring Cloud Contract generates stubs, which you can use during client-side testing. +You get a running WireMock instance/Messaging route that simulates the service. +You would like to feed that instance with a proper stub definition. +At some point in time, you need to send a request to the Fraud Detection service. +ResponseEntity<FraudServiceResponse> response = restTemplate.exchange( + "http://localhost:" + port + "/fraudcheck", HttpMethod.PUT, + new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class); +Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators. +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = { + "com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { +After that, during the tests, Spring Cloud Contract automatically finds the stubs +(simulating the real service) in the Maven repository and exposes them on a configured +(or random) port. +
+
+Server Side +Since you are developing your stub, you need to be sure that it actually resembles your +concrete implementation. You cannot have a situation where your stub acts in one way and +your application behaves in a different way, especially in production. +To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide. +The autogenerated test looks, more or less, like this: +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +
+
+
+Step-by-step Guide to Consumer Driven Contracts (CDC) +Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody. +Assume that Loan Issuance is a client to the Fraud Detection server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud. +Technical remark - Fraud Detection has an artifact-id of http-server, while Loan +Issuance has an artifact-id of http-client, and both have a group-id of com.example. +Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication. +The server +side code is available here and the +client code here. + +In this case, the producer owns the contracts. Physically, all the contract are +in the producer’s repository. + +
+Technical note +If using the SNAPSHOT / Milestone / Release Candidate versions please add the +following section to your build: + +Maven + +<repositories> + <repository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + <repository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> +</repositories> +<pluginRepositories> + <pluginRepository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> +</pluginRepositories> + + + +Gradle + +repositories { + mavenCentral() + mavenLocal() + maven { url "https://repo.spring.io/snapshot" } + maven { url "https://repo.spring.io/milestone" } + maven { url "https://repo.spring.io/release" } +} + + +
+
+Consumer side (Loan Issuance) +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: + + +Start doing TDD by writing a test for your feature. + + +Write the missing implementation. + + +Clone the Fraud Detection service repository locally. + + +Define the contract locally in the repo of Fraud Detection service. + + +Add the Spring Cloud Contract Verifier plugin. + + +Run the integration tests. + + +File a pull request. + + +Create an initial implementation. + + +Take over the pull request. + + +Write the missing implementation. + + +Deploy your app. + + +Work online. + + +Start doing TDD by writing a test for your feature. +@Test +public void shouldBeRejectedDueToAbnormalLoanAmount() { + // given: + LoanApplication application = new LoanApplication(new Client("1234567890"), + 99999); + // when: + LoanApplicationResult loanApplication = service.loanApplication(application); + // then: + assertThat(loanApplication.getLoanApplicationStatus()) + .isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED); + assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high"); +} +Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description. +Write the missing implementation. +At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the /fraudcheck url via the PUT method. +ResponseEntity<FraudServiceResponse> response = restTemplate.exchange( + "http://localhost:" + port + "/fraudcheck", HttpMethod.PUT, + new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class); +For simplicity, the port of the Fraud Detection service is set to 8080, and the +application runs on 8090. +If you start the test at this point, it breaks, because no service currently runs on port +8080. +Clone the Fraud Detection service repository locally. +You can start by playing around with the server side contract. To do so, you must first +clone it. +$ git clone https://your-git-server.com/server-side.git local-http-server-repo +Define the contract locally in the repo of Fraud Detection service. +As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract: + +Place the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important because the producer’s test base class name references that folder. + + +Groovy DSL + +/* + * Copyright 2013-2019 the original author or 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. + */ + +package contracts + +org.springframework.cloud.contract.spec.Contract.make { + request { // (1) + method 'PUT' // (2) + url '/fraudcheck' // (3) + body([ // (4) + "client.id": $(regex('[0-9]{10}')), + loanAmount : 99999 + ]) + headers { // (5) + contentType('application/json') + } + } + response { // (6) + status OK() // (7) + body([ // (8) + fraudCheckStatus : "FRAUD", + "rejection.reason": "Amount too high" + ]) + headers { // (9) + contentType('application/json') + } + } +} + +/* +From the Consumer perspective, when shooting a request in the integration test: + +(1) - If the consumer sends a request +(2) - With the "PUT" method +(3) - to the URL "/fraudcheck" +(4) - with the JSON body that + * has a field `client.id` that matches a regular expression `[0-9]{10}` + * has a field `loanAmount` that is equal to `99999` +(5) - with header `Content-Type` equal to `application/json` +(6) - then the response will be sent with +(7) - status equal `200` +(8) - and JSON body equal to + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +(9) - with header `Content-Type` equal to `application/json` + +From the Producer perspective, in the autogenerated producer-side test: + +(1) - A request will be sent to the producer +(2) - With the "PUT" method +(3) - to the URL "/fraudcheck" +(4) - with the JSON body that + * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}` + * has a field `loanAmount` that is equal to `99999` +(5) - with header `Content-Type` equal to `application/json` +(6) - then the test will assert if the response has been sent with +(7) - status equal `200` +(8) - and JSON body equal to + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +(9) - with header `Content-Type` matching `application/json.*` + */ + + + +YAML + +request: # (1) + method: PUT # (2) + url: /fraudcheck # (3) + body: # (4) + "client.id": 1234567890 + loanAmount: 99999 + headers: # (5) + Content-Type: application/json + matchers: + body: + - path: $.['client.id'] # (6) + type: by_regex + value: "[0-9]{10}" +response: # (7) + status: 200 # (8) + body: # (9) + fraudCheckStatus: "FRAUD" + "rejection.reason": "Amount too high" + headers: # (10) + Content-Type: application/json;charset=UTF-8 + + +#From the Consumer perspective, when shooting a request in the integration test: +# +#(1) - If the consumer sends a request +#(2) - With the "PUT" method +#(3) - to the URL "/fraudcheck" +#(4) - with the JSON body that +# * has a field `client.id` +# * has a field `loanAmount` that is equal to `99999` +#(5) - with header `Content-Type` equal to `application/json` +#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}` +#(7) - then the response will be sent with +#(8) - status equal `200` +#(9) - and JSON body equal to +# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +#(10) - with header `Content-Type` equal to `application/json` +# +#From the Producer perspective, in the autogenerated producer-side test: +# +#(1) - A request will be sent to the producer +#(2) - With the "PUT" method +#(3) - to the URL "/fraudcheck" +#(4) - with the JSON body that +# * has a field `client.id` `1234567890` +# * has a field `loanAmount` that is equal to `99999` +#(5) - with header `Content-Type` equal to `application/json` +#(7) - then the test will assert if the response has been sent with +#(8) - status equal `200` +#(9) - and JSON body equal to +# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +#(10) - with header `Content-Type` equal to `application/json;charset=UTF-8` + + +The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the section for more information. We highly recommend using the map notation! + +You must understand the map notation in order to set up contracts. Please read the +Groovy docs regarding JSON. + +The previously shown contract is an agreement between two sides that: + + +if an HTTP request is sent with all of + + +a PUT method on the /fraudcheck endpoint, + + +a JSON body with a client.id that matches the regular expression [0-9]{10} and +loanAmount equal to 99999, + + +and a Content-Type header with a value of application/vnd.fraud.v1+json, + + + + +then an HTTP response is sent to the consumer that + + +has status 200, + + +contains a JSON body with the fraudCheckStatus field containing a value FRAUD and +the rejectionReason field having value Amount too high, + + +and a Content-Type header with a value of application/vnd.fraud.v1+json. + + + + +Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally. +Add the Spring Cloud Contract Verifier plugin. +We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the Spring Cloud Contract BOM. +<dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-dependencies</artifactId> + <version>${spring-cloud-release.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> +</dependencyManagement> +Next, add the Spring Cloud Contract Verifier Maven plugin +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <packageWithBaseClasses>com.example.fraud</packageWithBaseClasses> + <convertToYaml>true</convertToYaml> + </configuration> +</plugin> +Since the plugin was added, you get the Spring Cloud Contract Verifier features which, +from the provided contracts: + + +generate and run tests + + +produce and install stubs + + +You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute: +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests +In the logs, you see something like this: +[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar +[INFO] +[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar +[INFO] +[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- +[INFO] +[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar +[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +The following line is extremely important: +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +It confirms that the stubs of the http-server have been installed in the local +repository. +Run the integration tests. +In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (Loan +Application service): +Add the Spring Cloud Contract BOM: +<dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-dependencies</artifactId> + <version>${spring-cloud-release-train.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> +</dependencyManagement> +Add the dependency to Spring Cloud Contract Stub Runner: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> + <scope>test</scope> +</dependency> +Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the +group-id and artifact-id for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you’re playing with the collaborators offline, you +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL). +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = { + "com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL) +public class LoanApplicationServiceTests { +Now, when you run your tests, you see something like this: +2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version +2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT +2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] +2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] +2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] +2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] +This output means that Stub Runner has found your stubs and started a server for your app +with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of +the stubs and with stubs classifier on port 8080. +File a pull request. +What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish. +Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done. +
+
+Producer side (Fraud Detection server) +As a developer of the Fraud Detection server (a server to the Loan Issuance service): +Create an initial implementation. +As a reminder, you can see the initial implementation here: +@RequestMapping(value = "/fraudcheck", method = PUT) +public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) { +return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON); +} +Take over the pull request. +$ git checkout -b contract-change-pr master +$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr +You must add the dependencies needed by the autogenerated tests: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-verifier</artifactId> + <scope>test</scope> +</dependency> +In the configuration of the Maven plugin, pass the packageWithBaseClasses property +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <packageWithBaseClasses>com.example.fraud</packageWithBaseClasses> + <convertToYaml>true</convertToYaml> + </configuration> +</plugin> + +This example uses "convention based" naming by setting the +packageWithBaseClasses property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +src/test/resources/contracts/fraud. Since you do not have two packages starting from +the contracts folder, pick only one, which should be fraud. Add the Base suffix and +capitalize fraud. That gives you the FraudBase test class name. + +All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use Rest Assured MVC to +start the server side FraudDetectionController. +/* + * Copyright 2013-2019 the original author or 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. + */ + +package com.example.fraud; + +import io.restassured.module.mockmvc.RestAssuredMockMvc; +import org.junit.Before; + +public class FraudBase { + + @Before + public void setup() { + RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(), + new FraudStatsController(stubbedStatsProvider())); + } + + private StatsProvider stubbedStatsProvider() { + return fraudType -> { + switch (fraudType) { + case DRUNKS: + return 100; + case ALL: + return 200; + } + return 0; + }; + } + + public void assertThatRejectionReasonIsNull(Object rejectionReason) { + assert rejectionReason == null; + } + +} +Now, if you run the ./mvnw clean install, you get something like this: +Results : + +Tests in error: + ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... +This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this: +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the +value(consumer(…​), producer(…​)) blocks got injected into the test. +In case of using YAML, the same applied for the matchers sections of the response. +Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the red part of red, green, and +refactor. It is time to convert the red into the green. +Write the missing implementation. +Because you know the expected input and expected output, you can write the missing +implementation: +@RequestMapping(value = "/fraudcheck", method = PUT) +public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) { +if (amountGreaterThanThreshold(fraudCheck)) { + return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH); +} +return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON); +} +When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud +Contract Verifier plugin adds the tests to the generated-test-sources, you can +actually run those tests from your IDE. +Deploy your app. +Once you finish your work, you can deploy your change. First, merge the branch: +$ git checkout master +$ git merge --no-ff contract-change-pr +$ git push origin master +Your CI might run something like ./mvnw clean deploy, which would publish both the +application and the stub artifacts. +
+
+Consumer Side (Loan Issuance) Final Step +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): +Merge branch to master. +$ git checkout master +$ git merge --no-ff contract-change-pr +Work online. +Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +stubsMode to REMOTE. The following code shows an example of +achieving the same thing by changing the properties. +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: https://repo.spring.io/libs-snapshot +That’s it! +
+
+
+Dependencies +The best way to add dependencies is to use the proper starter dependency. +For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add +spring-cloud-starter-contract-verifier. +
+
+Additional Links +Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development. +
+Spring Cloud Contract video +You can check out the video from the Warsaw JUG about Spring Cloud Contract: + +
+
+Readings + + +Slides from Marcin Grzejszczak’s talk about Accurest + + +Accurest related articles from Marcin Grzejszczak’s blog + + +Spring Cloud Contract related articles from Marcin Grzejszczak’s blog + + +Groovy docs regarding JSON + + +
+
+
+Samples +You can find some samples at +samples. +
+
+ +Spring Cloud Contract FAQ +
+Why use Spring Cloud Contract Verifier and not X ? +For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating +software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are: + + +Possibility to do CDC with messaging + + +Clear and easy to use, statically typed DSL + + +Possibility to copy paste your current JSON file to the contract and only edit its elements + + +Automatic generation of tests from the defined Contract + + +Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory + + +Spring Cloud integration - no discovery service is needed for integration tests + + +Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality + + +Via Docker adds support for any language & framework used + + +
+
+I don’t want to write a contract in Groovy! +No problem. You can write a contract in YAML! +
+
+What is this value(consumer(), producer()) ? +One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. +What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. +Imagine the following JSON request +{ + "time" : "2016-10-10 20:10:15", + "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a", + "body" : "foo" +} +and JSON response +{ + "time" : "2016-10-10 21:10:15", + "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051", + "body" : "bar" +} +Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the +database) by changing the clock in the system or providing stub implementations of data providers. The same is related +to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​ +So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system +will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned +JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words +you would like the stub to work like this: +{ + "time" : "SOMETHING THAT MATCHES TIME", + "id" : "SOMETHING THAT MATCHES UUID", + "body" : "foo" +} +As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid +{ + "time" : "2016-10-10 21:10:15", + "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051", + "body" : "bar" +} +As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks +much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. +So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the +producer’s backend can work on. Such a JSON would be a valid one: +{ + "time" : "2016-10-10 20:10:15", + "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a", + "body" : "foo" +} +On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to +contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d +have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side +what you might want is the following response: +{ + "time" : "SOMETHING THAT MATCHES TIME", + "id" : "SOMETHING THAT MATCHES UUID", + "body" : "bar" +} +How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? +In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both +sides of the communication. You can pass the values: +Either via the value method +value(consumer(...), producer(...)) +value(stub(...), test(...)) +value(client(...), server(...)) +or using the $() method +$(consumer(...), producer(...)) +$(stub(...), test(...)) +$(client(...), server(...)) +You can read more about this in the section. +Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). +Inside the producer() method you pass the value that should be used on the producer side (in the generated test). + +If on one side you have passed the regular expression and you haven’t passed the other, then the +other side will get auto-generated. + +Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')). +To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression +for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example): +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'GET' + url '/someUrl' + body([ + time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')), + id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}')) + body: "foo" + ]) + } + response { + status OK() + body([ + time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')), + id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}')) + body: "bar" + ]) + } +} + +Please read the Groovy docs related to JSON to understand how to +properly structure the request / response bodies. + +
+
+How to do Stubs versioning? +
+API Versioning +Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are +different approaches. + + +use Hypermedia, links and do not version your API by any means + + +pass versions through headers / urls + + +I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +business value should be picked. +Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. +You can create a subfolder for every version or append it to the contract name - whatever suits you more. +
+
+JAR versioning +If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches. +Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of +the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version +looks like this (it got built on the 20.10.2016 at 20:15:21) : +1.0.0.20161020-201521-RELEASE +In that case your generated stub jar will look like this. +1.0.0.20161020-201521-RELEASE-stubs.jar +In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the + latest version of the stubs. You can do that by passing the + sign. Example +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"}) +If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar +version. Example for 2.1.1. +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"}) +
+
+Dev or prod stubs +You can manipulate the classifier to run the tests against current development version of the stubs of other services + or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier + once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs. +Example of tests using development version of stubs +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"}) +Example of tests using production version of stubs +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"}) +You can pass those values also via properties from your deployment pipeline. +
+
+
+Common repo with contracts +Another way of storing contracts other than having them with the producer is keeping them in a common place. +It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep +contracts in a single place then you, as a producer, will know how many consumers you have and which +consumer you will break with your local changes. +
+Repo structure +Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, +client2, client3. Then in the repository with common contracts you would have the following setup +(which you can checkout here): +├── com +│   └── example +│   └── server +│   ├── client1 +│   │   └── expectation.groovy +│   ├── client2 +│   │   └── expectation.groovy +│   ├── client3 +│   │   └── expectation.groovy +│   └── pom.xml +├── mvnw +├── mvnw.cmd +├── pom.xml +└── src + └── assembly + └── contracts.xml +As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have +expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL +contract files as described throughout this documentation. This repository has to produce a JAR file that maps +one to one to the contents of the repo. +Example of a pom.xml inside the server folder. +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>com.example</groupId> + <artifactId>server</artifactId> + <version>0.0.1-SNAPSHOT</version> + + <name>Server Stubs</name> + <description>POM used to install locally stubs for consumer side</description> + + <parent> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-parent</artifactId> + <version>2.1.3.RELEASE</version> + <relativePath/> + </parent> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <java.version>1.8</java.version> + <spring-cloud-contract.version>2.1.2.BUILD-SNAPSHOT</spring-cloud-contract.version> + <spring-cloud-release.version>Greenwich.BUILD-SNAPSHOT + </spring-cloud-release.version> + <excludeBuildFolders>true</excludeBuildFolders> + </properties> + + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-dependencies</artifactId> + <version>${spring-cloud-release.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> + + <build> + <plugins> + <plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <!-- By default it would search under src/test/resources/ --> + <contractsDirectory>${project.basedir}</contractsDirectory> + </configuration> + </plugin> + </plugins> + </build> + + <repositories> + <repository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + <repository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + <pluginRepositories> + <pluginRepository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + </pluginRepositories> + +</project> +As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install + stubs of the producer project. +The pom.xml in the root folder can look like this: +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>com.example.standalone</groupId> + <artifactId>contracts</artifactId> + <version>0.0.1-SNAPSHOT</version> + + <name>Contracts</name> + <description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the + producers to generate tests and stubs + </description> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + </properties> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <id>contracts</id> + <phase>prepare-package</phase> + <goals> + <goal>single</goal> + </goals> + <configuration> + <attach>true</attach> + <descriptor>${basedir}/src/assembly/contracts.xml</descriptor> + <!-- If you want an explicit classifier remove the following line --> + <appendAssemblyId>false</appendAssemblyId> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> +It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here: +<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd"> + <id>project</id> + <formats> + <format>jar</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <fileSets> + <fileSet> + <directory>${project.basedir}</directory> + <outputDirectory>/</outputDirectory> + <useDefaultExcludes>true</useDefaultExcludes> + <excludes> + <exclude>**/${project.build.directory}/**</exclude> + <exclude>mvnw</exclude> + <exclude>mvnw.cmd</exclude> + <exclude>.mvn/**</exclude> + <exclude>src/**</exclude> + </excludes> + </fileSet> + </fileSets> +</assembly> +
+
+Workflow +The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference + is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on + common contracts in a common repository. +
+
+Consumer +When the consumer wants to work on the contracts offline, instead of cloning the producer code, the +consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) +and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts. + +You need to have Maven installed locally + +
+
+Producer +As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency +of the JAR containing the contracts: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <configuration> + <contractsMode>REMOTE</contractsMode> + <contractsRepositoryUrl> + https://link/to/your/nexus/or/artifactory/or/sth + </contractsRepositoryUrl> + <contractDependency> + <groupId>com.example.standalone</groupId> + <artifactId>contracts</artifactId> + </contractDependency> + </configuration> +</plugin> +With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from http://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the +tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken +when some incompatible changes are done. +The rest of the flow looks the same. +
+
+How can I define messaging contracts per topic not per producer? +To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, +we could create the structure when the rest contracts would be placed in a folder per producer and messaging +contracts in the folder per topic. +
+For Maven Project +To make it possible to work on the producer side we should specify an inclusion pattern for +filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin +allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid. +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <configuration> + <contractsMode>REMOTE</contractsMode> + <contractsRepositoryUrl>http://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl> + <contractDependency> + <groupId>com.example</groupId> + <artifactId>common-repo-with-contracts</artifactId> + <version>+</version> + </contractDependency> + <contractsPath>/</contractsPath> + <baseClassMappings> + <baseClassMapping> + <contractPackageRegex>.*messaging.*</contractPackageRegex> + <baseClassFQN>com.example.services.MessagingBase</baseClassFQN> + </baseClassMapping> + <baseClassMapping> + <contractPackageRegex>.*rest.*</contractPackageRegex> + <baseClassFQN>com.example.services.TestBase</baseClassFQN> + </baseClassMapping> + </baseClassMappings> + <includedFiles> + <includedFile>**/${project.artifactId}/**</includedFile> + <includedFile>**/${first-topic}/**</includedFile> + <includedFile>**/${second-topic}/**</includedFile> + </includedFiles> + </configuration> +</plugin> +
+
+For Gradle Project + + +Add a custom configuration for the common-repo dependency: + + +ext { + conractsGroupId = "com.example" + contractsArtifactId = "common-repo" + contractsVersion = "1.2.3" +} + +configurations { + contracts { + transitive = false + } +} + + +Add the common-repo dependency to your classpath: + + +dependencies { + contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}" + testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}" +} + + +Download the dependency to an appropriate folder: + + +task getContracts(type: Copy) { + from configurations.contracts + into new File(project.buildDir, "downloadedContracts") +} + + +Unzip JAR: + + +task unzipContracts(type: Copy) { + def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar") + def outputDir = file("${buildDir}/unpackedContracts") + + from zipTree(zipFile) + into outputDir +} + + +Cleanup unused contracts: + + +task deleteUnwantedContracts(type: Delete) { + delete fileTree(dir: "${buildDir}/unpackedContracts", + include: "**/*", + excludes: [ + "**/${project.name}/**"", + "**/${first-topic}/**", + "**/${second-topic}/**"]) +} + + +Create task dependencies: + + +unzipContracts.dependsOn("getContracts") +deleteUnwantedContracts.dependsOn("unzipContracts") +build.dependsOn("deleteUnwantedContracts") + + +Configure plugin by specifying the directory containing contracts using contractsDslDir property + + +contracts { + contractsDslDir = new File("${buildDir}/unpackedContracts") +} +
+
+
+
+Do I need a Binary Storage? Can’t I use Git? +In the polyglot world, there are languages that don’t use binary storages like +Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide +mechanisms to store contracts and stubs in a SCM repository. Currently the +only supported SCM is Git. +The repository would have to the following setup +(which you can checkout here): +. +└── META-INF + └── com.example + └── beer-api-producer-git + └── 0.0.1-SNAPSHOT + ├── contracts + │   └── beer-api-consumer + │   ├── messaging + │   │   ├── shouldSendAcceptedVerification.groovy + │   │   └── shouldSendRejectedVerification.groovy + │   └── rest + │   ├── shouldGrantABeerIfOldEnough.groovy + │   └── shouldRejectABeerIfTooYoung.groovy + └── mappings + └── beer-api-consumer + └── rest + ├── shouldGrantABeerIfOldEnough.json + └── shouldRejectABeerIfTooYoung.json +Under META-INF folder: + + +we group applications via groupId (e.g. com.example) + + +then each application is represented via the artifactId (e.g. beer-api-producer-git) + + +next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning) + + ++ or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means: + + +if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT + + +if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE + + +if you have a version called latest or + we will pick that folder + + + + +release - to find the latest release version of your stubs. That means: + + +if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE + + +if you have a version called release we will pick that folder + + + + + + +finally, there are two folders: + + +contracts - the good practice is to store the contracts required by each +consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you +can use the stubs-per-consumer feature. Further directory structure is arbitrary. + + +mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push +the stub server mappings. On the consumer side, Stub Runner will scan this folder +to start stub servers with stub definitions. The folder structure will be a copy +of the one created in the contracts subfolder. + + + + +
+Protocol convention +In order to control the type and location of the source of contracts (whether it’s +a binary storage or an SCM repository), you can use the protocol in the URL of +the repository. Spring Cloud Contract iterates over registered protocol resolvers +and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner). +For the SCM functionality, currently, we support the Git repository. To use it, +in the property, where the repository URL needs to be placed you just have to prefix +the connection URL with git://. Here you can find a couple of examples: +git://file:///foo/bar +git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git +git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git +
+
+Producer +For the producer, to use the SCM approach, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the SCM implementation via the URL that contains +the git:// protocol. + +You have to manually add the pushStubsToScm +goal in Maven or execute (bind) the pushStubsToScm task in +Gradle. We don’t push stubs to origin of your git +repository out of the box. + + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <!-- Base class mappings etc. --> + + <!-- We want to pick contracts from a Git repository --> + <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl> + + <!-- We reuse the contract dependency section to set up the path + to the folder that contains the contract definitions. In our case the + path will be /groupId/artifactId/version/contracts --> + <contractDependency> + <groupId>${project.groupId}</groupId> + <artifactId>${project.artifactId}</artifactId> + <version>${project.version}</version> + </contractDependency> + + <!-- The contracts mode can't be classpath --> + <contractsMode>REMOTE</contractsMode> + </configuration> + <executions> + <execution> + <phase>package</phase> + <goals> + <!-- By default we will not push the stubs back to SCM, + you have to explicitly add it as a goal --> + <goal>pushStubsToScm</goal> + </goals> + </execution> + </executions> +</plugin> + + + +Gradle + +contracts { + // We want to pick contracts from a Git repository + contractDependency { + stringNotation = "${project.group}:${project.name}:${project.version}" + } + /* + We reuse the contract dependency section to set up the path + to the folder that contains the contract definitions. In our case the + path will be /groupId/artifactId/version/contracts + */ + contractRepository { + repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git" + } + // The mode can't be classpath + contractsMode = "REMOTE" + // Base class mappings etc. +} + +/* +In this scenario we want to publish stubs to SCM whenever +the `publish` task is executed +*/ +publish.dependsOn("publishStubsToScm") + + +With such a setup: + + +Git project will be cloned to a temporary directory + + +The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder +to find contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/contracts + + +Tests will be generated from the contracts + + +Stubs will be created from the contracts + + +Once the tests pass, the stubs will be committed in the cloned repository + + +Finally, a push will be done to that repo’s origin + + +
+
+Producer with contracts stored locally +Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle. + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <!-- In the default configuration, we want to use the contracts stored locally --> + <configuration> + <baseClassMappings> + <baseClassMapping> + <contractPackageRegex>.*messaging.*</contractPackageRegex> + <baseClassFQN>com.example.BeerMessagingBase</baseClassFQN> + </baseClassMapping> + <baseClassMapping> + <contractPackageRegex>.*rest.*</contractPackageRegex> + <baseClassFQN>com.example.BeerRestBase</baseClassFQN> + </baseClassMapping> + </baseClassMappings> + <basePackageForTests>com.example</basePackageForTests> + </configuration> + <executions> + <execution> + <phase>package</phase> + <goals> + <!-- By default we will not push the stubs back to SCM, + you have to explicitly add it as a goal --> + <goal>pushStubsToScm</goal> + </goals> + <configuration> + <!-- We want to pick contracts from a Git repository --> + <contractsRepositoryUrl>git://file://${env.ROOT}/target/contract_empty_git/ + </contractsRepositoryUrl> + <!-- Example of URL via git protocol --> + <!--<contractsRepositoryUrl>git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>--> + <!-- Example of URL via http protocol --> + <!--<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>--> + <!-- We reuse the contract dependency section to set up the path + to the folder that contains the contract definitions. In our case the + path will be /groupId/artifactId/version/contracts --> + <contractDependency> + <groupId>${project.groupId}</groupId> + <artifactId>${project.artifactId}</artifactId> + <version>${project.version}</version> + </contractDependency> + <!-- The mode can't be classpath --> + <contractsMode>LOCAL</contractsMode> + </configuration> + </execution> + </executions> +</plugin> + + + +Gradle + +contracts { + // Base package for generated tests + basePackageForTests = "com.example" + baseClassMappings { + baseClassMapping(".*messaging.*", "com.example.BeerMessagingBase") + baseClassMapping(".*rest.*", "com.example.BeerRestBase") + } +} + +/* +In this scenario we want to publish stubs to SCM whenever +the `publish` task is executed +*/ +publishStubsToScm { + // We want to modify the default set up of the plugin when publish stubs to scm is called + customize { + // We want to pick contracts from a Git repository + contractDependency { + stringNotation = "${project.group}:${project.name}:${project.version}" + } + /* + We reuse the contract dependency section to set up the path + to the folder that contains the contract definitions. In our case the + path will be /groupId/artifactId/version/contracts + */ + contractRepository { + repositoryUrl = "git://file://${System.getenv("ROOT")}/target/contract_empty_git/" + } + // The mode can't be classpath + contractsMode = "LOCAL" + } +} + +publish.dependsOn("publishStubsToScm") +publishToMavenLocal.dependsOn("publishStubsToScm") + + +With such a setup: + + +Contracts from the default src/test/resources/contracts directory will be picked + + +Tests will be generated from the contracts + + +Stubs will be created from the contracts + + +Once the tests pass + + +Git project will be cloned to a temporary directory + + +The stubs and contracts will be committed in the cloned repository + + + + +Finally, a push will be done to that repo’s origin + + +
+Keeping contracts with the producer and stubs in an external repository +It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. +This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to +use an artifact repository for storing the stubs. +In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set +contractsRepositoryUrl to the repository where you want to keep the stubs. +
+
+
+Consumer +On the consumer side when passing the repositoryRoot parameter, +either from the @AutoConfigureStubRunner annotation, the +JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the +SCM repository, prefixed with the protocol. For example +@AutoConfigureStubRunner( + stubsMode="REMOTE", + repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git", + ids="com.example:bookstore:0.0.1.RELEASE" +) +With such a setup: + + +Git project will be cloned to a temporary directory + + +The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder +to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/ + + +Stub servers will be started and fed with mappings + + +Messaging definitions will be read and used in the messaging tests + + +
+
+
+Can I use the Pact Broker? +When using Pact you can use the Pact Broker +to store and share Pact definitions. Starting from Spring Cloud Contract +2.0.0 one can fetch Pact files from the Pact Broker to generate +tests and stubs. +As a prerequisite the Pact Converter and Pact Stub Downloader +are required. You have to add them via the spring-cloud-contract-pact dependency. +You can read more about it in the section. + +Pact follows the Consumer Contract convention. That means +that the Consumer creates the Pact definitions first, then +shares the files with the Producer. Those expectations are generated +from the Consumer’s code and can break the Producer if the expectations +are not met. + +
+Pact Consumer +The consumer uses Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. An example of such +setup can be found here. +
+
+Producer +For the producer, to use the Pact files from the Pact Broker, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the Pact implementation via the URL that contains +the pact:// protocol. It’s enough to pass the URL to the +Pact Broker. An example of such setup can be found here. + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <!-- Base class mappings etc. --> + + <!-- We want to pick contracts from a Git repository --> + <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl> + + <!-- We reuse the contract dependency section to set up the path + to the folder that contains the contract definitions. In our case the + path will be /groupId/artifactId/version/contracts --> + <contractDependency> + <groupId>${project.groupId}</groupId> + <artifactId>${project.artifactId}</artifactId> + <!-- When + is passed, a latest tag will be applied when fetching pacts --> + <version>+</version> + </contractDependency> + + <!-- The contracts mode can't be classpath --> + <contractsMode>REMOTE</contractsMode> + </configuration> + <!-- Don't forget to add spring-cloud-contract-pact to the classpath! --> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-pact</artifactId> + <version>${spring-cloud-contract.version}</version> + </dependency> + </dependencies> +</plugin> + + + +Gradle + +buildscript { + repositories { + //... + } + + dependencies { + // ... + // Don't forget to add spring-cloud-contract-pact to the classpath! + classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}" + } +} + +contracts { + // When + is passed, a latest tag will be applied when fetching pacts + contractDependency { + stringNotation = "${project.group}:${project.name}:+" + } + contractRepository { + repositoryUrl = "pact://http://localhost:8085" + } + // The mode can't be classpath + contractsMode = "REMOTE" + // Base class mappings etc. +} + + +With such a setup: + + +Pact files will be downloaded from the Pact Broker + + +Spring Cloud Contract will convert the Pact files into tests and stubs + + +The JAR with the stubs gets automatically created as usual + + +
+
+Pact Consumer (Producer Contract approach) +In the scenario where you don’t want to do Consumer Contract approach +(for every single consumer define the expectations) but you’d prefer +to do Producer Contracts (the producer provides the contracts and +publishes stubs), it’s enough to use Spring Cloud Contract with +Stub Runner option. An example of such setup can be found here. +First, remember to add Stub Runner and Spring Cloud Contract Pact module +as test dependencies. + +Maven + +<dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-dependencies</artifactId> + <version>${spring-cloud.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> +</dependencyManagement> + +<!-- Don't forget to add spring-cloud-contract-pact to the classpath! --> +<dependencies> + <!-- ... --> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-pact</artifactId> + <scope>test</scope> + </dependency> +</dependencies> + + + +Gradle + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} + +dependencies { + //... + testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner") + // Don't forget to add spring-cloud-contract-pact to the classpath! + testCompile("org.springframework.cloud:spring-cloud-contract-pact") +} + + +Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed +with pact:// protocol. E.g. pact://http://localhost:8085 +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE, + ids = "com.example:beer-api-producer-pact", + repositoryRoot = "pact://http://localhost:8085") +public class BeerControllerTest { + //Inject the port of the running stub + @StubRunnerPort("beer-api-producer-pact") int producerPort; + //... +} +With such a setup: + + +Pact files will be downloaded from the Pact Broker + + +Spring Cloud Contract will convert the Pact files into stub definitions + + +The stub servers will be started and fed with stubs + + +For more information about Pact support you can go to +the section. +
+
+
+How can I debug the request/response being sent by the generated tests client? +The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties +logging.level.org.apache.http.wire=DEBUG +
+How can I debug the mapping/request/response being sent by WireMock? +Starting from version 1.2.0 we turn on WireMock logging to +info and the WireMock notifier to being verbose. Now you will +exactly know what request was received by WireMock server and which +matching response definition was picked. +To turn off this feature just bump WireMock logging to ERROR +logging.level.com.github.tomakehurst.wiremock=ERROR +
+
+How can I see what got registered in the HTTP server stub? +You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or +`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server +was started will be attached. +
+
+Can I reference text from file? +Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays. +If you’re using YAML just use the bodyFromFile property. +
+
+
+ +Spring Cloud Contract Verifier Setup +You can set up Spring Cloud Contract Verifier in the following ways: + + +As a Gradle project + + +As a Maven project + + +As a Docker project + + +
+Gradle Project +To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Prerequisites +In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin. + +If you want to use Spock in your projects, you must add separately the +spock-core and spock-spring modules. Check Spock +docs for more information + +
+
+Add Gradle Plugin with Dependencies +To add a Gradle plugin with dependencies, use code similar to this: +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" + classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}" + } +} + +apply plugin: 'groovy' +apply plugin: 'spring-cloud-contract' + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}" + } +} + +dependencies { + testCompile 'org.codehaus.groovy:groovy-all:2.4.6' + // example with adding Spock core and Spock Spring + testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' + testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4' + testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' +} +
+
+Gradle and Rest Assured 2.0 +By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here: +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" + classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}" + classpath "com.jayway.restassured:rest-assured:2.5.0" + classpath "com.jayway.restassured:spring-mock-mvc:2.5.0" + } +} + +depenendencies { + // all dependencies + // you can exclude rest-assured from spring-cloud-contract-verifier + testCompile "com.jayway.restassured:rest-assured:2.5.0" + testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0" +} +That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly. +
+
+Snapshot Versions for Gradle +Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here: +buildscript { + repositories { + mavenCentral() + mavenLocal() + maven { url "https://repo.spring.io/snapshot" } + maven { url "https://repo.spring.io/milestone" } + maven { url "https://repo.spring.io/release" } + } +} +
+
+Add stubs +By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. +The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure: +src/test/resources/contracts/myservice/shouldCreateUser.groovy +src/test/resources/contracts/myservice/shouldReturnUser.groovy +Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods: + + +shouldCreateUser() + + +shouldReturnUser() + + +
+
+Run the Plugin +The plugin registers itself to be invoked before a check task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the generateContractTests task. +
+
+Default Setup +The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode): +contracts { + testFramework ='JUNIT' + testMode = 'MockMvc' + generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts") + generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts") + contractsDslDir = "${project.rootDir}/src/test/resources/contracts" + basePackageForTests = 'org.springframework.cloud.verifier.tests' + stubsOutputDir = project.file("${project.buildDir}/stubs") + + // the following properties are used when you want to provide where the JAR with contract lays + contractDependency { + stringNotation = '' + } + contractsPath = '' + contractsWorkOffline = false + contractRepository { + cacheDownloadedContracts(true) + } +} + +tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') { + baseName = project.name + classifier = contracts.stubsSuffix + from contractVerifier.stubsOutputDir +} + +project.artifacts { + archives task +} + +tasks.create(type: Copy, name: 'copyContracts') { + from contracts.contractsDslDir + into contracts.stubsOutputDir +} + +verifierStubsJar.dependsOn 'copyContracts' + +publishing { + publications { + stubs(MavenPublication) { + artifactId project.name + artifact verifierStubsJar + } + } +} +
+
+Configure Plugin +To change the default configuration, add a contracts snippet to your Gradle config, as +shown here: +contracts { + testMode = 'MockMvc' + baseClassForTests = 'org.mycompany.tests' + generatedTestSourcesDir = project.file('src/generatedContract') +} +
+
+Configuration Options + + +testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls. + + +imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array. + + +staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array. + + +basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests. + + +baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification. + + +packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. + + +baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests. + + +ruleClassForTests: Specifies a rule that should be added to the generated test +classes. + + +ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array. + + +contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts. + + +generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts. + + +generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts. + + +stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed. + + +testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework. + + +contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders. + + +The following properties are used when you want to specify the location of the JAR +containing the contracts: + + +contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up. + + +contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory. + + +contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.) + + +deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories + + +Below you can find a list of experimental features you can turn on via the plugin: + + +convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side. + + +assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. + + +
+
+Single Base Class for All Tests +When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified. +abstract class BaseMockMvcSpec extends Specification { + + def setup() { + RestAssuredMockMvc.standaloneSetup(new PairIdController()) + } + + void isProperCorrelationId(Integer correlationId) { + assert correlationId == 123456 + } + + void isEmpty(String value) { + assert value == null + } + +} +If you use Explicit mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this +base class should also contain a protected WebTarget webTarget field. Right now, the +only option to test the JAX-RS API is to start a web server. +
+
+Different Base Classes for Contracts +If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options: + + +Follow a convention by providing the packageWithBaseClasses + + +Provide explicit mapping via baseClassMappings + + +By Convention +The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure: +packageWithBaseClasses = 'com.example.base' +By Mapping +You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example: +baseClassForTests = "com.example.FooBase" +baseClassMappings { + baseClassMapping('.*/com/.*', 'com.example.ComBase') + baseClassMapping('.*/bar/.*': 'com.example.BarBase') +} +Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/ +By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase. +
+
+Invoking Generated Tests +To ensure that the provider side is compliant with defined contracts, you need to invoke: +./gradlew generateContractTests test +
+
+Pushing stubs to SCM +If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example: +$ ./gradlew pushStubsToScm +Under you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable. +
+
+Spring Cloud Contract Verifier on the Consumer Side +In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in src/test/resources/contracts and generate +WireMock JSON stubs using: +./gradlew generateClientStubs + +The stubsOutputDir option has to be set for stub generation to work. + +When present, JSON stubs can be used in automated tests of consuming a service. +@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application) +class LoanApplicationServiceSpec extends Specification { + + @ClassRule + @Shared + WireMockClassRule wireMockRule == new WireMockClassRule() + + @Autowired + LoanApplicationService sut + + def 'should successfully apply for loan'() { + given: + LoanApplication application = + new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123) + when: + LoanApplicationResult loanApplication == sut.loanApplication(application) + then: + loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED + loanApplication.rejectionReason == null + } +} +LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier. +
+
+
+Maven Project +To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Add maven plugin +Add the Spring Cloud Contract BOM in a fashion similar to this: +<dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-dependencies</artifactId> + <version>${spring-cloud-release.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> +</dependencyManagement> +Next, add the Spring Cloud Contract Verifier Maven plugin: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <packageWithBaseClasses>com.example.fraud</packageWithBaseClasses> + <convertToYaml>true</convertToYaml> + </configuration> +</plugin> +You can read more in the +Spring +Cloud Contract Maven Plugin Documentation (example for 2.0.0.RELEASE version). +
+
+Maven and Rest Assured 2.0 +By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <packageWithBaseClasses>com.example</packageWithBaseClasses> + </configuration> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-verifier</artifactId> + <version>${spring-cloud-contract.version}</version> + </dependency> + <dependency> + <groupId>com.jayway.restassured</groupId> + <artifactId>rest-assured</artifactId> + <version>2.5.0</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>com.jayway.restassured</groupId> + <artifactId>spring-mock-mvc</artifactId> + <version>2.5.0</version> + <scope>compile</scope> + </dependency> + </dependencies> +</plugin> + +<dependencies> + <!-- all dependencies --> + <!-- you can exclude rest-assured from spring-cloud-contract-verifier --> + <dependency> + <groupId>com.jayway.restassured</groupId> + <artifactId>rest-assured</artifactId> + <version>2.5.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.jayway.restassured</groupId> + <artifactId>spring-mock-mvc</artifactId> + <version>2.5.0</version> + <scope>test</scope> + </dependency> +</dependencies> +That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly. +
+
+Snapshot versions for Maven +For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here: +<repositories> + <repository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + <repository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> +</repositories> +<pluginRepositories> + <pluginRepository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> +</pluginRepositories> +
+
+Add stubs +By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure: +src/test/resources/contracts/myservice/shouldCreateUser.groovy +src/test/resources/contracts/myservice/shouldReturnUser.groovy +Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods + + +shouldCreateUser() + + +shouldReturnUser() + + +
+
+Run plugin +The plugin goal generateTests is assigned to be invoked in the phase called +generate-test-sources. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the generateTests goal. +
+
+Configure plugin +To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <executions> + <execution> + <goals> + <goal>convert</goal> + <goal>generateStubs</goal> + <goal>generateTests</goal> + </goals> + </execution> + </executions> + <configuration> + <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests> + <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests> + </configuration> +</plugin> +
+
+Configuration Options + + +testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls. + + +basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests. + + +ruleClassForTests: Specifies a rule that should be added to the generated test +classes. + + +baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification. + + +contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts. + + +generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts. + + +generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated + + +testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework. + + +packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix. + + +baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests. + + +contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders. + + +If you want to download your contract definitions from a Maven repository, you can use +the following options: + + +contractDependency: The contract dependency that contains all the packaged contracts. + + +contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated. + + +contractsMode: Picks the mode in which stubs will be found and registered + + +deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories + + +contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones. + + +contractsRepositoryUsername: The user name to be used to connect to the repo with contracts. + + +contractsRepositoryPassword: The password to be used to connect to the repo with contracts. + + +contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts. + + +contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts. + + +We cache only non-snapshot, explicitly provided versions (for example ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on. +Below you can find a list of experimental features you can turn on via the plugin: + + +convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side. + + +assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default. + + +
+
+Single Base Class for All Tests +When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified. +package org.mycompany.tests + +import org.mycompany.ExampleSpringController +import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc +import spock.lang.Specification + +class MvcSpec extends Specification { + def setup() { + RestAssuredMockMvc.standaloneSetup(new ExampleSpringController()) + } +} +You can also setup the whole context if necessary. +import io.restassured.module.mockmvc.RestAssuredMockMvc; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property") +public abstract class BaseTestClass { + + @Autowired + WebApplicationContext context; + + @Before + public void setup() { + RestAssuredMockMvc.webAppContextSetup(this.context); + } +} +If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests. +import io.restassured.RestAssured; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property") +public abstract class BaseTestClass { + + @LocalServerPort + int port; + + @Before + public void setup() { + RestAssured.baseURI = "http://localhost:" + this.port; + } +} +If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right +now, the only option to test the JAX-RS API is to start a web server. +
+
+Different base classes for contracts +If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options: + + +Follow a convention by providing the packageWithBaseClasses + + +provide explicit mapping via baseClassMappings + + +By Convention +The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <configuration> + <packageWithBaseClasses>hello</packageWithBaseClasses> + </configuration> +</plugin> +By Mapping +You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <configuration> + <baseClassForTests>com.example.FooBase</baseClassForTests> + <baseClassMappings> + <baseClassMapping> + <contractPackageRegex>.*com.*</contractPackageRegex> + <baseClassFQN>com.example.TestBase</baseClassFQN> + </baseClassMapping> + </baseClassMappings> + </configuration> +</plugin> +Assume that you have contracts under these two locations: +* src/test/resources/contract/com/ +* src/test/resources/contract/foo/ +By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase. +
+
+Invoking generated tests +The Spring Cloud Contract Maven Plugin generates verification code in a directory called +/generated-test-sources/contractVerifier and attaches this directory to testCompile +goal. +For Groovy Spock code, use the following: +<plugin> + <groupId>org.codehaus.gmavenplus</groupId> + <artifactId>gmavenplus-plugin</artifactId> + <version>1.5</version> + <executions> + <execution> + <goals> + <goal>testCompile</goal> + </goals> + </execution> + </executions> + <configuration> + <testSources> + <testSource> + <directory>${project.basedir}/src/test/groovy</directory> + <includes> + <include>**/*.groovy</include> + </includes> + </testSource> + <testSource> + <directory>${project.build.directory}/generated-test-sources/contractVerifier</directory> + <includes> + <include>**/*.groovy</include> + </includes> + </testSource> + </testSources> + </configuration> +</plugin> +To ensure that provider side is compliant with defined contracts, you need to invoke +mvn generateTest test. +
+
+Pushing stubs to SCM +If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example: +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <!-- Base class mappings etc. --> + + <!-- We want to pick contracts from a Git repository --> + <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl> + + <!-- We reuse the contract dependency section to set up the path + to the folder that contains the contract definitions. In our case the + path will be /groupId/artifactId/version/contracts --> + <contractDependency> + <groupId>${project.groupId}</groupId> + <artifactId>${project.artifactId}</artifactId> + <version>${project.version}</version> + </contractDependency> + + <!-- The contracts mode can't be classpath --> + <contractsMode>REMOTE</contractsMode> + </configuration> + <executions> + <execution> + <phase>package</phase> + <goals> + <!-- By default we will not push the stubs back to SCM, + you have to explicitly add it as a goal --> + <goal>pushStubsToScm</goal> + </goals> + </execution> + </executions> +</plugin> +Under you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable. +
+
+Maven Plugin and STS +If you see the following exception while using STS: + + + + + +STS Exception + + +When you click on the error marker you should see something like this: + plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring- + cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at + org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at +... + org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at + org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at + org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at +In order to fix this issue, provide the following section in your pom.xml: +<build> + <pluginManagement> + <plugins> + <!--This plugin's configuration is used to store Eclipse m2e settings + only. It has no influence on the Maven build itself. --> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <versionRange>[1.0,)</versionRange> + <goals> + <goal>convert</goal> + </goals> + </pluginExecutionFilter> + <action> + <execute /> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + </plugins> + </pluginManagement> +</build> +
+
+Maven Plugin with Spock Tests +You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly. +First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below: + +If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example: + +
+
+
+Stubs and Transitive Dependencies +The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom: +├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar +├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1 +├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar +├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1 +├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar +├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom +├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar +├── ... +└── ... +There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies: + + +Mark all application dependencies as optional + + +Create a separate artifactid for the stubs + + +Exclude dependencies on the consumer side + + +Mark all application dependencies as optional +If, in the github-webhook application, you mark all of your dependencies as optional, +when you include the github-webhook stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded. +Create a separate artifactid for the stubs +If you create a separate artifactid, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all. +Exclude dependencies on the consumer side +As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies. +
+
+Scenarios +You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example: +my_contracts_dir\ + scenario1\ + 1_login.groovy + 2_showCart.groovy + 3_logout.groovy +Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps: + + +login marked as Started pointing to…​ + + +showCart marked as Step1 pointing to…​ + + +logout marked as Step2 which will close the scenario. + + +More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/ +Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution. +
+
+Docker Project +We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application. + +The EXPLICIT mode means that the tests generated from contracts will send +real requests and not the mocked ones. + +
+Short intro to Maven, JARs and Binary storage +Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults. +Part of the following definitions were taken from the Maven Glossary + + +Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects. + + +Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group. + + +JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file. + + +GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/. + + +Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier. + + +Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus. + + +
+
+How it works +The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes). +It’s enough for you to mount your contracts, pass the environment variables + and the image will: + + +generate the contract tests + + +execute the tests against the provided URL + + +generate the WireMock stubs + + +(optional - turned on by default) publish the stubs to a Artifact Manager + + +
+Environment Variables +The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc. + + +PROJECT_GROUP - your project’s group id. Defaults to com.example + + +PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT + + +PROJECT_NAME - artifact id. Defaults to example + + +REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally + + +REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured + + +REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured + + +PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true. + + +These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable. + + +EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example + + +EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts. + + +EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default + + +EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest + + +EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally + + +EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path. + + +EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL. + + +These environment variables are used when tests are executed: + + +APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work) + + +APPLICATION_USERNAME - (optional) username for basic authentication to your application + + +APPLICATION_PASSWORD - (optional) password for basic authentication to your application + + +
+
+
+Example of usage +Let’s take a look at a simple MVC application +$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs +$ cd bookstore +The contracts are available under /contracts folder. +
+
+Server side (nodejs) +Since we want to run tests, we could just execute: +$ npm test +however, for learning purposes, let’s split it into pieces: +# Stop docker infra (nodejs, artifactory) +$ ./stop_infra.sh +# Start docker infra (nodejs, artifactory) +$ ./setup_infra.sh + +# Kill & Run app +$ pkill -f "node app" +$ nohup node app & + +# Prepare environment variables +$ SC_CONTRACT_DOCKER_VERSION="..." +$ APP_IP="192.168.0.100" +$ APP_PORT="3000" +$ ARTIFACTORY_PORT="8081" +$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}" +$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local" +$ CURRENT_DIR="$( pwd )" +$ CURRENT_FOLDER_NAME=${PWD##*/} +$ PROJECT_VERSION="0.0.1.RELEASE" + +# Execute contract tests +$ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}" + +# Kill app +$ pkill -f "node app" +What will happen is that via bash scripts: + + +infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time. + + +due to those constraints the contracts also represent the +stateful situation + + +first request is a POST that causes data to get inserted to the database + + +second request is a GET that returns a list of data with 1 previously inserted element + + + + +the NodeJS application will be started (on port 3000) + + +contract tests will be generated via Docker and tests +will be executed against the running application + + +the contracts will be taken from /contracts folder. + + +the output of the test execution is available under +node_modules/spring-cloud-contract/output. + + + + +the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar. + + +To see how the client side looks like check out the section. +
+
+
+ +Spring Cloud Contract Verifier Messaging +Spring Cloud Contract Verifier lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that. +
+Integrations +You can use one of the following four integration configurations: + + +Apache Camel + + +Spring Integration + + +Spring Cloud Stream + + +Spring AMQP + + +Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up. + +Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work. + + +If you want to use Spring Cloud Stream, remember to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support, as shown here: + + +Maven + +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-stream-test-support</artifactId> + <scope>test</scope> +</dependency> + + + +Gradle + +testCompile "org.springframework.cloud:spring-cloud-stream-test-support" + + +
+
+Manual Integration Testing +The main interface used by the tests is +org.springframework.cloud.contract.verifier.messaging.MessageVerifier. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal. +In a test, you can inject a ContractVerifierMessageExchange to send and receive +messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. +Here’s an example: +@RunWith(SpringTestRunner.class) +@SpringBootTest +@AutoConfigureMessageVerifier +public static class MessagingContractTests { + + @Autowired + private MessageVerifier verifier; + ... +} + +If your tests require stubs as well, then @AutoConfigureStubRunner includes the +messaging configuration, so you only need the one annotation. + +
+
+Publisher-Side Test Generation +Having the input or outputMessage sections in your DSL results in creation of tests +on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5 or Spock tests. +There are 3 main scenarios that we should take into consideration: + + +Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler). + + +Scenario 2: The input message triggers an output message. + + +Scenario 3: The input message is consumed and there is no output message. + + + +The destination passed to messageFrom or sentTo can have different +meanings for different messaging implementations. For Stream and Integration it is +first resolved as a destination of a channel. Then, if there is no such destination +it is resolved as a channel name. For Camel, that’s a certain component (for example, +jms). + +
+Scenario 1: No Input Message +For the given contract: + +Groovy DSL + + def contractDsl = Contract.make { + label 'some_label' + input { + triggeredBy('bookReturnedTriggered()') + } + outputMessage { + sentTo('activemq:output') + body('''{ "bookName" : "foo" }''') + headers { + header('BOOK-NAME', 'foo') + messagingContentType(applicationJson()) + } + } + } + + + +YAML + +label: some_label +input: + triggeredBy: bookReturnedTriggered +outputMessage: + sentTo: activemq:output + body: + bookName: foo + headers: + BOOK-NAME: foo + contentType: application/json + + +The following JUnit test is created: + ''' + // when: + bookReturnedTriggered(); + + // then: + ContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output"); + assertThat(response).isNotNull(); + assertThat(response.getHeader("BOOK-NAME")).isNotNull(); + assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo"); + assertThat(response.getHeader("contentType")).isNotNull(); + assertThat(response.getHeader("contentType").toString()).isEqualTo("application/json"); + // and: + DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload())); + assertThatJson(parsedJson).field("bookName").isEqualTo("foo"); +''' +And the following Spock test would be created: + ''' + when: + bookReturnedTriggered() + + then: + ContractVerifierMessage response = contractVerifierMessaging.receive('activemq:output') + assert response != null + response.getHeader('BOOK-NAME')?.toString() == 'foo' + response.getHeader('contentType')?.toString() == 'application/json' + and: + DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload)) + assertThatJson(parsedJson).field("bookName").isEqualTo("foo") + +''' +
+
+Scenario 2: Output Triggered by Input +For the given contract: + +Groovy DSL + + def contractDsl = Contract.make { + label 'some_label' + input { + messageFrom('jms:input') + messageBody([ + bookName: 'foo' + ]) + messageHeaders { + header('sample', 'header') + } + } + outputMessage { + sentTo('jms:output') + body([ + bookName: 'foo' + ]) + headers { + header('BOOK-NAME', 'foo') + } + } + } + + + +YAML + +label: some_label +input: + messageFrom: jms:input + messageBody: + bookName: 'foo' + messageHeaders: + sample: header +outputMessage: + sentTo: jms:output + body: + bookName: foo + headers: + BOOK-NAME: foo + + +The following JUnit test is created: + ''' +// given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + "{\\"bookName\\":\\"foo\\"}" +, headers() + .header("sample", "header")); + +// when: + contractVerifierMessaging.send(inputMessage, "jms:input"); + +// then: + ContractVerifierMessage response = contractVerifierMessaging.receive("jms:output"); + assertThat(response).isNotNull(); + assertThat(response.getHeader("BOOK-NAME")).isNotNull(); + assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo"); +// and: + DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload())); + assertThatJson(parsedJson).field("bookName").isEqualTo("foo"); +''' +And the following Spock test would be created: + """\ +given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + '''{"bookName":"foo"}''', + ['sample': 'header'] + ) + +when: + contractVerifierMessaging.send(inputMessage, 'jms:input') + +then: + ContractVerifierMessage response = contractVerifierMessaging.receive('jms:output') + assert response !- null + response.getHeader('BOOK-NAME')?.toString() == 'foo' +and: + DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload)) + assertThatJson(parsedJson).field("bookName").isEqualTo("foo") +""" +
+
+Scenario 3: No Output Message +For the given contract: + +Groovy DSL + + def contractDsl = Contract.make { + label 'some_label' + input { + messageFrom('jms:delete') + messageBody([ + bookName: 'foo' + ]) + messageHeaders { + header('sample', 'header') + } + assertThat('bookWasDeleted()') + } + } + + + +YAML + +label: some_label +input: + messageFrom: jms:delete + messageBody: + bookName: 'foo' + messageHeaders: + sample: header + assertThat: bookWasDeleted() + + +The following JUnit test is created: + ''' +// given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + "{\\"bookName\\":\\"foo\\"}" +, headers() + .header("sample", "header")); + +// when: + contractVerifierMessaging.send(inputMessage, "jms:delete"); + +// then: + bookWasDeleted(); +''' +And the following Spock test would be created: + ''' +given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + \'\'\'{"bookName":"foo"}\'\'\', + ['sample': 'header'] + ) + +when: + contractVerifierMessaging.send(inputMessage, 'jms:delete') + +then: + noExceptionThrown() + bookWasDeleted() +''' +
+
+
+Consumer Stub Generation +Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created. +For more information, see section. + +Maven + +<dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-stream-rabbit</artifactId> + </dependency> + + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-stream-test-support</artifactId> + <scope>test</scope> + </dependency> +</dependencies> + +<dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-dependencies</artifactId> + <version>Greenwich.BUILD-SNAPSHOT</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> +</dependencyManagement> + + + +Gradle + +ext { + contractsDir = file("mappings") + stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/") +} + +// Automatically added by plugin: +// copyContracts - copies contracts to the output folder from which JAR will be created +// verifierStubsJar - JAR with a provided stub suffix +// the presented publication is also added by the plugin but you can modify it as you wish + +publishing { + publications { + stubs(MavenPublication) { + artifactId "${project.name}-stubs" + artifact verifierStubsJar + } + } +} + + +
+
+ +Spring Cloud Contract Stub Runner +One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging. +Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you. +
+Snapshot versions +Add the additional snapshot repository to your build.gradle file to use snapshot +versions, which are automatically uploaded after every successful build: + +Maven + +<repositories> + <repository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + <repository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> +</repositories> +<pluginRepositories> + <pluginRepository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> +</pluginRepositories> + + + +Gradle + +buildscript { + repositories { + mavenCentral() + mavenLocal() + maven { url "https://repo.spring.io/snapshot" } + maven { url "https://repo.spring.io/milestone" } + maven { url "https://repo.spring.io/release" } + } + + +
+
+Publishing Stubs as JARs +The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository. + +For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to. + + +Maven + +<!-- First disable the default jar setup in the properties section --> +<!-- we don't want the verifier to do a jar for us --> +<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip> + +<!-- Next add the assembly plugin to your build --> +<!-- we want the assembly plugin to generate the JAR --> +<plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <id>stub</id> + <phase>prepare-package</phase> + <goals> + <goal>single</goal> + </goals> + <inherited>false</inherited> + <configuration> + <attach>true</attach> + <descriptors> + ${basedir}/src/assembly/stub.xml + </descriptors> + </configuration> + </execution> + </executions> +</plugin> + +<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml --> +<assembly + xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd"> + <id>stubs</id> + <formats> + <format>jar</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <fileSets> + <fileSet> + <directory>src/main/java</directory> + <outputDirectory>/</outputDirectory> + <includes> + <include>**com/example/model/*.*</include> + </includes> + </fileSet> + <fileSet> + <directory>${project.build.directory}/classes</directory> + <outputDirectory>/</outputDirectory> + <includes> + <include>**com/example/model/*.*</include> + </includes> + </fileSet> + <fileSet> + <directory>${project.build.directory}/snippets/stubs</directory> + <outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory> + <includes> + <include>**/*</include> + </includes> + </fileSet> + <fileSet> + <directory>${basedir}/src/test/resources/contracts</directory> + <outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory> + <includes> + <include>**/*.groovy</include> + </includes> + </fileSet> + </fileSets> +</assembly> + + + +Gradle + +ext { + contractsDir = file("mappings") + stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/") +} + +// Automatically added by plugin: +// copyContracts - copies contracts to the output folder from which JAR will be created +// verifierStubsJar - JAR with a provided stub suffix +// the presented publication is also added by the plugin but you can modify it as you wish + +publishing { + publications { + stubs(MavenPublication) { + artifactId "${project.name}-stubs" + artifact verifierStubsJar + } + } +} + + +
+
+Stub Runner Core +Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +Consumer Driven Contracts. +Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. +For messaging, special stub routes are defined. +
+Retrieving stubs +You can pick the following options of acquiring stubs + + +Aether based solution that downloads JARs with stubs from Artifactory / Nexus + + +Classpath scanning solution that searches classpath via pattern to retrieve stubs + + +Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization + + +The latter example is described in the Custom Stub Runner section. +
+Stub downloading +You can control the stub downloading via the stubsMode switch. It picks value from the +StubRunnerProperties.StubsMode enum. You can use the following options + + +StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath + + +StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2) + + +StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location + + +Example: +@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL) +
+
+Classpath scanning +If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH +(or set nothing since CLASSPATH is the default value) then classpath will get scanned. +Let’s look at the following example: +@AutoConfigureStubRunner(ids = { + "com.example:beer-api-producer:+:stubs:8095", + "com.example.foo:bar:1.0.0:superstubs:8096" +}) +If you’ve added the dependencies to your classpath + +Maven + +<dependency> + <groupId>com.example</groupId> + <artifactId>beer-api-producer-restdocs</artifactId> + <classifier>stubs</classifier> + <version>0.0.1-SNAPSHOT</version> + <scope>test</scope> + <exclusions> + <exclusion> + <groupId>*</groupId> + <artifactId>*</artifactId> + </exclusion> + </exclusions> +</dependency> +<dependency> + <groupId>com.example.foo</groupId> + <artifactId>bar</artifactId> + <classifier>superstubs</classifier> + <version>1.0.0</version> + <scope>test</scope> + <exclusions> + <exclusion> + <groupId>*</groupId> + <artifactId>*</artifactId> + </exclusion> + </exclusions> +</dependency> + + + +Gradle + +testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") { + transitive = false +} +testCompile("com.example.foo:bar:1.0.0:superstubs") { + transitive = false +} + + +Then the following locations on your classpath will get scanned. For com.example:beer-api-producer-restdocs + + +/META-INF/com.example/beer-api-producer-restdocs/*/.* + + +/contracts/com.example/beer-api-producer-restdocs/*/.* + + +/mappings/com.example/beer-api-producer-restdocs/*/.* + + +and com.example.foo:bar + + +/META-INF/com.example.foo/bar/*/.* + + +/contracts/com.example.foo/bar/*/.* + + +/mappings/com.example.foo/bar/*/.* + + + +As you can see you have to explicitly provide the group and artifact ids when packaging the +producer stubs. + +The producer would setup the contracts like this: +└── src + └── test + └── resources + └── contracts +    └── com.example +       └── beer-api-producer-restdocs +       └── nested +       └── contract3.groovy +To achieve proper stub packaging. +Or using the Maven assembly plugin or +Gradle Jar task you have to create the following +structure in your stubs jar. +└── META-INF + └── com.example + └── beer-api-producer-restdocs + └── 2.0.0 + ├── contracts + │   └── nested +    │ └── contract2.groovy +    └── mappings +    └── mapping.json +By maintaining this structure classpath gets scanned and you can profit from the messaging / +HTTP stubs without the need to download artifacts. +
+
+Configuring HTTP Server Stubs +Stub Runner has a notion of a HttpServerStub that abstracts the underlaying +concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). +Sometimes, you need to perform some additional tuning of the stub servers, +that is concrete for the given implementation. To do that, Stub Runner gives you +the httpServerStubConfigurer property that is available in the annotation, +JUnit rule, and is accessible via system properties, where you can provide +your implementation of the org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer interface. The implementations can alter +the configuration files for the given HTTP server stub. +Spring Cloud Contract Stub Runner comes with an implementation that you +can extend, for WireMock - org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. In the configure method +you can provide your own, custom configuration for the given stub. The use +case might be starting WireMock for the given artifact id, on an HTTPs port. Example: + +WireMockHttpServerStubConfigurer implementation + +@CompileStatic +static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer { + + private static final Log log = LogFactory.getLog(HttpsForFraudDetection) + + @Override + WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) { + if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") { + int httpsPort = SocketUtils.findAvailableTcpPort() + log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server") + return httpStubConfiguration + .httpsPort(httpsPort) + } + return httpStubConfiguration + } +} + + +You can then reuse it via the annotation +@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/", + httpServerStubConfigurer = HttpsForFraudDetection) +Whenever an https port is found, it will take precedence over the http one. +
+
+
+Running stubs +
+Running using main app +You can set the following options to the main class: +-c, --classifier Suffix for the jar containing stubs (e. + g. 'stubs' if the stub jar would + have a 'stubs' classifier for stubs: + foobar-stubs ). Defaults to 'stubs' + (default: stubs) +--maxPort, --maxp <Integer> Maximum port value to be assigned to + the WireMock instance. Defaults to + 15000 (default: 15000) +--minPort, --minp <Integer> Minimum port value to be assigned to + the WireMock instance. Defaults to + 10000 (default: 10000) +-p, --password Password to user when connecting to + repository +--phost, --proxyHost Proxy host to use for repository + requests +--pport, --proxyPort [Integer] Proxy port to use for repository + requests +-r, --root Location of a Jar containing server + where you keep your stubs (e.g. http: + //nexus. + net/content/repositories/repository) +-s, --stubs Comma separated list of Ivy + representation of jars with stubs. + Eg. groupid:artifactid1,groupid2: + artifactid2:classifier +--sm, --stubsMode Stubs mode to be used. Acceptable values + [CLASSPATH, LOCAL, REMOTE] +-u, --username Username to user when connecting to + repository +
+
+HTTP Stubs +Stubs are defined in JSON documents, whose syntax is defined in WireMock documentation +Example: +{ + "request": { + "method": "GET", + "url": "/ping" + }, + "response": { + "status": 200, + "body": "pong", + "headers": { + "Content-Type": "text/plain" + } + } +} +
+
+Viewing registered mappings +Every stubbed collaborator exposes list of defined mappings under __/admin/ endpoint. +You can also use the mappingsOutputFolder property to dump the mappings to files. + For annotation based approach it would look like this +@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer", +mappingsOutputFolder = "target/outputmappings/") +and for the JUnit approach like this: +@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule() + .repoRoot("http://some_url") + .downloadStub("a.b.c", "loanIssuance") + .downloadStub("a.b.c:fraudDetectionServer") + .withMappingsOutputFolder("target/outputmappings") +Then if you check out the folder target/outputmappings you would see the following structure +. +├── fraudDetectionServer_13705 +└── loanIssuance_12255 +That means that there were two stubs registered. fraudDetectionServer was registered at port 13705 +and loanIssuance at port 12255. If we take a look at one of the files we would see (for WireMock) +mappings available for the given server: +[{ + "id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7", + "request" : { + "url" : "/name", + "method" : "GET" + }, + "response" : { + "status" : 200, + "body" : "fraudDetectionServer" + }, + "uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7" +}, +... +] +
+
+Messaging Stubs +Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up. +
+
+
+
+Stub Runner JUnit Rule and Stub Runner JUnit5 Extension +Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id: +@ClassRule +public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot()) + .stubsMode(StubRunnerProperties.StubsMode.REMOTE) + .downloadStub("org.springframework.cloud.contract.verifier.stubs", + "loanIssuance") + .downloadStub( + "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"); + +@BeforeClass +@AfterClass +public static void setupProps() { + System.clearProperty("stubrunner.repository.root"); + System.clearProperty("stubrunner.classifier"); +} +There’s also a StubRunnerExtension available for JUnit 5. StubRunnerRule and StubRunnerExtension work in a very +similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to: + + +download them + + +cache them locally + + +unzip them to a temporary folder + + +start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port + + +feed the WireMock server with all JSON files that are valid WireMock definitions + + +can also send messages (remember to pass an implementation of MessageVerifier interface) + + +Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. +Check their docs for more information. +Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they allow you to find the started stubs: +package org.springframework.cloud.contract.stubrunner; + +import java.net.URL; +import java.util.Collection; +import java.util.Map; + +import org.springframework.cloud.contract.spec.Contract; + +/** + * Contract for finding registered stubs. + * + * @author Marcin Grzejszczak + */ +public interface StubFinder extends StubTrigger { + + /** + * For the given groupId and artifactId tries to find the matching URL of the running + * stub. + * @param groupId - might be null. In that case a search only via artifactId takes + * place + * @param artifactId - artifact id of the stub + * @return URL of a running stub or throws exception if not found + * @throws StubNotFoundException in case of not finding a stub + */ + URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException; + + /** + * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]} + * tries to find the matching URL of the running stub. You can also pass only + * {@code artifactId}. + * @param ivyNotation - Ivy representation of the Maven artifact + * @return URL of a running stub or throws exception if not found + * @throws StubNotFoundException in case of not finding a stub + */ + URL findStubUrl(String ivyNotation) throws StubNotFoundException; + + /** + * @return all running stubs + */ + RunningStubs findAllRunningStubs(); + + /** + * @return the list of Contracts + */ + Map<StubConfiguration, Collection<Contract>> getContracts(); + +} +Example of usage in Spock tests: +@ClassRule +@Shared +StubRunnerRule rule = new StubRunnerRule() + .stubsMode(StubRunnerProperties.StubsMode.REMOTE) + .repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString()) + .downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance") + .downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer") + .withMappingsOutputFolder("target/outputmappingsforrule") + + +def 'should start WireMock servers'() { + expect: 'WireMocks are running' + rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null + rule.findStubUrl('loanIssuance') != null + rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') + rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null + and: + rule.findAllRunningStubs().isPresent('loanIssuance') + rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer') + rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') + and: 'Stubs were registered' + "${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance' + "${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer' +} + +def 'should output mappings to output folder'() { + when: + def url = rule.findStubUrl('fraudDetectionServer') + then: + new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists() +} +Example of usage in JUnit tests: + @Test + public void should_start_wiremock_servers() throws Exception { + // expect: 'WireMocks are running' + then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", + "loanIssuance")).isNotNull(); + then(rule.findStubUrl("loanIssuance")).isNotNull(); + then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl( + "org.springframework.cloud.contract.verifier.stubs", "loanIssuance")); + then(rule.findStubUrl( + "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")) + .isNotNull(); + // and: + then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue(); + then(rule.findAllRunningStubs().isPresent( + "org.springframework.cloud.contract.verifier.stubs", + "fraudDetectionServer")).isTrue(); + then(rule.findAllRunningStubs().isPresent( + "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")) + .isTrue(); + // and: 'Stubs were registered' + then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name")) + .isEqualTo("loanIssuance"); + then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")) + .isEqualTo("fraudDetectionServer"); + } + + private String httpGet(String url) throws Exception { + try (InputStream stream = URI.create(url).toURL().openStream()) { + return StreamUtils.copyToString(stream, Charset.forName("UTF-8")); + } + } + +} +JUnit 5 Extension example: +// Visible for Junit +@RegisterExtension +static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension() + .repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE) + .downloadStub("org.springframework.cloud.contract.verifier.stubs", + "loanIssuance") + .downloadStub( + "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer") + .withMappingsOutputFolder("target/outputmappingsforrule"); + +@BeforeAll +@AfterAll +static void setupProps() { + System.clearProperty("stubrunner.repository.root"); + System.clearProperty("stubrunner.classifier"); +} + +private static String repoRoot() { + try { + return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/") + .toURI().toString(); + } + catch (Exception e) { + return ""; + } +} +Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner. + +To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the +MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). +If you don’t do this, then whenever you try to send a message an exception will be thrown. + +
+Maven settings +The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above. +
+
+Providing fixed ports +You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule. +
+
+Fluent API +When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub. +@ClassRule +public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot()) + .stubsMode(StubRunnerProperties.StubsMode.REMOTE) + .downloadStub("org.springframework.cloud.contract.verifier.stubs", + "loanIssuance") + .withPort(12345).downloadStub( + "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346"); + +@BeforeClass +@AfterClass +public static void setupProps() { + System.clearProperty("stubrunner.repository.root"); + System.clearProperty("stubrunner.classifier"); +} +You can see that for this example the following test is valid: +then(rule.findStubUrl("loanIssuance")) + .isEqualTo(URI.create("http://localhost:12345").toURL()); +then(rule.findStubUrl("fraudDetectionServer")) + .isEqualTo(URI.create("http://localhost:12346").toURL()); +
+
+Stub Runner with Spring +Sets up Spring configuration of the Stub Runner project. +By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +and registers in WireMock the selected stubs. +If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use +its methods as presented below: +@ContextConfiguration(classes = Config, loader = SpringBootContextLoader) +@SpringBootTest(properties = [" stubrunner.cloud.enabled=false", + 'foo=${stubrunner.runningstubs.fraudDetectionServer.port}', + 'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}']) +@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/", + httpServerStubConfigurer = HttpsForFraudDetection) +@ActiveProfiles("test") +class StubRunnerConfigurationSpec extends Specification { + + @Autowired + StubFinder stubFinder + @Autowired + Environment environment + @StubRunnerPort("fraudDetectionServer") + int fraudDetectionServerPort + @StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer") + int fraudDetectionServerPortWithGroupId + @Value('${foo}') + Integer foo + + @BeforeClass + @AfterClass + void setupProps() { + System.clearProperty("stubrunner.repository.root") + System.clearProperty("stubrunner.classifier") + } + + def 'should start WireMock servers'() { + expect: 'WireMocks are running' + stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null + stubFinder.findStubUrl('loanIssuance') != null + stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') + stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance') + stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs') + stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null + and: + stubFinder.findAllRunningStubs().isPresent('loanIssuance') + stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer') + stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') + and: 'Stubs were registered' + "${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance' + "${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer' + and: 'Fraud Detection is an HTTPS endpoint' + stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https") + } + + def 'should throw an exception when stub is not found'() { + when: + stubFinder.findStubUrl('nonExistingService') + then: + thrown(StubNotFoundException) + when: + stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId') + then: + thrown(StubNotFoundException) + } + + def 'should register started servers as environment variables'() { + expect: + environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null + stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer) + and: + environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null + stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer) + and: + environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null + stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer) + } + + def 'should be able to interpolate a running stub in the passed test property'() { + given: + int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") + expect: + fraudPort > 0 + environment.getProperty("foo", Integer) == fraudPort + environment.getProperty("fooWithGroup", Integer) == fraudPort + foo == fraudPort + } + + @Issue("#573") + def 'should be able to retrieve the port of a running stub via an annotation'() { + given: + int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") + expect: + fraudPort > 0 + fraudDetectionServerPort == fraudPort + fraudDetectionServerPortWithGroupId == fraudPort + } + + def 'should dump all mappings to a file'() { + when: + def url = stubFinder.findStubUrl("fraudDetectionServer") + then: + new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists() + } + + @Configuration + @EnableAutoConfiguration + static class Config {} + + @CompileStatic + static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer { + + private static final Log log = LogFactory.getLog(HttpsForFraudDetection) + + @Override + WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) { + if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") { + int httpsPort = SocketUtils.findAvailableTcpPort() + log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server") + return httpStubConfiguration + .httpsPort(httpsPort) + } + return httpStubConfiguration + } + } +} +for the following configuration file: +stubrunner: + repositoryRoot: classpath:m2repo/repository/ + ids: + - org.springframework.cloud.contract.verifier.stubs:loanIssuance + - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer + - org.springframework.cloud.contract.verifier.stubs:bootService + stubs-mode: remote +Instead of using the properties you can also use the properties inside the @AutoConfigureStubRunner. +Below you can find an example of achieving the same result by setting values on the annotation. +@AutoConfigureStubRunner( + ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance", + "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer", + "org.springframework.cloud.contract.verifier.stubs:bootService"], + stubsMode = StubRunnerProperties.StubsMode.REMOTE, + repositoryRoot = "classpath:m2repo/repository/") +Stub Runner Spring registers environment variables in the following manner +for every registered WireMock server. Example for Stub Runner ids + com.example:foo, com.example:bar. + + +stubrunner.runningstubs.foo.port + + +stubrunner.runningstubs.com.example.foo.port + + +stubrunner.runningstubs.bar.port + + +stubrunner.runningstubs.com.example.bar.port + + +Which you can reference in your code. +You can also use the @StubRunnerPort annotation to inject the port of a running stub. +Value of the annotation can be the groupid:artifactid or just the artifactid. Example for Stub Runner ids +com.example:foo, com.example:bar. +@StubRunnerPort("foo") +int fooPort; +@StubRunnerPort("com.example:bar") +int barPort; +
+
+
+Stub Runner Spring Cloud +Stub Runner can integrate with Spring Cloud. +For real life examples you can check the + + +producer app sample + + +consumer app sample + + +
+Stubbing Service Discovery +The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing + + +DiscoveryClient + + +Ribbon ServerList + + +that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate +or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool. +For example this test will pass +def 'should make service discovery work'() { + expect: 'WireMocks are running' + "${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance' + "${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer' + and: 'Stubs can be reached via load service discovery' + restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance' + restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer' +} +for the following configuration file +stubrunner: + idsToServiceIds: + ivyNotation: someValueInsideYourCode + fraudDetectionServer: someNameThatShouldMapFraudDetectionServer +
+Test profiles and service discovery +In your integration tests you typically don’t want to call neither a discovery service (e.g. Eureka) +or Config Server. That’s why you create an additional test configuration in which you want to disable +these features. +Due to certain limitations of spring-cloud-commons to achieve this you have disable these properties +via a static block like presented below (example for Eureka) + //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156 + static { + System.setProperty("eureka.client.enabled", "false"); + System.setProperty("spring.cloud.config.failFast", "false"); + } +
+
+
+Additional Configuration +You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. +You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false +You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false + +By default all service discovery will be stubbed. That means that regardless of the fact if you have +an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set + stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be + merged with the stubbed ones. + +The default Maven configuration used by Stub Runner can be tweaked either +via the following system properties or environment variables + + +maven.repo.local - path to the custom maven local repository location + + +org.apache.maven.user-settings - path to custom maven user settings location + + +org.apache.maven.global-settings - path to maven global settings location + + +
+
+
+Stub Runner Boot Application +Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +trigger the messaging labels and to access started WireMock servers. +One of the use-cases is to run some smoke (end to end) tests on a deployed application. +You can check out the Spring Cloud Pipelines +project for more information. +
+How to use it? +
+Stub Runner Server +Just add the +compile "org.springframework.cloud:spring-cloud-starter-stub-runner" +Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go! +For the properties check the Stub Runner Spring section. +
+
+Stub Runner Server Fat Jar +You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows: +$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar' +$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=... +
+
+Spring Cloud CLI +Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project you can start Stub Runner Boot by executing spring cloud stubrunner. +In order to pass the configuration just create a stubrunner.yml file in the current working directory +or a subdirectory called config or in ~/.spring-cloud. The file could look like this +(example for running stubs installed locally) + +stubrunner.yml + +stubrunner: + stubsMode: LOCAL + ids: + - com.example:beer-api-producer:+:9876 + + +and then just call spring cloud stubrunner from your terminal window to start +the Stub Runner server. It will be available at port 8750. +
+
+
+Endpoints +
+HTTP + + +GET /stubs - returns a list of all running stubs in ivy:integer notation + + +GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only) + + +
+
+Messaging +For Messaging + + +GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation + + +POST /triggers/{label} - executes a trigger with label + + +POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only) + + +
+
+
+Example +@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader) +@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false") +@ActiveProfiles("test") +class StubRunnerBootSpec extends Specification { + + @Autowired + StubRunning stubRunning + + def setup() { + RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), + new TriggerController(stubRunning)) + } + + def 'should return a list of running stub servers in "full ivy:port" notation'() { + when: + String response = RestAssuredMockMvc.get('/stubs').body.asString() + then: + def root = new JsonSlurper().parseText(response) + root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer + } + + def 'should return a port on which a [#stubId] stub is running'() { + when: + def response = RestAssuredMockMvc.get("/stubs/${stubId}") + then: + response.statusCode == 200 + Integer.valueOf(response.body.asString()) > 0 + where: + stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs', + 'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs', + 'org.springframework.cloud.contract.verifier.stubs:bootService:+', + 'org.springframework.cloud.contract.verifier.stubs:bootService', + 'bootService'] + } + + def 'should return 404 when missing stub was called'() { + when: + def response = RestAssuredMockMvc.get("/stubs/a:b:c:d") + then: + response.statusCode == 404 + } + + def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() { + when: + String response = RestAssuredMockMvc.get('/triggers').body.asString() + then: + def root = new JsonSlurper().parseText(response) + root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"]) + } + + def 'should trigger a messaging label'() { + given: + StubRunning stubRunning = Mock() + RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning)) + when: + def response = RestAssuredMockMvc.post("/triggers/delete_book") + then: + response.statusCode == 200 + and: + 1 * stubRunning.trigger('delete_book') + } + + def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() { + given: + StubRunning stubRunning = Mock() + RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning)) + when: + def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book") + then: + response.statusCode == 200 + and: + 1 * stubRunning.trigger(stubId, 'delete_book') + where: + stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService'] + } + + def 'should throw exception when trigger is missing'() { + when: + RestAssuredMockMvc.post("/triggers/missing_label") + then: + Exception e = thrown(Exception) + e.message.contains("Exception occurred while trying to return [missing_label] label.") + e.message.contains("Available labels are") + e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]") + e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=") + } + +} +
+
+Stub Runner Boot with Service Discovery +One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? + Let’s assume that you don’t want to deploy 50 microservice to a test environment in order + to check if your application is working fine. You’ve already executed a suite of tests during the build process + but you would also like to ensure that the packaging of your application is fine. What you can do + is to deploy your application to an environment, start it and run a couple of tests on it to see if + it’s working fine. We can call those tests smoke-tests since their idea is to check only a handful + of testing scenarios. +The problem with this approach is such that if you’re doing microservices most likely you’re + using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the + required stubs and register them in a service discovery tool. Let’s take a look at an example of + such a setup with Eureka. Let’s assume that Eureka was already running. +@SpringBootApplication +@EnableStubRunnerServer +@EnableEurekaClient +@AutoConfigureStubRunner +public class StubRunnerBootEurekaExample { + + public static void main(String[] args) { + SpringApplication.run(StubRunnerBootEurekaExample.class, args); + } + +} +As you can see we want to start a Stub Runner Boot server @EnableStubRunnerServer, enable Eureka client @EnableEurekaClient +and we want to have the stub runner feature turned on @AutoConfigureStubRunner. +Now let’s assume that we want to start this application so that the stubs get automatically registered. + We can do it by running the app java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar where + ${SYSTEM_PROPS} would contain the following list of properties +* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1) +* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2) +* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org. +* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework. +* cloud.contract.verifier.stubs:bootService (3) +* -Dstubrunner.idsToServiceIds.fraudDetectionServer= +* someNameThatShouldMapFraudDetectionServer (4) +* +* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default +* behaviour where the discovery service is stubbed. That's why the stub registration will +* be picked (3) - we provide a list of stubs to download (4) - we provide a list of +That way your deployed application can send requests to started WireMock servers via the service +discovery. Most likely points 1-3 could be set by default in application.yml cause they are not +likely to change. That way you can provide only the list of stubs to download whenever you start +the Stub Runner Boot. +
+
+
+Stubs Per Consumer +There are cases in which 2 consumers of the same endpoint want to have 2 different responses. + +This approach also allows you to immediately know which consumer is using which part of your API. +You can remove part of a response that your API produces and you can see which of your autogenerated tests +fails. If none fails then you can safely delete that part of the response cause nobody is using it. + +Let’s look at the following example for contract defined for the producer called producer. +There are 2 consumers: foo-consumer and bar-consumer. +Consumer foo-service +request { + url '/foo' + method GET() +} +response { + status OK() + body( + foo: "foo" + } +} +Consumer bar-service +request { + url '/foo' + method GET() +} +response { + status OK() + body( + bar: "bar" + } +} +You can’t produce for the same request 2 different responses. That’s why you can properly package the +contracts and then profit from the stubsPerConsumer feature. +On the producer side the consumers can have a folder that contains contracts related only to them. +By setting the stubrunner.stubs-per-consumer flag to true we no longer register all stubs but only those that +correspond to the consumer application’s name. In other words we’ll scan the path of every stub and +if it contains the subfolder with name of the consumer in the path only then will it get registered. +On the foo producer side the contracts would look like this +. +└── contracts + ├── bar-consumer + │   ├── bookReturnedForBar.groovy + │   └── shouldCallBar.groovy + └── foo-consumer + ├── bookReturnedForFoo.groovy + └── shouldCallFoo.groovy +Being the bar-consumer consumer you can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer +Or set the test as follows: +@ContextConfiguration(classes = Config, loader = SpringBootContextLoader) +@SpringBootTest(properties = ["spring.application.name=bar-consumer"]) +@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers", + repositoryRoot = "classpath:m2repo/repository/", + stubsMode = StubRunnerProperties.StubsMode.REMOTE, + stubsPerConsumer = true) +class StubRunnerStubsPerConsumerSpec extends Specification { +... +} +Then only the stubs registered under a path that contains the bar-consumer in its name (i.e. those from the +src/test/resources/contracts/bar-consumer/some/contracts/…​ folder) will be allowed to be referenced. +Or set the consumer name explicitly +@ContextConfiguration(classes = Config, loader = SpringBootContextLoader) +@SpringBootTest +@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers", + repositoryRoot = "classpath:m2repo/repository/", + consumerName = "foo-consumer", + stubsMode = StubRunnerProperties.StubsMode.REMOTE, + stubsPerConsumer = true) +class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification { +... +} +Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the +src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced. +You can check out issue 224 for more +information about the reasons behind this change. +
+
+Common +This section briefly describes common properties, including: + + + + + + + + +
+Common Properties for JUnit and Spring +You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values: + + + + + + + +Property name +Default value +Description + + + + +stubrunner.minPort +10000 +Minimum value of a port for a started WireMock with stubs. + + +stubrunner.maxPort +15000 +Maximum value of a port for a started WireMock with stubs. + + +stubrunner.repositoryRoot + +Maven repo URL. If blank, then call the local maven repo. + + +stubrunner.classifier +stubs +Default classifier for the stub artifacts. + + +stubrunner.stubsMode +CLASSPATH +The way you want to fetch and register the stubs + + +stubrunner.ids + +Array of Ivy notation stubs to download. + + +stubrunner.username + +Optional username to access the tool that stores the JARs with +stubs. + + +stubrunner.password + +Optional password to access the tool that stores the JARs with +stubs. + + +stubrunner.stubsPerConsumer +false +Set to true if you want to use different stubs for +each consumer instead of registering all stubs for every consumer. + + +stubrunner.consumerName + +If you want to use a stub for each consumer and want to +override the consumer name just change this value. + + + + +
+
+Stub Runner Stubs IDs +You can provide the stubs to download via the stubrunner.ids system property. They +follow this pattern: +groupId:artifactId:version:classifier:port +Note that version, classifier and port are optional. + + +If you do not provide the port, a random one will be picked. + + +If you do not provide the classifier, the default is used. (Note that you can +pass an empty classifier this way: groupId:artifactId:version:). + + +If you do not provide the version, then the + will be passed and the latest one is +downloaded. + + +port means the port of the WireMock server. + +Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +Aether versioning +ranges here. + +
+
+
+Stub Runner Docker +We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +that will start the standalone version of Stub Runner. +If you want to learn more about the basics of Maven, artifact ids, +group ids, classifiers and Artifact Managers, just click here . +
+How to use it +Just execute the docker image. You can pass any of the +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (.) should be separated via underscore (_). E.g. + the stubrunner.repositoryRoot property should be represented + as a STUBRUNNER_REPOSITORY_ROOT environment variable. +
+
+Example of client side usage in a non JVM project +We’d like to use the stubs created in this step. +Let’s assume that we want to run the stubs on port 9876. The NodeJS code +is available here: +$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs +$ cd bookstore +Let’s run the Stub Runner Boot application with the stubs. +# Provide the Spring Cloud Contract Docker version +$ SC_CONTRACT_DOCKER_VERSION="..." +# The IP at which the app is running and Docker container can reach it +$ APP_IP="192.168.0.100" +# Spring Cloud Contract Stub Runner properties +$ STUBRUNNER_PORT="8083" +# Stub coordinates 'groupId:artifactId:version:classifier:port' +$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876" +$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local" +# Run the docker with Stub Runner Boot +$ docker run --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}" +What’s happening is that + + +a standalone Stub Runner application got started + + +it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876 + + +it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local + + +after a while Stub Runner will be running on port 8083 + + +and the stubs will be running at port 9876 + + +On the server side we built a stateful stub. Let’s use curl to assert +that the stubs are setup properly. +# let's execute the first request (no response is returned) +$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books +# Now time for the second request +$ curl -X GET http://localhost:9876/api/books +# You will receive contents of the JSON + +If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro" + +
+
+
+ +Stub Runner for Messaging +Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks: + + +Spring Integration + + +Spring Cloud Stream + + +Apache Camel + + +Spring AMQP + + +It also provides entry points to integrate with any other solution on the market. + +If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. +That way the only remaining framework is Spring AMQP. + +
+Stub triggering +To trigger a message, use the StubTrigger interface: +package org.springframework.cloud.contract.stubrunner; + +import java.util.Collection; +import java.util.Map; + +/** + * Contract for triggering stub messages. + * + * @author Marcin Grzejszczak + */ +public interface StubTrigger { + + /** + * Triggers an event by a given label for a given {@code groupid:artifactid} notation. + * You can use only {@code artifactId} too. + * + * Feature related to messaging. + * @param ivyNotation ivy notation of a stub + * @param labelName name of the label to trigger + * @return true - if managed to run a trigger + */ + boolean trigger(String ivyNotation, String labelName); + + /** + * Triggers an event by a given label. + * + * Feature related to messaging. + * @param labelName name of the label to trigger + * @return true - if managed to run a trigger + */ + boolean trigger(String labelName); + + /** + * Triggers all possible events. + * + * Feature related to messaging. + * @return true - if managed to run a trigger + */ + boolean trigger(); + + /** + * Feature related to messaging. + * @return a mapping of ivy notation of a dependency to all the labels it has. + */ + Map<String, Collection<String>> labels(); + +} +For convenience, the StubFinder interface extends StubTrigger, so you only need one +or the other in your tests. +StubTrigger gives you the following options to trigger a message: + + + + + + + + + + + + + + +
+Trigger by Label +stubFinder.trigger('return_book_1') +
+
+Trigger by Group and Artifact Ids +stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1') +
+
+Trigger by Artifact Ids +stubFinder.trigger('streamService', 'return_book_1') +
+
+Trigger All Messages +stubFinder.trigger() +
+
+
+Stub Runner Camel +Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +For the provided artifacts it will automatically download the stubs and register the required +routes. +
+Adding it to the project +It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner. +
+
+Disabling the functionality +If you need to disable this functionality just pass stubrunner.camel.enabled=false property. +
+
+Examples +
+Stubs structure +Let us assume that we have the following Maven repository with a deployed stubs for the +camelService application. +└── .m2 + └── repository + └── io + └── codearte + └── accurest + └── stubs + └── camelService + ├── 0.0.1-SNAPSHOT + │   ├── camelService-0.0.1-SNAPSHOT.pom + │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +And the stubs contain the following structure: +├── META-INF +│   └── MANIFEST.MF +└── repository + ├── accurest + │   ├── bookDeleted.groovy + │   ├── bookReturned1.groovy + │   └── bookReturned2.groovy + └── mappings +Let’s consider the following contracts (let' number it with 1): +Contract.make { + label 'return_book_1' + input { + triggeredBy('bookReturnedTriggered()') + } + outputMessage { + sentTo('jms:output') + body('''{ "bookName" : "foo" }''') + headers { + header('BOOK-NAME', 'foo') + } + } +} +and number 2 +Contract.make { + label 'return_book_2' + input { + messageFrom('jms:input') + messageBody([ + bookName: 'foo' + ]) + messageHeaders { + header('sample', 'header') + } + } + outputMessage { + sentTo('jms:output') + body([ + bookName: 'foo' + ]) + headers { + header('BOOK-NAME', 'foo') + } + } +} +
+
+Scenario 1 (no input message) +So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows +stubFinder.trigger('return_book_1') +Next we’ll want to listen to the output of the message sent to jms:output +Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000) +And the received message would pass the following assertions +receivedMessage != null +assertThatBodyContainsBookNameFoo(receivedMessage.in.body) +receivedMessage.in.headers.get('BOOK-NAME') == 'foo' +
+
+Scenario 2 (output triggered by input) +Since the route is set for you it’s enough to just send a message to the jms:output destination. +producerTemplate. + sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header']) +Next we’ll want to listen to the output of the message sent to jms:output +Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000) +And the received message would pass the following assertions +receivedMessage != null +assertThatBodyContainsBookNameFoo(receivedMessage.in.body) +receivedMessage.in.headers.get('BOOK-NAME') == 'foo' +
+
+Scenario 3 (input with no output) +Since the route is set for you it’s enough to just send a message to the jms:output destination. +producerTemplate. + sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header']) +
+
+
+
+Stub Runner Integration +Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes. +
+Adding the Runner to the Project +You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner. +
+
+Disabling the functionality +If you need to disable this functionality, set the +stubrunner.integration.enabled=false property. +Assume that you have the following Maven repository with deployed stubs for the +integrationService application: +└── .m2 + └── repository + └── io + └── codearte + └── accurest + └── stubs + └── integrationService + ├── 0.0.1-SNAPSHOT + │   ├── integrationService-0.0.1-SNAPSHOT.pom + │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +Further assume the stubs contain the following structure: +├── META-INF +│   └── MANIFEST.MF +└── repository + ├── accurest + │   ├── bookDeleted.groovy + │   ├── bookReturned1.groovy + │   └── bookReturned2.groovy + └── mappings +Consider the following contracts (numbered 1): +Contract.make { + label 'return_book_1' + input { + triggeredBy('bookReturnedTriggered()') + } + outputMessage { + sentTo('output') + body('''{ "bookName" : "foo" }''') + headers { + header('BOOK-NAME', 'foo') + } + } +} +Now consider 2: +Contract.make { + label 'return_book_2' + input { + messageFrom('input') + messageBody([ + bookName: 'foo' + ]) + messageHeaders { + header('sample', 'header') + } + } + outputMessage { + sentTo('output') + body([ + bookName: 'foo' + ]) + headers { + header('BOOK-NAME', 'foo') + } + } +} +and the following Spring Integration Route: +<?xml version="1.0" encoding="UTF-8"?> +<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:beans="http://www.springframework.org/schema/beans" + xmlns="http://www.springframework.org/schema/integration" + xsi:schemaLocation="http://www.springframework.org/schema/beans + https://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/integration + http://www.springframework.org/schema/integration/spring-integration.xsd"> + + + <!-- REQUIRED FOR TESTING --> + <bridge input-channel="output" + output-channel="outputTest"/> + + <channel id="outputTest"> + <queue/> + </channel> + +</beans:beans> +These examples lend themselves to three scenarios: + + + + + + + + + + + +
+Scenario 1 (no input message) +To trigger a message via the return_book_1 label, use the StubTigger interface, as +follows: +stubFinder.trigger('return_book_1') +To listen to the output of the message sent to output: +Message<?> receivedMessage = messaging.receive('outputTest') +The received message would pass the following assertions: +receivedMessage != null +assertJsons(receivedMessage.payload) +receivedMessage.headers.get('BOOK-NAME') == 'foo' +
+
+Scenario 2 (output triggered by input) +Since the route is set for you, you can send a message to the output +destination: +messaging.send(new BookReturned('foo'), [sample: 'header'], 'input') +To listen to the output of the message sent to output: +Message<?> receivedMessage = messaging.receive('outputTest') +The received message passes the following assertions: +receivedMessage != null +assertJsons(receivedMessage.payload) +receivedMessage.headers.get('BOOK-NAME') == 'foo' +
+
+Scenario 3 (input with no output) +Since the route is set for you, you can send a message to the input destination: +messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete') +
+
+
+
+Stub Runner Stream +Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes. + +If Stub Runner’s integration with Stream the messageFrom or sentTo Strings +are resolved first as a destination of a channel and no such destination exists, the +destination is resolved as a channel name. + + +If you want to use Spring Cloud Stream remember, to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support. + + +Maven + +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-stream-test-support</artifactId> + <scope>test</scope> +</dependency> + + + +Gradle + +testCompile "org.springframework.cloud:spring-cloud-stream-test-support" + + +
+Adding the Runner to the Project +You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner. +
+
+Disabling the functionality +If you need to disable this functionality, set the stubrunner.stream.enabled=false +property. +Assume that you have the following Maven repository with a deployed stubs for the +streamService application: +└── .m2 + └── repository + └── io + └── codearte + └── accurest + └── stubs + └── streamService + ├── 0.0.1-SNAPSHOT + │   ├── streamService-0.0.1-SNAPSHOT.pom + │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +Further assume the stubs contain the following structure: +├── META-INF +│   └── MANIFEST.MF +└── repository + ├── accurest + │   ├── bookDeleted.groovy + │   ├── bookReturned1.groovy + │   └── bookReturned2.groovy + └── mappings +Consider the following contracts (numbered 1): +Contract.make { + label 'return_book_1' + input { triggeredBy('bookReturnedTriggered()') } + outputMessage { + sentTo('returnBook') + body('''{ "bookName" : "foo" }''') + headers { header('BOOK-NAME', 'foo') } + } +} +Now consider 2: +Contract.make { + label 'return_book_2' + input { + messageFrom('bookStorage') + messageBody([ + bookName: 'foo' + ]) + messageHeaders { header('sample', 'header') } + } + outputMessage { + sentTo('returnBook') + body([ + bookName: 'foo' + ]) + headers { header('BOOK-NAME', 'foo') } + } +} +Now consider the following Spring configuration: +stubrunner.repositoryRoot: classpath:m2repo/repository/ +stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs +stubrunner.stubs-mode: remote +spring: + cloud: + stream: + bindings: + output: + destination: returnBook + input: + destination: bookStorage + +server: + port: 0 + +debug: true +These examples lend themselves to three scenarios: + + + + + + + + + + + +
+Scenario 1 (no input message) +To trigger a message via the return_book_1 label, use the StubTrigger interface as +follows: +stubFinder.trigger('return_book_1') +To listen to the output of the message sent to a channel whose destination is +returnBook: +Message<?> receivedMessage = messaging.receive('returnBook') +The received message passes the following assertions: +receivedMessage != null +assertJsons(receivedMessage.payload) +receivedMessage.headers.get('BOOK-NAME') == 'foo' +
+
+Scenario 2 (output triggered by input) +Since the route is set for you, you can send a message to the bookStorage +destination: +messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage') +To listen to the output of the message sent to returnBook: +Message<?> receivedMessage = messaging.receive('returnBook') +The received message passes the following assertions: +receivedMessage != null +assertJsons(receivedMessage.payload) +receivedMessage.headers.get('BOOK-NAME') == 'foo' +
+
+Scenario 3 (input with no output) +Since the route is set for you, you can send a message to the output +destination: +messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete') +
+
+
+
+Stub Runner Spring AMQP +Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes. +The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a RabbitTemplate on the application context and +uses it as a spring boot test named @SpyBean. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application. +On the message consumer side, the stub runner considers all @RabbitListener annotated +endpoints and all SimpleMessageListenerContainer objects on the application context. +As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners. +If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey +messaging header. +
+Adding the Runner to the Project +You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property stubrunner.amqp.enabled=true. Remember to annotate your test class +with @AutoConfigureStubRunner. + +If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the stubrunner.stream.enabled=false and +stubrunner.integration.enabled=false properties. + +Assume that you have the following Maven repository with a deployed stubs for the +spring-cloud-contract-amqp-test application. +└── .m2 + └── repository + └── com + └── example + └── spring-cloud-contract-amqp-test + ├── 0.4.0-SNAPSHOT + │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom + │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar + │   └── maven-metadata-local.xml + └── maven-metadata-local.xml +Further assume that the stubs contain the following structure: +├── META-INF +│   └── MANIFEST.MF +└── contracts + └── shouldProduceValidPersonData.groovy +Consider the following contract: +Contract.make { + // Human readable description + description 'Should produce valid person data' + // Label by means of which the output message can be triggered + label 'contract-test.person.created.event' + // input to the contract + input { + // the contract will be triggered by a method + triggeredBy('createPerson()') + } + // output message of the contract + outputMessage { + // destination to which the output message will be sent + sentTo 'contract-test.exchange' + headers { + header('contentType': 'application/json') + header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person') + } + // the body of the output message + body([ + id : $(consumer(9), producer(regex("[0-9]+"))), + name: "me" + ]) + } +} +Now consider the following Spring configuration: +stubrunner: + repositoryRoot: classpath:m2repo/repository/ + ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs + stubs-mode: remote + amqp: + enabled: true +server: + port: 0 +
+Triggering the message +To trigger a message using the contract above, use the StubTrigger interface as +follows: +stubTrigger.trigger("contract-test.person.created.event") +The message has a destination of contract-test.exchange, so the Spring AMQP stub runner +integration looks for bindings related to this exchange. +@Bean +public Binding binding() { + return BindingBuilder.bind(new Queue("test.queue")) + .to(new DirectExchange("contract-test.exchange")).with("#"); +} +The binding definition binds the queue test.queue. As a result, the following listener +definition is matched and invoked with the contract message. +@Bean +public SimpleMessageListenerContainer simpleMessageListenerContainer( + ConnectionFactory connectionFactory, + MessageListenerAdapter listenerAdapter) { + SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); + container.setConnectionFactory(connectionFactory); + container.setQueueNames("test.queue"); + container.setMessageListener(listenerAdapter); + + return container; +} +Also, the following annotated listener matches and is invoked: +@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"), exchange = @Exchange(value = "contract-test.exchange", ignoreDeclarationExceptions = "true"))) +public void handlePerson(Person person) { + this.person = person; +} + +The message is directly handed over to the onMessage method of the +MessageListener associated with the matching SimpleMessageListenerContainer. + +
+
+Spring AMQP Test Configuration +In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock ConnectionFactory. +To disable the mocked ConnectionFactory, set the following property: +stubrunner.amqp.mockConnection=false +stubrunner: + amqp: + mockConnection: false +
+
+
+
+ +Contract DSL +Spring Cloud Contract supports out of the box 2 types of DSL. One written in +Groovy and one written in YAML. +If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself. + +Remember that, inside the Groovy contract file, you have to provide the fully +qualified name to the Contract class and make static imports, such as +org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to +the Contract class: import org.springframework.cloud.spec.Contract and then call +Contract.make { …​ }. + + +Spring Cloud Contract supports defining multiple contracts in a single file. + +The following is a complete example of a Groovy contract definition: + +The following is a complete example of a YAML contract definition: +description: Some description +name: some name +priority: 8 +ignored: true +request: + url: /foo + queryParameters: + a: b + b: c + method: PUT + headers: + foo: bar + fooReq: baz + body: + foo: bar + matchers: + body: + - path: $.foo + type: by_regex + value: bar + headers: + - key: foo + regex: bar +response: + status: 200 + headers: + foo2: bar + foo3: foo33 + fooRes: baz + body: + foo2: bar + foo3: baz + nullValue: null + matchers: + body: + - path: $.foo2 + type: by_regex + value: bar + - path: $.foo3 + type: by_command + value: executeMe($it) + - path: $.nullValue + type: by_null + value: null + headers: + - key: foo2 + regex: bar + - key: foo3 + command: andMeToo($it) + +You can compile contracts to stubs mapping using standalone maven command: +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert + +
+Limitations + +Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature. + + +The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to true: +spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. +You can also provide the assertJsonSize property in the plugin configuration. + + +Because JSON structure can have any form, it can be impossible to parse it +properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That +is why you should use the Groovy Map notation. + +
+
+Common Top-Level elements +The following sections describe the most common top-level elements: + + + + + + + + + + + + + + + + + +
+Description +You can add a description to your contract. The description is arbitrary text. The +following code shows an example: + +Groovy DSL + + org.springframework.cloud.contract.spec.Contract.make { + description(''' +given: + An input +when: + Sth happens +then: + Output +''') + } + + + +YAML + +description: Some description +name: some name +priority: 8 +ignored: true +request: + url: /foo + queryParameters: + a: b + b: c + method: PUT + headers: + foo: bar + fooReq: baz + body: + foo: bar + matchers: + body: + - path: $.foo + type: by_regex + value: bar + headers: + - key: foo + regex: bar +response: + status: 200 + headers: + foo2: bar + foo3: foo33 + fooRes: baz + body: + foo2: bar + foo3: baz + nullValue: null + matchers: + body: + - path: $.foo2 + type: by_regex + value: bar + - path: $.foo3 + type: by_command + value: executeMe($it) + - path: $.nullValue + type: by_null + value: null + headers: + - key: foo2 + regex: bar + - key: foo3 + command: andMeToo($it) + + +
+
+Name +You can provide a name for your contract. Assume that you provided the following name: +should register a user. If you do so, the name of the autogenerated test is +validate_should_register_a_user. Also, the name of the stub in a WireMock stub is +should_register_a_user.json. + +You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other. + + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + name("some_special_name") +} + + + +YAML + +name: some name + + +
+
+Ignoring Contracts +If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the ignored property on the contract itself: + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + ignored() +} + + + +YAML + +ignored: true + + +
+
+Passing Values from Files +Starting with version 1.2.0, you can pass values from files. Assume that you have the +following resources in our project. +└── src +    └── test +       └── resources +          └── contracts +    ├── readFromFile.groovy +    ├── request.json +    └── response.json +Further assume that your contract is as follows: + +Groovy DSL + +/* + * Copyright 2013-2019 the original author or 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. + */ + +import org.springframework.cloud.contract.spec.Contract + +Contract.make { + request { + method('PUT') + headers { + contentType(applicationJson()) + } + body(file("request.json")) + url("/1") + } + response { + status OK() + body(file("response.json")) + headers { + contentType(applicationJson()) + } + } +} + + + +YAML + +request: + method: GET + url: /foo + bodyFromFile: request.json +response: + status: 200 + bodyFromFile: response.json + + +Further assume that the JSON files is as follows: +request.json +{ + "status": "REQUEST" +} +response.json +{ + "status": "RESPONSE" +} +When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. The name of the file needs to be a file with location +relative to the folder in which the contract lays. +If you need to pass the contents of a file in a binary form +it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML. + +Groovy DSL + +import org.springframework.cloud.contract.spec.Contract + +Contract.make { + request { + url("/1") + method(PUT()) + headers { + contentType(applicationOctetStream()) + } + body(fileAsBytes("request.pdf")) + } + response { + status 200 + body(fileAsBytes("response.pdf")) + headers { + contentType(applicationOctetStream()) + } + } +} + + + +YAML + +request: + url: /1 + method: PUT + headers: + Content-Type: application/octet-stream + bodyFromFileAsBytes: request.pdf +response: + status: 200 + bodyFromFileAsBytes: response.pdf + headers: + Content-Type: application/octet-stream + + + +You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. + +
+
+HTTP Top-Level Elements +The following methods can be called in the top-level closure of a contract definition. +request and response are mandatory. priority is optional. + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + // Definition of HTTP request part of the contract + // (this can be a valid request or invalid depending + // on type of contract being specified). + request { + method GET() + url "/foo" + //... + } + + // Definition of HTTP response part of the contract + // (a service implementing this contract should respond + // with following response after receiving request + // specified in "request" part above). + response { + status 200 + //... + } + + // Contract priority, which can be used for overriding + // contracts (1 is highest). Priority is optional. + priority 1 +} + + + +YAML + +priority: 8 +request: +... +response: +... + + + +If you want to make your contract have a higher value of priority +you need to pass a lower number to the priority tag / method. E.g. priority with +value 5 has higher priority than priority with value 10. + +
+
+
+Request +The HTTP protocol requires only method and url to be specified in a request. The +same information is mandatory in request definition of the Contract. + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + // HTTP request method (GET/POST/PUT/DELETE). + method 'GET' + + // Path component of request URL is specified as follows. + urlPath('/users') + } + + response { + //... + status 200 + } +} + + + +YAML + +method: PUT +url: /foo + + +It is possible to specify an absolute rather than relative url, but using urlPath is +the recommended way, as doing so makes the tests host-independent. + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'GET' + + // Specifying `url` and `urlPath` in one contract is illegal. + url('http://localhost:8888/users') + } + + response { + //... + status 200 + } +} + + + +YAML + +request: + method: PUT + urlPath: /foo + + +request may contain query parameters. + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + //... + method GET() + + urlPath('/users') { + + // Each parameter is specified in form + // `'paramName' : paramValue` where parameter value + // may be a simple literal or one of matcher functions, + // all of which are used in this example. + queryParameters { + + // If a simple literal is used as value + // default matcher function is used (equalTo) + parameter 'limit': 100 + + // `equalTo` function simply compares passed value + // using identity operator (==). + parameter 'filter': equalTo("email") + + // `containing` function matches strings + // that contains passed substring. + parameter 'gender': value(consumer(containing("[mf]")), producer('mf')) + + // `matching` function tests parameter + // against passed regular expression. + parameter 'offset': value(consumer(matching("[0-9]+")), producer(123)) + + // `notMatching` functions tests if parameter + // does not match passed regular expression. + parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3)) + } + } + + //... + } + + response { + //... + status 200 + } +} + + + +YAML + +request: +... + queryParameters: + a: b + b: c + headers: + foo: bar + fooReq: baz + cookies: + foo: bar + fooReq: baz + body: + foo: bar + matchers: + body: + - path: $.foo + type: by_regex + value: bar + headers: + - key: foo + regex: bar +response: + status: 200 + fixedDelayMilliseconds: 1000 + headers: + foo2: bar + foo3: foo33 + fooRes: baz + body: + foo2: bar + foo3: baz + nullValue: null + matchers: + body: + - path: $.foo2 + type: by_regex + value: bar + - path: $.foo3 + type: by_command + value: executeMe($it) + - path: $.nullValue + type: by_null + value: null + headers: + - key: foo2 + regex: bar + - key: foo3 + command: andMeToo($it) + cookies: + - key: foo2 + regex: bar + - key: foo3 + predefined: + + +request may contain additional request headers, as shown in the following example: + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + //... + method GET() + url "/foo" + + // Each header is added in form `'Header-Name' : 'Header-Value'`. + // there are also some helper methods + headers { + header 'key': 'value' + contentType(applicationJson()) + } + + //... + } + + response { + //... + status 200 + } +} + + + +YAML + +request: +... +headers: + foo: bar + fooReq: baz + + +request may contain additional request cookies, as shown in the following example: + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + //... + method GET() + url "/foo" + + // Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`. + // there are also some helper methods + cookies { + cookie 'key': 'value' + cookie('another_key', 'another_value') + } + + //... + } + + response { + //... + status 200 + } +} + + + +YAML + +request: +... +cookies: + foo: bar + fooReq: baz + + +request may contain a request body: + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + //... + method GET() + url "/foo" + + // Currently only JSON format of request body is supported. + // Format will be determined from a header or body's content. + body '''{ "login" : "john", "name": "John The Contract" }''' + } + + response { + //... + status 200 + } +} + + + +YAML + +request: +... +body: + foo: bar + + +request may contain multipart elements. To include multipart elements, use the +multipart method/section, as shown in the following examples + +Groovy DSL + + + + + +YAML + +request: + method: PUT + url: /multipart + headers: + Content-Type: multipart/form-data;boundary=AaB03x + multipart: + params: + # key (parameter name), value (parameter value) pair + formParameter: '"formParameterValue"' + someBooleanParameter: true + named: + - paramName: file + fileName: filename.csv + fileContent: file content + matchers: + multipart: + params: + - key: formParameter + regex: ".+" + - key: someBooleanParameter + predefined: any_boolean + named: + - paramName: file + fileName: + predefined: non_empty + fileContent: + predefined: non_empty +response: + status: 200 + + +In the preceding example, we define parameters in either of two ways: + +Groovy DSL + +Directly, by using the map notation, where the value can be a dynamic property (such as +formParameter: $(consumer(…​), producer(…​))). + + +By using the named(…​) method that lets you set a named parameter. A named parameter +can set a name and content. You can call it either via a method with two arguments, +such as named("fileName", "fileContent"), or via a map notation, such as +named(name: "fileName", content: "fileContent"). + + + +YAML + +The multipart parameters are set via multipart.params section + + +The named parameters (the fileName and fileContent for a given parameter name) +can be set via the multipart.named section. That section contains +the paramName (name of the parameter), fileName (name of the file), +fileContent (content of the file) fields + + +The dynamic bits can be set via the matchers.multipart section + + +for parameters use the params section that can accept +regex or a predefined regular expression + + +for named params use the named section where first you +define the parameter name via paramName and then you can pass the +parametrization of either fileName or fileContent via +regex or a predefined regular expression + + + + +From this contract, the generated test is as follows: +// given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "multipart/form-data;boundary=AaB03x") + .param("formParameter", "\"formParameterValue\"") + .param("someBooleanParameter", "true") + .multiPart("file", "filename.csv", "file content".getBytes()); + +// when: + ResponseOptions response = given().spec(request) + .put("/multipart"); + +// then: + assertThat(response.statusCode()).isEqualTo(200); +The WireMock stub is as follows: + ''' +{ + "request" : { + "url" : "/multipart", + "method" : "PUT", + "headers" : { + "Content-Type" : { + "matches" : "multipart/form-data;boundary=AaB03x.*" + } + }, + "bodyPatterns" : [ { + "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*" + }, { + "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*" + }, { + "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*" + } ] + }, + "response" : { + "status" : 200, + "transformers" : [ "response-template", "foo-transformer" ] + } +} + ''' +
+
+Response +The response must contain an HTTP status code and may contain other information. The +following code shows an example: + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + //... + method GET() + url "/foo" + } + response { + // Status code sent by the server + // in response to request specified above. + status OK() + } +} + + + +YAML + +response: +... +status: 200 + + +Besides status, the response may contain headers, cookies and a body, both of which are +specified the same way as in the request (see the previous paragraph). + +Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus +methods to provide a meaningful status instead of a digit. E.g. you can call +OK() for a status 200 or BAD_REQUEST() for 400. + +
+
+Dynamic properties +The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub. +For Groovy DSL you can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in a separate section called +bodyMatchers. + +Before 2.0.0 these were set using testMatchers and stubMatchers, +check out the migration guide for more information. + +For YAML you can only use the matchers section. +
+Dynamic properties inside the body + +This section is valid only for Groovy DSL. Check out the + section for YAML examples of a similar feature. + +You can set the properties inside the body either with the value method or, if you use +the Groovy map notation, with $(). The following example shows how to set dynamic +properties with the value method: +value(consumer(...), producer(...)) +value(c(...), p(...)) +value(stub(...), test(...)) +value(client(...), server(...)) +The following example shows how to set dynamic properties with $(): +$(consumer(...), producer(...)) +$(c(...), p(...)) +$(stub(...), test(...)) +$(client(...), server(...)) +Both approaches work equally well. stub and client methods are aliases over the consumer +method. Subsequent sections take a closer look at what you can do with those values. +
+
+Regular expressions + +This section is valid only for Groovy DSL. Check out the + section for YAML examples of a similar feature. + +You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests. +The following example shows how to use regular expressions to write a request: +org.springframework.cloud.contract.spec.Contract.make { + request { + method('GET') + url $(consumer(~/\/[0-9]{2}/), producer('/12')) + } + response { + status OK() + body( + id: $(anyNumber()), + surname: $( + consumer('Kowalsky'), + producer(regex('[a-zA-Z]+')) + ), + name: 'Jan', + created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))), + correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'), + producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}')) + ) + ) + headers { + header 'Content-Type': 'text/plain' + } + } +} +You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example: +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'PUT' + url value(consumer(regex('/foo/[0-9]{5}'))) + body([ + requestElement: $(consumer(regex('[0-9]{5}'))) + ]) + headers { + header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*')))) + } + } + response { + status OK() + body([ + responseElement: $(producer(regex('[0-9]{7}'))) + ]) + headers { + contentType("application/vnd.fraud.v1+json") + } + } +} +In the preceding example, the opposite side of the communication has the respective data +generated for request and response. +Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example: +protected static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/) +protected static final Pattern ALPHA_NUMERIC = Pattern.compile('[a-zA-Z0-9]+') +protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile(/[\p{L}]*/) +protected static final Pattern NUMBER = Pattern.compile('-?(\\d*\\.\\d+|\\d+)') +protected static final Pattern INTEGER = Pattern.compile('-?(\\d+)') +protected static final Pattern POSITIVE_INT = Pattern.compile('([1-9]\\d*)') +protected static final Pattern DOUBLE = Pattern.compile('-?(\\d*\\.\\d+)') +protected static final Pattern HEX = Pattern.compile('[a-fA-F0-9]+') +protected static final Pattern IP_ADDRESS = Pattern. + compile('([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])') +protected static final Pattern HOSTNAME_PATTERN = Pattern. + compile('((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?') +protected static final Pattern EMAIL = Pattern. + compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}') +protected static final Pattern URL = UrlHelper.URL +protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL +protected static final Pattern UUID = Pattern. + compile('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}') +protected static final Pattern ANY_DATE = Pattern. + compile('(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])') +protected static final Pattern ANY_DATE_TIME = Pattern. + compile('([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])') +protected static final Pattern ANY_TIME = Pattern. + compile('(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])') +protected static final Pattern NON_EMPTY = Pattern.compile(/[\S\s]+/) +protected static final Pattern NON_BLANK = Pattern.compile(/^\s*\S[\S\s]*/) +protected static final Pattern ISO8601_WITH_OFFSET = Pattern. + compile(/([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.\d{3})?(Z|[+-][01]\d:[0-5]\d)/) + +protected static Pattern anyOf(String... values) { + return Pattern.compile(values.collect({ "^$it\$" }).join("|")) +} + +RegexProperty onlyAlphaUnicode() { + return new RegexProperty(ONLY_ALPHA_UNICODE).asString() +} + +RegexProperty alphaNumeric() { + return new RegexProperty(ALPHA_NUMERIC).asString() +} + +RegexProperty number() { + return new RegexProperty(NUMBER).asDouble() +} + +RegexProperty positiveInt() { + return new RegexProperty(POSITIVE_INT).asInteger() +} + +RegexProperty anyBoolean() { + return new RegexProperty(TRUE_OR_FALSE).asBooleanType() +} + +RegexProperty anInteger() { + return new RegexProperty(INTEGER).asInteger() +} + +RegexProperty aDouble() { + return new RegexProperty(DOUBLE).asDouble() +} + +RegexProperty ipAddress() { + return new RegexProperty(IP_ADDRESS).asString() +} + +RegexProperty hostname() { + return new RegexProperty(HOSTNAME_PATTERN).asString() +} + +RegexProperty email() { + return new RegexProperty(EMAIL).asString() +} + +RegexProperty url() { + return new RegexProperty(URL).asString() +} + +RegexProperty httpsUrl() { + return new RegexProperty(HTTPS_URL).asString() +} + +RegexProperty uuid() { + return new RegexProperty(UUID).asString() +} + +RegexProperty isoDate() { + return new RegexProperty(ANY_DATE).asString() +} + +RegexProperty isoDateTime() { + return new RegexProperty(ANY_DATE_TIME).asString() +} + +RegexProperty isoTime() { + return new RegexProperty(ANY_TIME).asString() +} + +RegexProperty iso8601WithOffset() { + return new RegexProperty(ISO8601_WITH_OFFSET).asString() +} + +RegexProperty nonEmpty() { + return new RegexProperty(NON_EMPTY).asString() +} + +RegexProperty nonBlank() { + return new RegexProperty(NON_BLANK).asString() +} +In your contract, you can use it as shown in the following example: +Contract dslWithOptionalsInString = Contract.make { + priority 1 + request { + method POST() + url '/users/password' + headers { + contentType(applicationJson()) + } + body( + email: $(consumer(optional(regex(email()))), producer('abc@abc.com')), + callback_url: $(consumer(regex(hostname())), producer('http://partners.com')) + ) + } + response { + status 404 + headers { + contentType(applicationJson()) + } + body( + code: value(consumer("123123"), producer(optional("123123"))), + message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]" + ) + } +} +To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. +All of those methods start with any prefix: +T anyAlphaUnicode() + +T anyAlphaNumeric() + +T anyNumber() + +T anyInteger() + +T anyPositiveInt() + +T anyDouble() + +T anyHex() + +T aBoolean() + +T anyIpAddress() + +T anyHostname() + +T anyEmail() + +T anyUrl() + +T anyHttpsUrl() + +T anyUuid() + +T anyDate() + +T anyDateTime() + +T anyTime() + +T anyIso8601WithOffset() + +T anyNonBlankString() + +T anyNonEmptyString() + +T anyOf(String... values) +and this is an example of how you can reference those methods: +Contract contractDsl = Contract.make { + label 'trigger_event' + input { + triggeredBy('toString()') + } + outputMessage { + sentTo 'topic.rateablequote' + body([ + alpha : $(anyAlphaUnicode()), + number : $(anyNumber()), + anInteger : $(anyInteger()), + positiveInt : $(anyPositiveInt()), + aDouble : $(anyDouble()), + aBoolean : $(aBoolean()), + ip : $(anyIpAddress()), + hostname : $(anyHostname()), + email : $(anyEmail()), + url : $(anyUrl()), + httpsUrl : $(anyHttpsUrl()), + uuid : $(anyUuid()), + date : $(anyDate()), + dateTime : $(anyDateTime()), + time : $(anyTime()), + iso8601WithOffset: $(anyIso8601WithOffset()), + nonBlankString : $(anyNonBlankString()), + nonEmptyString : $(anyNonEmptyString()), + anyOf : $(anyOf('foo', 'bar')) + ]) + } +} +
+
+Passing Optional Parameters + +This section is valid only for Groovy DSL. Check out the + section for YAML examples of a similar feature. + +It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following: + + +STUB side of the Request + + +TEST side of the Response + + +The following example shows how to provide optional parameters: +org.springframework.cloud.contract.spec.Contract.make { + priority 1 + request { + method 'POST' + url '/users/password' + headers { + contentType(applicationJson()) + } + body( + email: $(consumer(optional(regex(email()))), producer('abc@abc.com')), + callback_url: $(consumer(regex(hostname())), producer('https://partners.com')) + ) + } + response { + status 404 + headers { + header 'Content-Type': 'application/json' + } + body( + code: value(consumer("123123"), producer(optional("123123"))) + ) + } +} +By wrapping a part of the body with the optional() method, you create a regular +expression that must be present 0 or more times. +If you use Spock for, the following test would be generated from the previous example: + """ + given: + def request = given() + .header("Content-Type", "application/json") + .body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''') + + when: + def response = given().spec(request) + .post("/users/password") + + then: + response.statusCode == 404 + response.header('Content-Type') == 'application/json' + and: + DocumentContext parsedJson = JsonPath.parse(response.body.asString()) + assertThatJson(parsedJson).field("['code']").matches("(123123)?") +""" +The following stub would also be generated: + ''' +{ + "request" : { + "url" : "/users/password", + "method" : "POST", + "bodyPatterns" : [ { + "matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]" + }, { + "matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]" + } ], + "headers" : { + "Content-Type" : { + "equalTo" : "application/json" + } + } + }, + "response" : { + "status" : 404, + "body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}", + "headers" : { + "Content-Type" : "application/json" + } + }, + "priority" : 1 +} +''' +
+
+Executing Custom Methods on the Server Side + +This section is valid only for Groovy DSL. Check out the + section for YAML examples of a similar feature. + +You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case: +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'PUT' + url $(consumer(regex('^/api/[0-9]{2}$')), producer('/api/12')) + headers { + header 'Content-Type': 'application/json' + } + body '''\ + [{ + "text": "Gonna see you at Warsaw" + }] + ''' + } + response { + body( + path: $(consumer('/api/12'), producer(regex('^/api/[0-9]{2}$'))), + correlationId: $(consumer('1223456'), producer(execute('isProperCorrelationId($it)'))) + ) + status OK() + } +} +The following code shows the base class portion of the test case: +abstract class BaseMockMvcSpec extends Specification { + + def setup() { + RestAssuredMockMvc.standaloneSetup(new PairIdController()) + } + + void isProperCorrelationId(Integer correlationId) { + assert correlationId == 123456 + } + + void isEmpty(String value) { + assert value == null + } + +} + +You cannot use both a String and execute to perform concatenation. For +example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to +improper results. Instead, call header('Authorization', execute('authToken()')) and +ensure that the authToken() method returns everything you need. + +The type of the object read from the JSON can be one of the following, depending on the +JSON path: + + +String: If you point to a String value in the JSON. + + +JSONArray: If you point to a List in the JSON. + + +Map: If you point to a Map in the JSON. + + +Number: If you point to Integer, Double etc. in the JSON. + + +Boolean: If you point to a Boolean in the JSON. + + +In the request part of the contract, you can specify that the body should be taken from +a method. + +You must provide both the consumer and the producer side. The execute part +is applied for the whole body - not for parts of it. + +The following example shows how to read an object from JSON: +Contract contractDsl = Contract.make { + request { + method 'GET' + url '/something' + body( + $(c('foo'), p(execute('hashCode()'))) + ) + } + response { + status OK() + } +} +The preceding example results in calling the hashCode() method in the request body. +It should resemble the following code: +// given: + MockMvcRequestSpecification request = given() + .body(hashCode()); + +// when: + ResponseOptions response = given().spec(request) + .get("/something"); + +// then: + assertThat(response.statusCode()).isEqualTo(200); +
+
+Referencing the Request from the Response +The best situation is to provide fixed values, but sometimes you need to reference a +request in your response. +If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options: + + +fromRequest().url(): Returns the request URL and query parameters. + + +fromRequest().query(String key): Returns the first query parameter with a given name. + + +fromRequest().query(String key, int index): Returns the nth query parameter with a +given name. + + +fromRequest().path(): Returns the full path. + + +fromRequest().path(int index): Returns the nth path element. + + +fromRequest().header(String key): Returns the first header with a given name. + + +fromRequest().header(String key, int index): Returns the nth header with a given name. + + +fromRequest().body(): Returns the full request body. + + +fromRequest().body(String jsonPath): Returns the element from the request that +matches the JSON Path. + + +If you’re using the YAML contract definition you have to use the +Handlebars {{{ }}} notation with custom, Spring Cloud Contract + functions to achieve this. + + +{{{ request.url }}}: Returns the request URL and query parameters. + + +{{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. +E.g. for key foo, first entry {{{ request.query.foo.[0] }}} + + +{{{ request.path }}}: Returns the full path. + + +{{{ request.path.[index] }}}: Returns the nth path element. E.g. +for first entry `{{{ request.path.[0] }}} + + +{{{ request.headers.key }}}: Returns the first header with a given name. + + +{{{ request.headers.key.[index] }}}: Returns the nth header with a given name. + + +{{{ request.body }}}: Returns the full request body. + + +{{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that +matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}} + + +Consider the following contract: + +Groovy DSL + + + + + +YAML + +request: + method: GET + url: /api/v1/xxxx + queryParameters: + foo: + - bar + - bar2 + headers: + Authorization: + - secret + - secret2 + body: + foo: bar + baz: 5 +response: + status: 200 + headers: + Authorization: "foo {{{ request.headers.Authorization.0 }}} bar" + body: + url: "{{{ request.url }}}" + path: "{{{ request.path }}}" + pathIndex: "{{{ request.path.1 }}}" + param: "{{{ request.query.foo }}}" + paramIndex: "{{{ request.query.foo.1 }}}" + authorization: "{{{ request.headers.Authorization.0 }}}" + authorization2: "{{{ request.headers.Authorization.1 }}" + fullBody: "{{{ request.body }}}" + responseFoo: "{{{ jsonpath this '$.foo' }}}" + responseBaz: "{{{ jsonpath this '$.baz' }}}" + responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla" + + +Running a JUnit test generation leads to a test that resembles the following example: +// given: + MockMvcRequestSpecification request = given() + .header("Authorization", "secret") + .header("Authorization", "secret2") + .body("{\"foo\":\"bar\",\"baz\":5}"); + +// when: + ResponseOptions response = given().spec(request) + .queryParam("foo","bar") + .queryParam("foo","bar2") + .get("/api/v1/xxxx"); + +// then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Authorization")).isEqualTo("foo secret bar"); +// and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}"); + assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret"); + assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2"); + assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx"); + assertThatJson(parsedJson).field("['param']").isEqualTo("bar"); + assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2"); + assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1"); + assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5); + assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar"); + assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2"); + assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla"); +As you can see, elements from the request have been properly referenced in the response. +The generated WireMock stub should resemble the following example: +{ + "request" : { + "urlPath" : "/api/v1/xxxx", + "method" : "POST", + "headers" : { + "Authorization" : { + "equalTo" : "secret2" + } + }, + "queryParameters" : { + "foo" : { + "equalTo" : "bar2" + } + }, + "bodyPatterns" : [ { + "matchesJsonPath" : "$[?(@.['baz'] == 5)]" + }, { + "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]" + } ] + }, + "response" : { + "status" : 200, + "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}", + "headers" : { + "Authorization" : "{{{request.headers.Authorization.[0]}}};foo" + }, + "transformers" : [ "response-template" ] + } +} +Sending a request such as the one presented in the request part of the contract results +in sending the following response body: +{ + "url" : "/api/v1/xxxx?foo=bar&foo=bar2", + "path" : "/api/v1/xxxx", + "pathIndex" : "v1", + "param" : "bar", + "paramIndex" : "bar2", + "authorization" : "secret", + "authorization2" : "secret2", + "fullBody" : "{\"foo\":\"bar\",\"baz\":5}", + "responseFoo" : "bar", + "responseBaz" : 5, + "responseBaz2" : "Bla bla bar bla bla" +} + +This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s +response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into +proper values. Additionally, it registers two helper functions: + + + +escapejsonbody: Escapes the request body in a format that can be embedded in a JSON. + + +jsonpath: For a given parameter, find an object in the request body. + + +
+
+Registering Your Own WireMock Extension +WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. +Since we use the spring.factories extension approach, you can create an entry in +META-INF/spring.factories file similar to the following: +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\ +org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions +org.springframework.cloud.contract.spec.ContractConverter=\ +org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter +The following is an example of a custom extension: + +TestWireMockExtensions.groovy + +/* + * Copyright 2013-2019 the original author or 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. + */ + +package org.springframework.cloud.contract.verifier.dsl.wiremock + +import com.github.tomakehurst.wiremock.extension.Extension + +/** + * Extension that registers the default transformer and the custom one + */ +class TestWireMockExtensions implements WireMockExtensions { + @Override + List<Extension> extensions() { + return [ + new DefaultResponseTransformer(), + new CustomExtension() + ] + } +} + +class CustomExtension implements Extension { + + @Override + String getName() { + return "foo-transformer" + } +} + + + +Remember to override the applyGlobally() method and set it to false if you +want the transformation to be applied only for a mapping that explicitly requires it. + +
+
+Dynamic Properties in the Matchers Sections +If you work with Pact, the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract. +You can use the bodyMatchers section for two reasons: + + +Define the dynamic values that should end up in a stub. +You can set it in the request or inputMessage part of your contract. + + +Verify the result of your test. +This section is present in the response or outputMessage side of the +contract. + + +Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities: + +Groovy DSL + +For the stubs(in tests on the Consumer’s side): + + +byEquality(): The value taken from the consumer’s request via the provided JSON Path must be +equal to the value provided in the contract. + + +byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must +match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.) + + +byDate(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Date value. + + +byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO DateTime value. + + +byTime(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Time value. + + + + +For the verification(in generated tests on the Producer’s side): + + +byEquality(): The value taken from the producer’s response via the provided JSON Path must be +equal to the provided value in the contract. + + +byRegex(…​): The value taken from the producer’s response via the provided JSON Path must +match the regex. + + +byDate(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Date value. + + +byTimestamp(): The value taken from the producer’s response via the provided JSON Path must +match the regex for an ISO DateTime value. + + +byTime(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Time value. + + +byType(): The value taken from the producer’s response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the byCommand(…​) testMatcher. + + +byCommand(…​): The value taken from the producer’s response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +byCommand('foo($it)') results in calling a foo method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path: + + +String: If you point to a String value. + + +JSONArray: If you point to a List. + + +Map: If you point to a Map. + + +Number: If you point to Integer, Double, or other kind of number. + + +Boolean: If you point to a Boolean. + + + + +byNull(): The value taken from the response via the provided JSON Path must be null + + + + + +YAML +Please read the Groovy section for detailed explanation of +what the types mean + +For YAML the structure of a matcher looks like this +- path: $.foo + type: by_regex + value: bar + regexType: as_string +Or if you want to use one of the predefined regular expressions +[only_alpha_unicode, number, any_boolean, ip_address, hostname, +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]: +- path: $.foo + type: by_regex + predefined: only_alpha_unicode +Below you can find the allowed list of `type`s. + + +For stubMatchers: + + +by_equality + + +by_regex + + +by_date + + +by_timestamp + + +by_time + + +by_type + + +there are 2 additional fields accepted: minOccurrence and maxOccurrence. + + + + + + +For testMatchers: + + +by_equality + + +by_regex + + +by_date + + +by_timestamp + + +by_time + + +by_type + + +there are 2 additional fields accepted: minOccurrence and maxOccurrence. + + + + +by_command + + +by_null + + + + +You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types: + + +as_integer + + +as_double + + +as_float, + + +as_long + + +as_short + + +as_boolean + + +as_string + + +Consider the following example: + +Groovy DSL + +Contract contractDsl = Contract.make { + request { + method 'GET' + urlPath '/get' + body([ + duck : 123, + alpha : 'abc', + number : 123, + aBoolean : true, + date : '2017-01-01', + dateTime : '2017-01-01T01:23:45', + time : '01:02:34', + valueWithoutAMatcher: 'foo', + valueWithTypeMatch : 'string', + key : [ + 'complex.key': 'foo' + ] + ]) + bodyMatchers { + jsonPath('$.duck', byRegex("[0-9]{3}").asInteger()) + jsonPath('$.duck', byEquality()) + jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString()) + jsonPath('$.alpha', byEquality()) + jsonPath('$.number', byRegex(number()).asInteger()) + jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType()) + jsonPath('$.date', byDate()) + jsonPath('$.dateTime', byTimestamp()) + jsonPath('$.time', byTime()) + jsonPath("\$.['key'].['complex.key']", byEquality()) + } + headers { + contentType(applicationJson()) + } + } + response { + status OK() + body([ + duck : 123, + alpha : 'abc', + number : 123, + positiveInteger : 1234567890, + negativeInteger : -1234567890, + positiveDecimalNumber: 123.4567890, + negativeDecimalNumber: -123.4567890, + aBoolean : true, + date : '2017-01-01', + dateTime : '2017-01-01T01:23:45', + time : "01:02:34", + valueWithoutAMatcher : 'foo', + valueWithTypeMatch : 'string', + valueWithMin : [ + 1, 2, 3 + ], + valueWithMax : [ + 1, 2, 3 + ], + valueWithMinMax : [ + 1, 2, 3 + ], + valueWithMinEmpty : [], + valueWithMaxEmpty : [], + key : [ + 'complex.key': 'foo' + ], + nullValue : null + ]) + bodyMatchers { + // asserts the jsonpath value against manual regex + jsonPath('$.duck', byRegex("[0-9]{3}").asInteger()) + // asserts the jsonpath value against the provided value + jsonPath('$.duck', byEquality()) + // asserts the jsonpath value against some default regex + jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString()) + jsonPath('$.alpha', byEquality()) + jsonPath('$.number', byRegex(number()).asInteger()) + jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger()) + jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger()) + jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble()) + jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble()) + jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType()) + // asserts vs inbuilt time related regex + jsonPath('$.date', byDate()) + jsonPath('$.dateTime', byTimestamp()) + jsonPath('$.time', byTime()) + // asserts that the resulting type is the same as in response body + jsonPath('$.valueWithTypeMatch', byType()) + jsonPath('$.valueWithMin', byType { + // results in verification of size of array (min 1) + minOccurrence(1) + }) + jsonPath('$.valueWithMax', byType { + // results in verification of size of array (max 3) + maxOccurrence(3) + }) + jsonPath('$.valueWithMinMax', byType { + // results in verification of size of array (min 1 & max 3) + minOccurrence(1) + maxOccurrence(3) + }) + jsonPath('$.valueWithMinEmpty', byType { + // results in verification of size of array (min 0) + minOccurrence(0) + }) + jsonPath('$.valueWithMaxEmpty', byType { + // results in verification of size of array (max 0) + maxOccurrence(0) + }) + // will execute a method `assertThatValueIsANumber` + jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)')) + jsonPath("\$.['key'].['complex.key']", byEquality()) + jsonPath('$.nullValue', byNull()) + } + headers { + contentType(applicationJson()) + header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}')))) + } + } +} + + + +YAML + +request: + method: GET + urlPath: /get/1 + headers: + Content-Type: application/json + cookies: + foo: 2 + bar: 3 + queryParameters: + limit: 10 + offset: 20 + filter: 'email' + sort: name + search: 55 + age: 99 + name: John.Doe + email: 'bob@email.com' + body: + duck: 123 + alpha: "abc" + number: 123 + aBoolean: true + date: "2017-01-01" + dateTime: "2017-01-01T01:23:45" + time: "01:02:34" + valueWithoutAMatcher: "foo" + valueWithTypeMatch: "string" + key: + "complex.key": 'foo' + nullValue: null + valueWithMin: + - 1 + - 2 + - 3 + valueWithMax: + - 1 + - 2 + - 3 + valueWithMinMax: + - 1 + - 2 + - 3 + valueWithMinEmpty: [] + valueWithMaxEmpty: [] + matchers: + url: + regex: /get/[0-9] + # predefined: + # execute a method + #command: 'equals($it)' + queryParameters: + - key: limit + type: equal_to + value: 20 + - key: offset + type: containing + value: 20 + - key: sort + type: equal_to + value: name + - key: search + type: not_matching + value: '^[0-9]{2}$' + - key: age + type: not_matching + value: '^\\w*$' + - key: name + type: matching + value: 'John.*' + - key: hello + type: absent + cookies: + - key: foo + regex: '[0-9]' + - key: bar + command: 'equals($it)' + headers: + - key: Content-Type + regex: "application/json.*" + body: + - path: $.duck + type: by_regex + value: "[0-9]{3}" + - path: $.duck + type: by_equality + - path: $.alpha + type: by_regex + predefined: only_alpha_unicode + - path: $.alpha + type: by_equality + - path: $.number + type: by_regex + predefined: number + - path: $.aBoolean + type: by_regex + predefined: any_boolean + - path: $.date + type: by_date + - path: $.dateTime + type: by_timestamp + - path: $.time + type: by_time + - path: "$.['key'].['complex.key']" + type: by_equality + - path: $.nullvalue + type: by_null + - path: $.valueWithMin + type: by_type + minOccurrence: 1 + - path: $.valueWithMax + type: by_type + maxOccurrence: 3 + - path: $.valueWithMinMax + type: by_type + minOccurrence: 1 + maxOccurrence: 3 +response: + status: 200 + cookies: + foo: 1 + bar: 2 + body: + duck: 123 + alpha: "abc" + number: 123 + aBoolean: true + date: "2017-01-01" + dateTime: "2017-01-01T01:23:45" + time: "01:02:34" + valueWithoutAMatcher: "foo" + valueWithTypeMatch: "string" + valueWithMin: + - 1 + - 2 + - 3 + valueWithMax: + - 1 + - 2 + - 3 + valueWithMinMax: + - 1 + - 2 + - 3 + valueWithMinEmpty: [] + valueWithMaxEmpty: [] + key: + 'complex.key': 'foo' + nulValue: null + matchers: + headers: + - key: Content-Type + regex: "application/json.*" + cookies: + - key: foo + regex: '[0-9]' + - key: bar + command: 'equals($it)' + body: + - path: $.duck + type: by_regex + value: "[0-9]{3}" + - path: $.duck + type: by_equality + - path: $.alpha + type: by_regex + predefined: only_alpha_unicode + - path: $.alpha + type: by_equality + - path: $.number + type: by_regex + predefined: number + - path: $.aBoolean + type: by_regex + predefined: any_boolean + - path: $.date + type: by_date + - path: $.dateTime + type: by_timestamp + - path: $.time + type: by_time + - path: $.valueWithTypeMatch + type: by_type + - path: $.valueWithMin + type: by_type + minOccurrence: 1 + - path: $.valueWithMax + type: by_type + maxOccurrence: 3 + - path: $.valueWithMinMax + type: by_type + minOccurrence: 1 + maxOccurrence: 3 + - path: $.valueWithMinEmpty + type: by_type + minOccurrence: 0 + - path: $.valueWithMaxEmpty + type: by_type + maxOccurrence: 0 + - path: $.duck + type: by_command + value: assertThatValueIsANumber($it) + - path: $.nullValue + type: by_null + value: null + headers: + Content-Type: application/json + + +In the preceding example, you can see the dynamic portions of the contract in the +matchers sections. For the request part, you can see that, for all fields but +valueWithoutAMatcher, the values of the regular expressions that the stub should +contain are explicitly set. For the valueWithoutAMatcher, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check. +For the response side in the bodyMatchers section, we define the dynamic parts in a +similar manner. The only difference is that the byType matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called): + + +For $.valueWithTypeMatch, the engine checks whether the type is the same. + + +For $.valueWithMin, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence. + + +For $.valueWithMax, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence. + + +For $.valueWithMinMax, the engine checks the type and asserts whether the size is +between the min and maximum occurrence. + + +The resulting test would resemble the following example (note that an and section +separates the autogenerated assertions and the assertion from matchers): +// given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/json") + .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}"); + +// when: + ResponseOptions response = given().spec(request) + .get("/get"); + +// then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/json.*"); +// and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo"); +// and: + assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}"); + assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123); + assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*"); + assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc"); + assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)"); + assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)"); + assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"); + assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])"); + assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])"); + assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class); + assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class); + assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1); + assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class); + assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3); + assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class); + assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3); + assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class); + assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0); + assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class); + assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0); + assertThatValueIsANumber(parsedJson.read("$.duck")); + assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo"); + +Notice that, for the byCommand method, the example calls the +assertThatValueIsANumber. This method must be defined in the test base class or be +statically imported to your tests. Notice that the byCommand call was converted to +assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took +the method name and passed the proper JSON path as a parameter to it. + +The resulting WireMock stub is in the following example: + ''' +{ + "request" : { + "urlPath" : "/get", + "method" : "POST", + "headers" : { + "Content-Type" : { + "matches" : "application/json.*" + } + }, + "bodyPatterns" : [ { + "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]" + }, { + "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]" + }, { + "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]" + }, { + "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]" + }, { + "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]" + }, { + "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]" + }, { + "matchesJsonPath" : "$[?(@.duck == 123)]" + }, { + "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]" + }, { + "matchesJsonPath" : "$[?(@.alpha == 'abc')]" + }, { + "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]" + }, { + "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]" + }, { + "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]" + }, { + "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]" + }, { + "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]" + }, { + "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]" + }, { + "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]" + }, { + "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]" + }, { + "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]" + }, { + "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]" + } ] + }, + "response" : { + "status" : 200, + "body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}", + "headers" : { + "Content-Type" : "application/json" + }, + "transformers" : [ "response-template" ] + } +} +''' + +If you use a matcher, then the part of the request and response that the +matcher addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for all the elements of the +collection. + +Consider the following example: +Contract.make { + request { + method 'GET' + url("/foo") + } + response { + status OK() + body(events: [[ + operation : 'EXPORT', + eventId : '16f1ed75-0bcc-4f0d-a04d-3121798faf99', + status : 'OK' + ], [ + operation : 'INPUT_PROCESSING', + eventId : '3bb4ac82-6652-462f-b6d1-75e424a0024a', + status : 'OK' + ] + ] + ) + bodyMatchers { + jsonPath('$.events[0].operation', byRegex('.+')) + jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$')) + jsonPath('$.events[0].status', byRegex('.+')) + } + } +} +The preceding code leads to creating the following test (the code block shows only the assertion section): +and: + DocumentContext parsedJson = JsonPath.parse(response.body.asString()) + assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99") + assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT") + assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING") + assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a") + assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK") +and: + assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+") + assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$") + assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+") +As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole $.events +collection and assert it with the byCommand(…​) method. +
+
+
+JAX-RS Support +The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define protected WebTarget webTarget and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of application/octet-stream gets used. +In order to use JAX-RS mode, use the following settings: +testMode == 'JAXRSCLIENT' +The following example shows a generated test API: + ''' + // when: + Response response = webTarget + .path("/users") + .queryParam("limit", "10") + .queryParam("offset", "20") + .queryParam("filter", "email") + .queryParam("sort", "name") + .queryParam("search", "55") + .queryParam("age", "99") + .queryParam("name", "Denis.Stepanov") + .queryParam("email", "bob@email.com") + .request() + .method("GET"); + + String responseAsString = response.readEntity(String.class); + + // then: + assertThat(response.getStatus()).isEqualTo(200); + // and: + DocumentContext parsedJson = JsonPath.parse(responseAsString); + assertThatJson(parsedJson).field("['property1']").isEqualTo("a"); +''' +
+
+Async Support +If you’re using asynchronous communication on the server side (your controllers are +returning Callable, DeferredResult, and so on), then, inside your contract, you must +provide an async() method in the response section. The following code shows an example: + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + method GET() + url '/get' + } + response { + status OK() + body 'Passed' + async() + } +} + + + +YAML + +response: + async: true + + +You can also use the fixedDelayMilliseconds method / property to add delay to your stubs. + +Groovy DSL + +org.springframework.cloud.contract.spec.Contract.make { + request { + method GET() + url '/get' + } + response { + status 200 + body 'Passed' + fixedDelayMilliseconds 1000 + } +} + + + +YAML + +response: + fixedDelayMilliseconds: 1000 + + +
+
+Working with Context Paths +Spring Cloud Contract supports context paths. + +The only change needed to fully support context paths is the switch on the +PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer +side remains untouched. In order for the generated test to pass, you must use EXPLICIT +mode. + + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <testMode>EXPLICIT</testMode> + </configuration> +</plugin> + + + +Gradle + +contracts { + testMode = 'EXPLICIT' +} + + +That way, you generate a test that DOES NOT use MockMvc. It means that you generate +real requests and you need to setup your generated test’s base class to work on a real +socket. +Consider the following contract: +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'GET' + url '/my-context-path/url' + } + response { + status OK() + } +} +The following example shows how to set up a base class and Rest Assured: +import io.restassured.RestAssured; +import org.junit.Before; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class ContextPathTestingBaseClass { + + @LocalServerPort int port; + + @Before + public void setup() { + RestAssured.baseURI = "http://localhost"; + RestAssured.port = this.port; + } +} +If you do it this way: + + +All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, /my-context-path/url). + + +Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call /my-context-path/url). + + +
+
+Working with WebFlux +Spring Cloud Contract offers two ways of working with WebFlux. +
+WebFlux with WebTestClient +One of them is via the WebTestClient mode. + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <testMode>WEBTESTCLIENT</testMode> + </configuration> +</plugin> + + + +Gradle + +contracts { + testMode = 'WEBTESTCLIENT' +} + + +The following example shows how to set up a WebTestClient base class and RestAssured +for WebFlux: +import io.restassured.module.webtestclient.RestAssuredWebTestClient; +import org.junit.Before; + +public abstract class BeerRestBase { + + @Before + public void setup() { + RestAssuredWebTestClient.standaloneSetup( + new ProducerController(personToCheck -> personToCheck.age >= 20)); + } +} +} +
+
+WebFlux with Explicit mode +Another way is with the EXPLICIT mode in your generated tests +to work with WebFlux. + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <testMode>EXPLICIT</testMode> + </configuration> +</plugin> + + + +Gradle + +contracts { + testMode = 'EXPLICIT' +} + + +The following example shows how to set up a base class and Rest Assured for Web Flux: +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BeerRestBase.Config.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = "server.port=0") +public abstract class BeerRestBase { + + // your tests go here + + // in this config class you define all controllers and mocked services +@Configuration +@EnableAutoConfiguration +static class Config { + + @Bean + PersonCheckingService personCheckingService() { + return personToCheck -> personToCheck.age >= 20; + } + + @Bean + ProducerController producerController() { + return new ProducerController(personCheckingService()); + } +} + +} +
+
+
+XML Support for REST +For REST contracts, we also support XML request and response body. +The XML body has to be passed within the body element +as a String or GString. Also body matchers can be provided for +both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath +method should be used, with the desired xPath provided as the first argument +and the appropriate MatchingType as second. All the body matchers apart from byType() are supported. +Here is an example of a Groovy DSL contract with XML response body: + Contract.make { + request { + method GET() + urlPath '/get' + headers { + contentType(applicationXml()) + } + } + response { + status(OK()) + headers { + contentType(applicationXml()) + } + body """ +<test> +<duck type='xtype'>123</duck> +<alpha>abc</alpha> +<list> +<elem>abc</elem> +<elem>def</elem> +<elem>ghi</elem> +</list> +<number>123</number> +<aBoolean>true</aBoolean> +<date>2017-01-01</date> +<dateTime>2017-01-01T01:23:45</dateTime> +<time>01:02:34</time> +<valueWithoutAMatcher>foo</valueWithoutAMatcher> +<key><complex>foo</complex></key> +</test>""" + bodyMatchers { + xPath('/test/duck/text()', byRegex("[0-9]{3}")) + xPath('/test/duck/text()', byCommand('test($it)')) + xPath('/test/duck/xxx', byNull()) + xPath('/test/duck/text()', byEquality()) + xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode())) + xPath('/test/alpha/text()', byEquality()) + xPath('/test/number/text()', byRegex(number())) + xPath('/test/date/text()', byDate()) + xPath('/test/dateTime/text()', byTimestamp()) + xPath('/test/time/text()', byTime()) + xPath('/test/*/complex/text()', byEquality()) + xPath('/test/duck/@type', byEquality()) + } + } + } +And below is an example of a YAML contract with XML request and response bodies: +include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml +Here is an example of an automatically generated test for XML response body: +@Test +public void validate_xmlMatches() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/xml"); + + // when: + ResponseOptions response = given().spec(request).get("/get"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + // and: + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() + .newDocumentBuilder(); + Document parsedXml = documentBuilder.parse(new InputSource( + new StringReader(response.getBody().asString()))); + // and: + assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc"); + assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def"); + assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}"); + assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull(); + assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*"); + assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo"); + assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype"); + } +
+
+Messaging Top-Level Elements +The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences: + + + + + + + + + + + + + + +
+Output Triggered by a Method +The output message can be triggered by calling a method (such as a Scheduler when a was +started and a message was sent), as shown in the following example: + +Groovy DSL + +def dsl = Contract.make { + // Human readable description + description 'Some description' + // Label by means of which the output message can be triggered + label 'some_label' + // input to the contract + input { + // the contract will be triggered by a method + triggeredBy('bookReturnedTriggered()') + } + // output message of the contract + outputMessage { + // destination to which the output message will be sent + sentTo('output') + // the body of the output message + body('''{ "bookName" : "foo" }''') + // the headers of the output message + headers { + header('BOOK-NAME', 'foo') + } + } +} + + + +YAML + +# Human readable description +description: Some description +# Label by means of which the output message can be triggered +label: some_label +input: + # the contract will be triggered by a method + triggeredBy: bookReturnedTriggered() +# output message of the contract +outputMessage: + # destination to which the output message will be sent + sentTo: output + # the body of the output message + body: + bookName: foo + # the headers of the output message + headers: + BOOK-NAME: foo + + +In the previous example case, the output message is sent to output if a method called +bookReturnedTriggered is executed. On the message publisher’s side, we generate a +test that calls that method to trigger the message. On the consumer side, you can use +the some_label to trigger the message. +
+
+Output Triggered by a Message +The output message can be triggered by receiving a message, as shown in the following +example: + +Groovy DSL + +def dsl = Contract.make { + description 'Some Description' + label 'some_label' + // input is a message + input { + // the message was received from this destination + messageFrom('input') + // has the following body + messageBody([ + bookName: 'foo' + ]) + // and the following headers + messageHeaders { + header('sample', 'header') + } + } + outputMessage { + sentTo('output') + body([ + bookName: 'foo' + ]) + headers { + header('BOOK-NAME', 'foo') + } + } +} + + + +YAML + +# Human readable description +description: Some description +# Label by means of which the output message can be triggered +label: some_label +# input is a message +input: + messageFrom: input + # has the following body + messageBody: + bookName: 'foo' + # and the following headers + messageHeaders: + sample: 'header' +# output message of the contract +outputMessage: + # destination to which the output message will be sent + sentTo: output + # the body of the output message + body: + bookName: foo + # the headers of the output message + headers: + BOOK-NAME: foo + + +In the preceding example, the output message is sent to output if a proper message is +received on the input destination. On the message publisher’s side, the engine +generates a test that sends the input message to the defined destination. On the +consumer side, you can either send a message to the input destination or use a label +(some_label in the example) to trigger the message. +
+
+Consumer/Producer + +This section is valid only for Groovy DSL. + +In HTTP, you have a notion of client/stub and `server/test notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the consumer and producer methods, as presented in the following example +(note that you can use either $ or value methods to provide consumer and producer +parts): + Contract.make { + label 'some_label' + input { + messageFrom value(consumer('jms:output'), producer('jms:input')) + messageBody([ + bookName: 'foo' + ]) + messageHeaders { + header('sample', 'header') + } + } + outputMessage { + sentTo $(consumer('jms:input'), producer('jms:output')) + body([ + bookName: 'foo' + ]) + } + } +
+
+Common +In the input or outputMessage section you can call assertThat with the name +of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test. +
+
+
+Multiple Contracts in One File +You can define multiple contracts in one file. Such a contract might resemble the +following example: + +Groovy DSL + +import org.springframework.cloud.contract.spec.Contract + +[ + Contract.make { + name("should post a user") + request { + method 'POST' + url('/users/1') + } + response { + status OK() + } + }, + Contract.make { + request { + method 'POST' + url('/users/2') + } + response { + status OK() + } + } +] + + + +YAML + +--- +name: should post a user +request: + method: POST + url: /users/1 +response: + status: 200 +--- +request: + method: POST + url: /users/2 +response: + status: 200 +--- +request: + method: POST + url: /users/3 +response: + status: 200 + + +In the preceding example, one contract has the name field and the other does not. This +leads to generation of two tests that look more or less like this: +package org.springframework.cloud.contract.verifier.tests.com.hello; + +import com.example.TestBase; +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; +import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification; +import com.jayway.restassured.response.ResponseOptions; +import org.junit.Test; + +import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*; +import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson; +import static org.assertj.core.api.Assertions.assertThat; + +public class V1Test extends TestBase { + + @Test + public void validate_should_post_a_user() throws Exception { + // given: + MockMvcRequestSpecification request = given(); + + // when: + ResponseOptions response = given().spec(request) + .post("/users/1"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + } + + @Test + public void validate_withList_1() throws Exception { + // given: + MockMvcRequestSpecification request = given(); + + // when: + ResponseOptions response = given().spec(request) + .post("/users/2"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + } + +} +Notice that, for the contract that has the name field, the generated test method is named +validate_should_post_a_user. For the one that does not have the name, it is called +validate_withList_1. It corresponds to the name of the file WithList.groovy and the +index of the contract in the list. +The generated stubs is shown in the following example: +should post a user.json +1_WithList.json +As you can see, the first file got the name parameter from the contract. The second +got the name of the contract file (WithList.groovy) prefixed with the index (in this +case, the contract had an index of 1 in the list of contracts in the file). + +As you can see, it is much better if you name your contracts because doing so makes +your tests far more meaningful. + +
+
+Generating Spring REST Docs snippets from the contracts +When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven’t already. + +Maven + +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-verifier</artifactId> + <scope>test</scope> +</dependency> +<dependency> + <groupId>org.springframework.restdocs</groupId> + <artifactId>spring-restdocs-mockmvc</artifactId> + <optional>true</optional> +</dependency> + + + +Gradle + +testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' +testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc' + + +Next you need to make some changes to your base class like the following example. +package com.example.fraud; + +import io.restassured.module.mockmvc.RestAssuredMockMvc; +import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.TestName; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public abstract class FraudBaseWithWebAppSetup { + + private static final String OUTPUT = "target/generated-snippets"; + + @Rule + public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT); + + @Rule + public TestName testName = new TestName(); + + @Autowired + private WebApplicationContext context; + + @Before + public void setup() { + RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context) + .apply(documentationConfiguration(this.restDocumentation)) + .alwaysDo(document( + getClass().getSimpleName() + "_" + testName.getMethodName())) + .build()); + } + + protected void assertThatRejectionReasonIsNull(Object rejectionReason) { + assert rejectionReason == null; + } + +} +In case you are using the standalone setup, you can set up RestAssuredMockMvc like this: +package com.example.fraud; + +import io.restassured.module.mockmvc.RestAssuredMockMvc; +import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.TestName; + +import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; + +public abstract class FraudBaseWithStandaloneSetup { + + private static final String OUTPUT = "target/generated-snippets"; + + @Rule + public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT); + + @Rule + public TestName testName = new TestName(); + + @Before + public void setup() { + RestAssuredMockMvc.standaloneSetup(MockMvcBuilders + .standaloneSetup(new FraudDetectionController()) + .apply(documentationConfiguration(this.restDocumentation)) + .alwaysDo(document( + getClass().getSimpleName() + "_" + testName.getMethodName()))); + } + +} + +You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. + +
+
+ +Customization + +This section is valid only for Groovy DSL + +You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section. +
+Extending the DSL +You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of: + + +Creating a JAR with reusable classes. + + +Referencing of these classes in the DSLs. + + +You can find the full example +here. +
+Common JAR +The following examples show three classes that can be reused in the DSLs. +PatternUtils contains functions used by both the consumer and the producer. +package com.example; + +import java.util.regex.Pattern; + +/** + * If you want to use {@link Pattern} directly in your tests + * then you can create a class resembling this one. It can + * contain all the {@link Pattern} you want to use in the DSL. + * + * <pre> + * {@code + * request { + * body( + * [ age: $(c(PatternUtils.oldEnough()))] + * ) + * } + * </pre> + * + * Notice that we're using both {@code $()} for dynamic values + * and {@code c()} for the consumer side. + * + * @author Marcin Grzejszczak + */ +//tag::impl[] +public class PatternUtils { + + public static String tooYoung() { + //remove::start[] + return "[0-1][0-9]"; + //remove::end[return] + } + + public static Pattern oldEnough() { + //remove::start[] + return Pattern.compile("[2-9][0-9]"); + //remove::end[return] + } + + /** + * Makes little sense but it's just an example ;) + */ + public static Pattern ok() { + //remove::start[] + return Pattern.compile("OK"); + //remove::end[return] + } +} +//end::impl[] +ConsumerUtils contains functions used by the consumer. +package com.example; + +import org.springframework.cloud.contract.spec.internal.ClientDslProperty; + +/** + * DSL Properties passed to the DSL from the consumer's perspective. + * That means that on the input side {@code Request} for HTTP + * or {@code Input} for messaging you can have a regular expression. + * On the {@code Response} for HTTP or {@code Output} for messaging + * you have to have a concrete value. + * + * @author Marcin Grzejszczak + */ +//tag::impl[] +public class ConsumerUtils { + /** + * Consumer side property. By using the {@link ClientDslProperty} + * you can omit most of boilerplate code from the perspective + * of dynamic values. Example + * + * <pre> + * {@code + * request { + * body( + * [ age: $(ConsumerUtils.oldEnough())] + * ) + * } + * </pre> + * + * That way it's in the implementation that we decide what value we will pass to the consumer + * and which one to the producer. + * + * @author Marcin Grzejszczak + */ + public static ClientDslProperty oldEnough() { + //remove::start[] + // this example is not the best one and + // theoretically you could just pass the regex instead of `ServerDslProperty` but + // it's just to show some new tricks :) + return new ClientDslProperty(PatternUtils.oldEnough(), 40); + //remove::end[return] + } + +} +//end::impl[] +ProducerUtils contains functions used by the producer. +package com.example; + +import org.springframework.cloud.contract.spec.internal.ServerDslProperty; + +/** + * DSL Properties passed to the DSL from the producer's perspective. + * That means that on the input side {@code Request} for HTTP + * or {@code Input} for messaging you have to have a concrete value. + * On the {@code Response} for HTTP or {@code Output} for messaging + * you can have a regular expression. + * + * @author Marcin Grzejszczak + */ +//tag::impl[] +public class ProducerUtils { + + /** + * Producer side property. By using the {@link ProducerUtils} + * you can omit most of boilerplate code from the perspective + * of dynamic values. Example + * + * <pre> + * {@code + * response { + * body( + * [ status: $(ProducerUtils.ok())] + * ) + * } + * </pre> + * + * That way it's in the implementation that we decide what value we will pass to the consumer + * and which one to the producer. + */ + public static ServerDslProperty ok() { + // this example is not the best one and + // theoretically you could just pass the regex instead of `ServerDslProperty` but + // it's just to show some new tricks :) + return new ServerDslProperty( PatternUtils.ok(), "OK"); + } +} +//end::impl[] +
+
+Adding the Dependency to the Project +In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project. +
+
+Test the Dependency in the Project’s Dependencies +First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency: + +Maven + +<dependency> + <groupId>com.example</groupId> + <artifactId>beer-common</artifactId> + <version>${project.version}</version> + <scope>test</scope> +</dependency> + + + +Gradle + +testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT") + + +
+
+Test a Dependency in the Plugin’s Dependencies +Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example: + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <packageWithBaseClasses>com.example</packageWithBaseClasses> + <baseClassMappings> + <baseClassMapping> + <contractPackageRegex>.*intoxication.*</contractPackageRegex> + <baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN> + </baseClassMapping> + </baseClassMappings> + </configuration> + <dependencies> + <dependency> + <groupId>com.example</groupId> + <artifactId>beer-common</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + </dependencies> +</plugin> + + + +Gradle + +classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT" + + +
+
+Referencing classes in DSLs +You can now reference your classes in your DSL, as shown in the following example: +package contracts.beer.rest + +import com.example.ConsumerUtils +import com.example.ProducerUtils +import org.springframework.cloud.contract.spec.Contract + +Contract.make { + description(""" +Represents a successful scenario of getting a beer + +``` +given: + client is old enough +when: + he applies for a beer +then: + we'll grant him the beer +``` + +""") + request { + method 'POST' + url '/check' + body( + age: $(ConsumerUtils.oldEnough()) + ) + headers { + contentType(applicationJson()) + } + } + response { + status 200 + body(""" + { + "status": "${value(ProducerUtils.ok())}" + } + """) + headers { + contentType(applicationJson()) + } + } +} + +You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. + +
+
+
+ +Using the Pluggable Architecture +You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations). +
+Custom Contract Converter +The ContractConverter interface lets you register your own implementation of a contract +structure converter. The following code listing shows the ContractConverter interface: +package org.springframework.cloud.contract.spec + +/** + * Converter to be used to convert FROM {@link File} TO {@link Contract} + * and from {@link Contract} to {@code T} + * + * @param <T > - type to which we want to convert the contract + * + * @author Marcin Grzejszczak + * @since 1.1.0 + */ +interface ContractConverter<T> extends ContractStorer<T> { + + /** + * Should this file be accepted by the converter. Can use the file extension + * to check if the conversion is possible. + * + * @param file - file to be considered for conversion + * @return - {@code true} if the given implementation can convert the file + */ + boolean isAccepted(File file) + + /** + * Converts the given {@link File} to its {@link Contract} representation + * + * @param file - file to convert + * @return - {@link Contract} representation of the file + */ + Collection<Contract> convertFrom(File file) + + /** + * Converts the given {@link Contract} to a {@link T} representation + * + * @param contract - the parsed contract + * @return - {@link T} the type to which we do the conversion + */ + T convertTo(Collection<Contract> contract) +} +Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions. + +Once you create your implementation, you must create a +/META-INF/spring.factories file in which you provide the fully qualified name of your +implementation. + +The following example shows a typical spring.factories file: +org.springframework.cloud.contract.spec.ContractConverter=\ +org.springframework.cloud.contract.verifier.converter.YamlContractConverter +
+Pact Converter +Spring Cloud Contract includes support for Pact representation of +contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used. +In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries: + + +to define the destination to which a message gets sent, you have to +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" } + + +
+
+Pact Contract +Consider following example of a Pact contract, which is a file under the +src/test/resources/contracts folder. +{ + "provider": { + "name": "Provider" + }, + "consumer": { + "name": "Consumer" + }, + "interactions": [ + { + "description": "", + "request": { + "method": "PUT", + "path": "/fraudcheck", + "headers": { + "Content-Type": "application/vnd.fraud.v1+json" + }, + "body": { + "clientId": "1234567890", + "loanAmount": 99999 + }, + "generators": { + "body": { + "$.clientId": { + "type": "Regex", + "regex": "[0-9]{10}" + } + } + }, + "matchingRules": { + "header": { + "Content-Type": { + "matchers": [ + { + "match": "regex", + "regex": "application/vnd\\.fraud\\.v1\\+json.*" + } + ], + "combine": "AND" + } + }, + "body": { + "$.clientId": { + "matchers": [ + { + "match": "regex", + "regex": "[0-9]{10}" + } + ], + "combine": "AND" + } + } + } + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/vnd.fraud.v1+json;charset=UTF-8" + }, + "body": { + "fraudCheckStatus": "FRAUD", + "rejectionReason": "Amount too high" + }, + "matchingRules": { + "header": { + "Content-Type": { + "matchers": [ + { + "match": "regex", + "regex": "application/vnd\\.fraud\\.v1\\+json.*" + } + ], + "combine": "AND" + } + }, + "body": { + "$.fraudCheckStatus": { + "matchers": [ + { + "match": "regex", + "regex": "FRAUD" + } + ], + "combine": "AND" + } + } + } + } + } + ], + "metadata": { + "pact-specification": { + "version": "3.0.0" + }, + "pact-jvm": { + "version": "3.5.13" + } + } +} +The remainder of this section about using Pact refers to the preceding file. +
+
+Pact for Producers +On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use. + +Maven + +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <packageWithBaseClasses>com.example.fraud</packageWithBaseClasses> + </configuration> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-pact</artifactId> + <version>${spring-cloud-contract.version}</version> + </dependency> + </dependencies> +</plugin> + + + +Gradle + +classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}" + + +When you execute the build of your application, a test will be generated. The generated +test might be as follows: +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high"); + // and: + assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD"); +} +The corresponding generated stub might be as follows: +{ + "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62", + "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62", + "request" : { + "url" : "/fraudcheck", + "method" : "PUT", + "headers" : { + "Content-Type" : { + "matches" : "application/vnd\\.fraud\\.v1\\+json.*" + } + }, + "bodyPatterns" : [ { + "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]" + }, { + "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]" + } ] + }, + "response" : { + "status" : 200, + "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}", + "headers" : { + "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8" + }, + "transformers" : [ "response-template" ] + }, +} +
+
+Pact for Consumers +On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use. + +Maven + +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-pact</artifactId> + <scope>test</scope> +</dependency> + + + +Gradle + +testCompile "org.springframework.cloud:spring-cloud-contract-pact" + + +
+
+
+Using the Custom Test Generator +If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation. +The SingleTestGenerator interface lets you register your own implementation. The +following code listing shows the SingleTestGenerator interface: +package org.springframework.cloud.contract.verifier.builder + + +import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties +import org.springframework.cloud.contract.verifier.file.ContractMetadata + +/** + * Builds a single test. + * + * @since 1.1.0 + */ +trait SingleTestGenerator { + + /** + * Creates contents of a single test class in which all test scenarios from + * the contract metadata should be placed. + * + * @param properties - properties passed to the plugin + * @param listOfFiles - list of parsed contracts with additional metadata + * @param className - the name of the generated test class + * @param classPackage - the name of the package in which the test class should be stored + * @param includedDirectoryRelativePath - relative path to the included directory + * @return contents of a single test class + * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)} + */ + @Deprecated + abstract String buildClass(ContractVerifierConfigProperties properties, + Collection<ContractMetadata> listOfFiles, String className, String classPackage, String includedDirectoryRelativePath) + + /** + * Creates contents of a single test class in which all test scenarios from + * the contract metadata should be placed. + * + * @param properties - properties passed to the plugin + * @param listOfFiles - list of parsed contracts with additional metadata + * @param generatedClassData - information about the generated class + * @param includedDirectoryRelativePath - relative path to the included directory + * @return contents of a single test class + */ + String buildClass(ContractVerifierConfigProperties properties, + Collection<ContractMetadata> listOfFiles, String includedDirectoryRelativePath, GeneratedClassData generatedClassData) { + String className = generatedClassData.className + String classPackage = generatedClassData.classPackage + String path = includedDirectoryRelativePath + return buildClass(properties, listOfFiles, className, classPackage, path) + } + + /** + * Extension that should be appended to the generated test class. E.g. {@code .java} or {@code .php} + * + * @param properties - properties passed to the plugin + */ + abstract String fileExtension(ContractVerifierConfigProperties properties) + + static class GeneratedClassData { + public final String className + public final String classPackage + public final java.nio.file.Path testClassPath + + GeneratedClassData(String className, String classPackage, + java.nio.file.Path testClassPath) { + this.className = className + this.classPackage = classPackage + this.testClassPath = testClassPath + } + } +} +Again, you must provide a spring.factories file, such as the one shown in the following +example: +org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/ +com.example.MyGenerator +
+
+Using the Custom Stub Generator +If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the StubGenerator interface. The following code listing shows the +StubGenerator interface: +package org.springframework.cloud.contract.verifier.converter + +import groovy.transform.CompileStatic + +import org.springframework.cloud.contract.spec.Contract +import org.springframework.cloud.contract.verifier.file.ContractMetadata + +/** + * Converts contracts into their stub representation. + * + * @since 1.1.0 + */ +@CompileStatic +interface StubGenerator { + + /** + * @return {@code true} if the converter can handle the file to convert it into a stub. + */ + boolean canHandleFileName(String fileName) + + /** + * @return the collection of converted contracts into stubs. One contract can + * result in multiple stubs. + */ + Map<Contract, String> convertContents(String rootName, ContractMetadata content) + + /** + * @return the name of the converted stub file. If you have multiple contracts + * in a single file then a prefix will be added to the generated file. If you + * provide the {@link Contract#name} field then that field will override the + * generated file name. + * + * Example: name of file with 2 contracts is {@code foo.groovy}, it will be + * converted by the implementation to {@code foo.json}. The recursive file + * converter will create two files {@code 0_foo.json} and {@code 1_foo.json} + */ + String generateOutputFileNameForInput(String inputFileName) +} +Again, you must provide a spring.factories file, such as the one shown in the following +example: +# Stub converters +org.springframework.cloud.contract.verifier.converter.StubGenerator=\ +org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter +The default implementation is the WireMock stub generation. + +You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files. + +
+
+Using the Custom Stub Runner +If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider. +Assume that you use Moco to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file. +In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example: +package org.springframework.cloud.contract.stubrunner.provider.moco + +import com.github.dreamhead.moco.bootstrap.arg.HttpArgs +import com.github.dreamhead.moco.runner.JsonRunner +import com.github.dreamhead.moco.runner.RunnerSetting +import groovy.util.logging.Commons + +import org.springframework.cloud.contract.stubrunner.HttpServerStub +import org.springframework.util.SocketUtils + +@Commons +class MocoHttpServerStub implements HttpServerStub { + + private boolean started + private JsonRunner runner + private int port + + @Override + int port() { + if (!isRunning()) { + return -1 + } + return port + } + + @Override + boolean isRunning() { + return started + } + + @Override + HttpServerStub start() { + return start(SocketUtils.findAvailableTcpPort()) + } + + @Override + HttpServerStub start(int port) { + this.port = port + return this + } + + @Override + HttpServerStub stop() { + if (!isRunning()) { + return this + } + this.runner.stop() + return this + } + + @Override + HttpServerStub registerMappings(Collection<File> stubFiles) { + List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") } + .collect { + log.info("Trying to parse [${it.name}]") + try { + return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()). + build() + } + catch (Exception e) { + log.warn("Exception occurred while trying to parse file [${it.name}]", e) + return null + } + }.findAll { it } + this.runner = JsonRunner.newJsonRunnerWithSetting(settings, + HttpArgs.httpArgs().withPort(this.port).build()) + this.runner.run() + this.started = true + return this + } + + @Override + String registeredMappings() { + return "" + } + + @Override + boolean isAccepted(File file) { + return file.name.endsWith(".json") + } +} +Then, you can register it in your spring.factories file, as shown in the following +example: +org.springframework.cloud.contract.stubrunner.HttpServerStub=\ +org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub +Now you can run stubs with Moco. + +If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used. + +
+
+Using the Custom Stub Downloader +You can customize the way your stubs are downloaded by creating an implementation of the +StubDownloaderBuilder interface, as shown in the following example: +package com.example; + +class CustomStubDownloaderBuilder implements StubDownloaderBuilder { + + @Override + public StubDownloader build(final StubRunnerOptions stubRunnerOptions) { + return new StubDownloader() { + @Override + public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar( + StubConfiguration config) { + File unpackedStubs = retrieveStubs(); + return new AbstractMap.SimpleEntry<>( + new StubConfiguration(config.getGroupId(), config.getArtifactId(), version, + config.getClassifier()), unpackedStubs); + } + + File retrieveStubs() { + // here goes your custom logic to provide a folder where all the stubs reside + } +} +Then you can register it in your spring.factories file, as shown in the following +example: +# Example of a custom Stub Downloader Provider +org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\ +com.example.CustomStubDownloaderBuilder +Now you can pick a folder with the source of your stubs. + +If you do not provide any implementation, then the default is used (scan classpath). +If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or +, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used +If you provide more than one, then the first one on the list is used. + +
+
+Using the SCM Stub Downloader +Whenever the repositoryRoot starts with a SCM protocol +(currently we support only git://), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs. +Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties + +SCM Stub Downloader properties + + + + + + +Type of a property +Name of the property +Description + + +* git.branch (plugin prop)* stubrunner.properties.git.branch (system prop)* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop) +master +Which branch to checkout + + +* git.username (plugin prop)* stubrunner.properties.git.username (system prop)* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop) + +Git clone username + + +* git.password (plugin prop)* stubrunner.properties.git.password (system prop)* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop) + +Git clone password + + +* git.no-of-attempts (plugin prop)* stubrunner.properties.git.no-of-attempts (system prop)* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop) +10 +Number of attempts to push the commits to origin + + +* git.wait-between-attempts (Plugin prop)* stubrunner.properties.git.wait-between-attempts (system prop)* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop) +1000 +Number of millis to wait between attempts to push the commits to origin + + + +
+
+
+Using the Pact Stub Downloader +Whenever the repositoryRoot starts with a Pact protocol +(starts with pact://), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after pact:// will be parsed as the Pact Broker URL. +Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties + +SCM Stub Downloader properties + + + + + + +Name of a property +Default +Description + + +* pactbroker.host (plugin prop)* stubrunner.properties.pactbroker.host (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop) +Host from URL passed to repositoryRoot +What is the URL of Pact Broker + + +* pactbroker.port (plugin prop)* stubrunner.properties.pactbroker.port (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop) +Port from URL passed to repositoryRoot +What is the port of Pact Broker + + +* pactbroker.protocol (plugin prop)* stubrunner.properties.pactbroker.protocol (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop) +Protocol from URL passed to repositoryRoot +What is the protocol of Pact Broker + + +* pactbroker.tags (plugin prop)* stubrunner.properties.pactbroker.tags (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop) +Version of the stub, or latest if version is + +What tags should be used to fetch the stub + + +* pactbroker.auth.scheme (plugin prop)* stubrunner.properties.pactbroker.auth.scheme (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop) +Basic +What kind of authentication should be used to connect to the Pact Broker + + +* pactbroker.auth.username (plugin prop)* stubrunner.properties.pactbroker.auth.username (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop) +The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle) +Username used to connect to the Pact Broker + + +* pactbroker.auth.password (plugin prop)* stubrunner.properties.pactbroker.auth.password (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop) +The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle) +Password used to connect to the Pact Broker + + +* pactbroker.provider-name-with-group-id (plugin prop)* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop) +false +When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used + + + +
+
+
+ +Spring Cloud Contract WireMock +The Spring Cloud Contract WireMock modules let you use WireMock in a +Spring Boot application. Check out the +samples +for more details. +If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with spring-boot-starter-web), you can add +spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example: +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@AutoConfigureWireMock(port = 0) +public class WiremockForDocsTests { + + // A service that calls out over HTTP + @Autowired + private Service service; + + @Before + public void setup() { + this.service.setBase("http://localhost:" + + this.environment.getProperty("wiremock.server.port")); + } + + // Using the WireMock APIs in the normal way: + @Test + public void contextLoads() throws Exception { + // Stubbing WireMock + stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + // We're asserting if WireMock responded properly + assertThat(this.service.go()).isEqualTo("Hello World!"); + } + +} +To start the stub server on a different port use (for example), +@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test. +
+Registering Stubs Automatically +If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +system or classpath (by default, from file:src/test/resources/mappings). You can +customize the locations using the stubs attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, */.json is +appended. The following code shows an example: +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureWireMock(stubs="classpath:/stubs") +public class WiremockImportApplicationTests { + + @Autowired + private Service service; + + @Test + public void contextLoads() throws Exception { + assertThat(this.service.go()).isEqualTo("Hello World!"); + } + +} + +Actually, WireMock always loads mappings from src/test/resources/mappings as +well as the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document. + +If you’re using Spring Cloud Contract’s default stub jars, then your +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax. +@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json") +
+
+Using Files to Specify the Stub Bodies +WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a bodyFileName instead of a +(literal) body. The files are resolved relative to a root directory (by default, +src/test/resources/__files). To customize this location you can set the files +attribute in the @AutoConfigureWireMock annotation to the location of the parent +directory (in other words, __files is a subdirectory). You can use Spring resource +notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body. + +When you configure the files root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of files has no +effect on the stubs loaded explicitly from the stubs attribute. + +
+
+Alternative: Using JUnit Rules +For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +the server. To do so, use the WireMockSpring convenience class to obtain an Options +instance, as shown in the following example: +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class WiremockForDocsClassRuleTests { + + // Start WireMock on some dynamic port + // for some reason `dynamicPort()` is not working properly + @ClassRule + public static WireMockClassRule wiremock = new WireMockClassRule( + WireMockSpring.options().dynamicPort()); + + // A service that calls out over HTTP to wiremock's port + @Autowired + private Service service; + + @Before + public void setup() { + this.service.setBase("http://localhost:" + wiremock.port()); + } + + // Using the WireMock APIs in the normal way: + @Test + public void contextLoads() throws Exception { + // Stubbing WireMock + wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse() + .withHeader("Content-Type", "text/plain").withBody("Hello World!"))); + // We're asserting if WireMock responded properly + assertThat(this.service.go()).isEqualTo("Hello World!"); + } + +} +The @ClassRule means that the server shuts down after all the methods in this class +have been run. +
+
+Relaxed SSL Validation for Rest Template +WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that’s not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course). +To make this work with minimum fuss, you need to be using the Spring Boot +RestTemplateBuilder in your app, as shown in the following example: +@Bean +public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); +} +You need RestTemplateBuilder because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the @AutoConfigureWireMock +annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the +@AutoConfigureHttpClient annotation as well, as shown in the following example: +@RunWith(SpringRunner.class) +@SpringBootTest("app.baseUrl=https://localhost:6443") +@AutoConfigureHttpClient +public class WiremockHttpsServerApplicationTests { + + @ClassRule + public static WireMockClassRule wiremock = new WireMockClassRule( + WireMockSpring.options().httpsPort(6443)); +... +} +If you are using spring-boot-starter-test, you have the Apache HTTP client on the +classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL +errors. If you use the default java.net client, you do not need the annotation (but it +won’t do any harm). There is no support currently for other clients, but it may be added +in future releases. +To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled +property to false. +
+
+WireMock and Spring MVC Mocks +Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring MockRestServiceServer. The following code shows an example: +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.NONE) +public class WiremockForDocsMockServerApplicationTests { + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private Service service; + + @Test + public void contextLoads() throws Exception { + // will read stubs classpath + MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) + .baseUrl("https://example.org").stubs("classpath:/stubs/resource.json") + .build(); + // We're asserting if WireMock responded properly + assertThat(this.service.go()).isEqualTo("Hello World"); + server.verify(); + } + +} +The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to +visit https://example.org/, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +WireMock website. +Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one). +
+
+Customization of WireMock configuration +You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +in order to customize the WireMock configuration (e.g. add custom transformers). +Example: + @Bean + WireMockConfigurationCustomizer optionsCustomizer() { + return new WireMockConfigurationCustomizer() { + @Override + public void customize(WireMockConfiguration options) { +// perform your customization here + } + }; + } +
+
+Generating Stubs using REST Docs +Spring REST Docs can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc +or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example using MockMvc: +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureRestDocs(outputDir = "target/snippets") +@AutoConfigureMockMvc +public class ApplicationTests { + + @Autowired + private MockMvc mockMvc; + + @Test + public void contextLoads() throws Exception { + mockMvc.perform(get("/resource")) + .andExpect(content().string("Hello World")) + .andDo(document("resource")); + } +} +This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. The same example with WebTestClient (used +for testing Spring WebFlux applications) would look like this: +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureRestDocs(outputDir = "target/snippets") +@AutoConfigureWebTestClient +public class ApplicationTests { + + @Autowired + private WebTestClient client; + + @Test + public void contextLoads() throws Exception { + client.get().uri("/resource").exchange() + .expectBody(String.class).isEqualTo("Hello World") + .consumeWith(document("resource")); + } +} +Without any additional configuration, these tests create a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects: + + +Creating a stub that matches only in the way you specify. + + +Asserting that the request in the test case also matches the same conditions. + + +The main entry point for this feature is WireMockRestDocs.verify(), which can be used +as a substitute for the document() convenience method, as shown in the following +example: +import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify; +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureRestDocs(outputDir = "target/snippets") +@AutoConfigureMockMvc +public class ApplicationTests { + + @Autowired + private MockMvc mockMvc; + + @Test + public void contextLoads() throws Exception { + mockMvc.perform(post("/resource") + .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) + .andExpect(status().isOk()) + .andDo(verify().jsonPath("$.id") + .stub("resource")); + } +} +This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to .jsonPath() to add additional +matchers. If JSON Path is unfamiliar, The JayWay +documentation can help you get up to speed. The WebTestClient version of this test +has a similar verify() static helper that you insert in the same place. +Instead of the jsonPath and contentType convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example: +@Test +public void contextLoads() throws Exception { + mockMvc.perform(post("/resource") + .content("{\"id\":\"123456\",\"message\":\"Hello World\"}")) + .andExpect(status().isOk()) + .andDo(verify() + .wiremock(WireMock.post( + urlPathEquals("/resource")) + .withRequestBody(matchingJsonPath("$.id")) + .stub("post-resource")); +} +The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example: + +post-resource.json + +{ + "request" : { + "url" : "/resource", + "method" : "POST", + "bodyPatterns" : [ { + "matchesJsonPath" : "$.id" + }] + }, + "response" : { + "status" : 200, + "body" : "Hello World", + "headers" : { + "X-Application-Context" : "application:-1", + "Content-Type" : "text/plain" + } + } +} + + + +You can use either the wiremock() method or the jsonPath() and contentType() +methods to create request matchers, but you can’t use both approaches. + +On the consumer side, you can make the resource.json generated earlier in this section +available on the classpath (by +<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this +document. +
+
+Generating Contracts by Using REST Docs +You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs. +Why would you want to use this feature? Some people in the community asked questions +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them. + +You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs. + +Consider the following test: + this.mockMvc + .perform(post("/foo").accept(MediaType.APPLICATION_PDF) + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"foo\": 23, \"bar\" : \"baz\" }")) + .andExpect(status().isOk()).andExpect(content().string("bar")) + // first WireMock + .andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]") + .jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]") + .contentType(MediaType.valueOf("application/json")) + .stub("shouldGrantABeerIfOldEnough")) + // then Contract DSL documentation + .andDo(document("index", SpringCloudContractRestDocs.dslContract())); +The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file. +The contract is called index.groovy and might look like the following example: +import org.springframework.cloud.contract.spec.Contract + +Contract.make { + request { + method 'POST' + url '/foo' + body(''' + {"foo": 23 } + ''') + headers { + header('''Accept''', '''application/json''') + header('''Content-Type''', '''application/json''') + } + } + response { + status OK() + body(''' + bar + ''') + headers { + header('''Content-Type''', '''application/json;charset=UTF-8''') + header('''Content-Length''', '''3''') + } + testMatchers { + jsonPath('$[?(@.foo >= 20)]', byType()) + } + } +} +The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be index/dsl-contract.adoc. +
+
+ +Migrations + +For up to date migration guides please visit +the project’s wiki page. + +This section covers migrating from one version of Spring Cloud Contract Verifier to the +next version. It covers the following versions upgrade paths: +
+1.0.x → 1.1.x +This section covers upgrading from version 1.0 to version 1.1. +
+New structure of generated stubs +In 1.1.x we have introduced a change to the structure of generated stubs. If you have +been using the @AutoConfigureWireMock notation to use the stubs from the classpath, +it no longer works. The following example shows how the @AutoConfigureWireMock notation +used to work: +@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084) +You must either change the location of the stubs to: +classpath:…​/META-INF/groupId/artifactId/version/mappings or use the new +classpath-based @AutoConfigureStubRunner, as shown in the following example: +@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084) +If you do not want to use @AutoConfigureStubRunner and you want to remain with the old +structure, set your plugin tasks accordingly. The following example would work for the +structure presented in the previous snippet. + +Maven + +<!-- start of pom.xml --> + +<properties> + <!-- we don't want the verifier to do a jar for us --> + <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip> +</properties> + +<!-- ... --> + +<!-- You need to set up the assembly plugin --> +<build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <id>stub</id> + <phase>prepare-package</phase> + <goals> + <goal>single</goal> + </goals> + <inherited>false</inherited> + <configuration> + <attach>true</attach> + <descriptor>${basedir}/src/assembly/stub.xml</descriptor> + </configuration> + </execution> + </executions> + </plugin> + </plugins> +</build> +<!-- end of pom.xml --> + +<!-- start of stub.xml--> + +<assembly + xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd"> + <id>stubs</id> + <formats> + <format>jar</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <fileSets> + <fileSet> + <directory>${project.build.directory}/snippets/stubs</directory> + <outputDirectory>customer-stubs/mappings</outputDirectory> + <includes> + <include>**/*</include> + </includes> + </fileSet> + <fileSet> + <directory>${basedir}/src/test/resources/contracts</directory> + <outputDirectory>customer-stubs/contracts</outputDirectory> + <includes> + <include>**/*.groovy</include> + </includes> + </fileSet> + </fileSets> +</assembly> + +<!-- end of stub.xml--> + + + +Gradle + +task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') { +// Preserve directory structure from 1.0.X of spring-cloud-contract + from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}" + into "${project.buildDir}/resources/main/customer-stubs" +} + + +
+
+
+1.1.x → 1.2.x +This section covers upgrading from version 1.1 to version 1.2. +
+Custom <literal>HttpServerStub</literal> +HttpServerStub includes a method that was not in version 1.1. The method is +String registeredMappings() If you have classes that implement HttpServerStub, you +now have to implement the registeredMappings() method. It should return a String +representing all mappings available in a single HttpServerStub. +See issue 355 for more +detail. +
+
+New packages for generated tests +The flow for setting the generated tests package name will look like this: + + +Set basePackageForTests + + +If basePackageForTests was not set, pick the package from baseClassForTests + + +If baseClassForTests was not set, pick packageWithBaseClasses + + +If nothing got set, pick the default value: +org.springframework.cloud.contract.verifier.tests + + +See issue 260 for more +detail. +
+
+New Methods in TemplateProcessor +In order to add support for fromRequest.path, the following methods had to be added to the +TemplateProcessor interface: + + +path() + + +path(int index) + + +See issue 388 for more +detail. +
+
+RestAssured 3.0 +Rest Assured, used in the generated test classes, got bumped to 3.0. If +you manually set versions of Spring Cloud Contract and the release train +you might see the following exception: +Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure: +[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist +This exception will occur due to the fact that the tests got generated with +an old version of plugin and at test execution time you have an incompatible +version of the release train (and vice versa). +Done via issue 267 +
+
+
+1.2.x → 2.0.x + +
+
+ +Links +The following links may be helpful when working with Spring Cloud Contract: + + +Spring Cloud Contract Github +Repository + + +Spring Cloud +Contract Samples + + +Spring Cloud Contract Gitter + + +Spring Cloud Contract WJUG Presentation by +Marcin Grzejszczak + + + +
\ No newline at end of file