diff --git a/.github/actions/await-http-resource/action.yml b/.github/actions/await-http-resource/action.yml new file mode 100644 index 000000000..ba177fb75 --- /dev/null +++ b/.github/actions/await-http-resource/action.yml @@ -0,0 +1,20 @@ +name: Await HTTP Resource +description: 'Waits for an HTTP resource to be available (a HEAD request succeeds)' +inputs: + url: + description: 'URL of the resource to await' + required: true +runs: + using: composite + steps: + - name: Await HTTP resource + shell: bash + run: | + url=${{ inputs.url }} + echo "Waiting for $url" + until curl --fail --head --silent ${{ inputs.url }} > /dev/null + do + echo "." + sleep 60 + done + echo "$url is available" diff --git a/.github/actions/build/action.yml b/.github/actions/build/action.yml new file mode 100644 index 000000000..70b051310 --- /dev/null +++ b/.github/actions/build/action.yml @@ -0,0 +1,66 @@ +name: Build +description: 'Builds the project, optionally publishing it to a local deployment repository' +inputs: + develocity-access-key: + description: 'Access key for authentication with ge.spring.io' + required: false + gradle-cache-read-only: + description: 'Whether Gradle''s cache should be read only' + required: false + default: 'true' + java-distribution: + description: 'Java distribution to use' + required: false + default: 'liberica' + java-early-access: + description: 'Whether the Java version is in early access' + required: false + default: 'false' + java-toolchain: + description: 'Whether a Java toolchain should be used' + required: false + default: 'false' + java-version: + description: 'Java version to compile and test with' + required: false + default: '17' + publish: + description: 'Whether to publish artifacts ready for deployment to Artifactory' + required: false + default: 'false' +outputs: + build-scan-url: + description: 'URL, if any, of the build scan produced by the build' + value: ${{ (inputs.publish == 'true' && steps.publish.outputs.build-scan-url) || steps.build.outputs.build-scan-url }} + version: + description: 'Version that was built' + value: ${{ steps.read-version.outputs.version }} +runs: + using: composite + steps: + - name: Prepare Gradle Build + uses: ./.github/actions/prepare-gradle-build + with: + cache-read-only: ${{ inputs.gradle-cache-read-only }} + develocity-access-key: ${{ inputs.develocity-access-key }} + java-distribution: ${{ inputs.java-distribution }} + java-early-access: ${{ inputs.java-early-access }} + java-toolchain: ${{ inputs.java-toolchain }} + java-version: ${{ inputs.java-version }} + - name: Build + id: build + if: ${{ inputs.publish == 'false' }} + shell: bash + run: ./gradlew build + - name: Publish + id: publish + if: ${{ inputs.publish == 'true' }} + shell: bash + run: ./gradlew -PdeploymentRepository=$(pwd)/deployment-repository ${{ !startsWith(github.event.head_commit.message, 'Next development version') && 'build' || '' }} publishAllPublicationsToDeploymentRepository + - name: Read Version From gradle.properties + id: read-version + shell: bash + run: | + version=$(sed -n 's/version=\(.*\)/\1/p' gradle.properties) + echo "Version is $version" + echo "version=$version" >> $GITHUB_OUTPUT diff --git a/.github/actions/create-github-release/action.yml b/.github/actions/create-github-release/action.yml new file mode 100644 index 000000000..03452537a --- /dev/null +++ b/.github/actions/create-github-release/action.yml @@ -0,0 +1,27 @@ +name: Create GitHub Release +description: 'Create the release on GitHub with a changelog' +inputs: + milestone: + description: 'Name of the GitHub milestone for which a release will be created' + required: true + pre-release: + description: 'Whether the release is a pre-release (a milestone or release candidate)' + required: false + default: 'false' + token: + description: 'Token to use for authentication with GitHub' + required: true +runs: + using: composite + steps: + - name: Generate Changelog + uses: spring-io/github-changelog-generator@185319ad7eaa75b0e8e72e4b6db19c8b2cb8c4c1 #v0.0.11 + with: + config-file: .github/actions/create-github-release/changelog-generator.yml + milestone: ${{ inputs.milestone }} + token: ${{ inputs.token }} + - name: Create GitHub Release + shell: bash + env: + GITHUB_TOKEN: ${{ inputs.token }} + run: gh release create ${{ format('v{0}', inputs.milestone) }} --notes-file changelog.md ${{ inputs.pre-release == 'true' && '--prerelease' || '' }} diff --git a/ci/config/changelog-generator.yml b/.github/actions/create-github-release/changelog-generator.yml similarity index 93% rename from ci/config/changelog-generator.yml rename to .github/actions/create-github-release/changelog-generator.yml index 9c7fa3589..0c1077fdf 100644 --- a/ci/config/changelog-generator.yml +++ b/.github/actions/create-github-release/changelog-generator.yml @@ -1,5 +1,4 @@ changelog: - repository: spring-projects/spring-restdocs sections: - title: ":star: New Features" labels: diff --git a/.github/actions/prepare-gradle-build/action.yml b/.github/actions/prepare-gradle-build/action.yml new file mode 100644 index 000000000..f9969cf31 --- /dev/null +++ b/.github/actions/prepare-gradle-build/action.yml @@ -0,0 +1,61 @@ +name: Prepare Gradle Build +description: 'Prepares a Gradle build. Sets up Java and Gradle and configures Gradle properties' +inputs: + cache-read-only: + description: 'Whether Gradle''s cache should be read only' + required: false + default: 'true' + develocity-access-key: + description: 'Access key for authentication with ge.spring.io' + required: false + java-distribution: + description: 'Java distribution to use' + required: false + default: 'liberica' + java-early-access: + description: 'Whether the Java version is in early access. When true, forces java-distribution to temurin' + required: false + default: 'false' + java-toolchain: + description: 'Whether a Java toolchain should be used' + required: false + default: 'false' + java-version: + description: 'Java version to use for the build' + required: false + default: '17' +runs: + using: composite + steps: + - name: Set Up Java + uses: actions/setup-java@v4 + with: + distribution: ${{ inputs.java-early-access == 'true' && 'temurin' || (inputs.java-distribution || 'liberica') }} + java-version: | + ${{ inputs.java-early-access == 'true' && format('{0}-ea', inputs.java-version) || inputs.java-version }} + ${{ inputs.java-toolchain == 'true' && '17' || '' }} + - name: Set Up Gradle With Read/Write Cache + if: ${{ inputs.cache-read-only == 'false' }} + uses: gradle/actions/setup-gradle@d156388eb19639ec20ade50009f3d199ce1e2808 # v4.1.0 + with: + cache-read-only: false + develocity-access-key: ${{ inputs.develocity-access-key }} + - name: Set Up Gradle + uses: gradle/actions/setup-gradle@d156388eb19639ec20ade50009f3d199ce1e2808 # v4.1.0 + with: + develocity-access-key: ${{ inputs.develocity-access-key }} + - name: Configure Gradle Properties + shell: bash + run: | + mkdir -p $HOME/.gradle + echo 'systemProp.user.name=spring-builds+github' >> $HOME/.gradle/gradle.properties + echo 'systemProp.org.gradle.internal.launcher.welcomeMessageEnabled=false' >> $HOME/.gradle/gradle.properties + echo 'org.gradle.daemon=false' >> $HOME/.gradle/gradle.properties + - name: Configure Toolchain Properties + if: ${{ inputs.java-toolchain == 'true' }} + shell: bash + run: | + echo toolchainVersion=${{ inputs.java-version }} >> $HOME/.gradle/gradle.properties + echo systemProp.org.gradle.java.installations.auto-detect=false >> $HOME/.gradle/gradle.properties + echo systemProp.org.gradle.java.installations.auto-download=false >> $HOME/.gradle/gradle.properties + echo systemProp.org.gradle.java.installations.paths=${{ format('$JAVA_HOME_{0}_X64', inputs.java-version) }} >> $HOME/.gradle/gradle.properties diff --git a/.github/actions/print-jvm-thread-dumps/action.yml b/.github/actions/print-jvm-thread-dumps/action.yml new file mode 100644 index 000000000..bcaebf367 --- /dev/null +++ b/.github/actions/print-jvm-thread-dumps/action.yml @@ -0,0 +1,17 @@ +name: Print JVM thread dumps +description: 'Prints a thread dump for all running JVMs' +runs: + using: composite + steps: + - if: ${{ runner.os == 'Linux' }} + shell: bash + run: | + for jvm_pid in $(jps -q -J-XX:+PerfDisableSharedMem); do + jcmd $jvm_pid Thread.print + done + - if: ${{ runner.os == 'Windows' }} + shell: powershell + run: | + foreach ($jvm_pid in $(jps -q -J-XX:+PerfDisableSharedMem)) { + jcmd $jvm_pid Thread.print + } diff --git a/.github/actions/send-notification/action.yml b/.github/actions/send-notification/action.yml new file mode 100644 index 000000000..b379e6789 --- /dev/null +++ b/.github/actions/send-notification/action.yml @@ -0,0 +1,39 @@ +name: Send Notification +description: 'Sends a Google Chat message as a notification of the job''s outcome' +inputs: + build-scan-url: + description: 'URL of the build scan to include in the notification' + required: false + run-name: + description: 'Name of the run to include in the notification' + required: false + default: ${{ format('{0} {1}', github.ref_name, github.job) }} + status: + description: 'Status of the job' + required: true + webhook-url: + description: 'Google Chat Webhook URL' + required: true +runs: + using: composite + steps: + - name: Prepare Variables + shell: bash + run: | + echo "BUILD_SCAN=${{ inputs.build-scan-url == '' && ' [build scan unavailable]' || format(' [<{0}|Build Scan>]', inputs.build-scan-url) }}" >> "$GITHUB_ENV" + echo "RUN_URL=${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" >> "$GITHUB_ENV" + - name: Success Notification + if: ${{ inputs.status == 'success' }} + shell: bash + run: | + curl -X POST '${{ inputs.webhook-url }}' -H 'Content-Type: application/json' -d '{ text: "<${{ env.RUN_URL }}|${{ inputs.run-name }}> was successful ${{ env.BUILD_SCAN }}"}' || true + - name: Failure Notification + if: ${{ inputs.status == 'failure' }} + shell: bash + run: | + curl -X POST '${{ inputs.webhook-url }}' -H 'Content-Type: application/json' -d '{ text: " *<${{ env.RUN_URL }}|${{ inputs.run-name }}> failed* ${{ env.BUILD_SCAN }}"}' || true + - name: Cancel Notification + if: ${{ inputs.status == 'cancelled' }} + shell: bash + run: | + curl -X POST '${{ inputs.webhook-url }}' -H 'Content-Type: application/json' -d '{ text: "<${{ env.RUN_URL }}|${{ inputs.run-name }}> was cancelled"}' || true diff --git a/.github/actions/sync-to-maven-central/action.yml b/.github/actions/sync-to-maven-central/action.yml new file mode 100644 index 000000000..ec3b20d36 --- /dev/null +++ b/.github/actions/sync-to-maven-central/action.yml @@ -0,0 +1,43 @@ +name: Sync to Maven Central +description: 'Syncs a release to Maven Central and waits for it to be available for use' +inputs: + jfrog-cli-config-token: + description: 'Config token for the JFrog CLI' + required: true + ossrh-s01-staging-profile: + description: 'Staging profile to use when syncing to Central' + required: true + ossrh-s01-token-password: + description: 'Password for authentication with s01.oss.sonatype.org' + required: true + ossrh-s01-token-username: + description: 'Username for authentication with s01.oss.sonatype.org' + required: true + spring-restdocs-version: + description: 'Version of Spring REST Docs that is being synced to Central' + required: true +runs: + using: composite + steps: + - name: Set Up JFrog CLI + uses: jfrog/setup-jfrog-cli@9fe0f98bd45b19e6e931d457f4e98f8f84461fb5 # v4.4.1 + env: + JF_ENV_SPRING: ${{ inputs.jfrog-cli-config-token }} + - name: Download Release Artifacts + shell: bash + run: jf rt download --spec ${{ format('{0}/artifacts.spec', github.action_path) }} --spec-vars 'buildName=${{ format('spring-restdocs-{0}', inputs.spring-restdocs-version) }};buildNumber=${{ github.run_number }}' + - name: Sync + uses: spring-io/nexus-sync-action@42477a2230a2f694f9eaa4643fa9e76b99b7ab84 # v0.0.1 + with: + close: true + create: true + generate-checksums: true + password: ${{ inputs.ossrh-s01-token-password }} + release: true + staging-profile-name: ${{ inputs.ossrh-s01-staging-profile }} + upload: true + username: ${{ inputs.ossrh-s01-token-username }} + - name: Await + uses: ./.github/actions/await-http-resource + with: + url: ${{ format('https://repo.maven.apache.org/maven2/org/springframework/restdocs/spring-restdocs-core/{0}/spring-restdocs-core-{0}.jar', inputs.spring-restdocs-version) }} diff --git a/.github/actions/sync-to-maven-central/artifacts.spec b/.github/actions/sync-to-maven-central/artifacts.spec new file mode 100644 index 000000000..82049730c --- /dev/null +++ b/.github/actions/sync-to-maven-central/artifacts.spec @@ -0,0 +1,20 @@ +{ + "files": [ + { + "aql": { + "items.find": { + "$and": [ + { + "@build.name": "${buildName}", + "@build.number": "${buildNumber}", + "path": { + "$nmatch": "org/springframework/restdocs/spring-restdocs/*" + } + } + ] + } + }, + "target": "nexus/" + } + ] +} diff --git a/.github/dco.yml b/.github/dco.yml new file mode 100644 index 000000000..0c4b142e9 --- /dev/null +++ b/.github/dco.yml @@ -0,0 +1,2 @@ +require: + members: false diff --git a/.github/workflows/build-and-deploy-snapshot.yml b/.github/workflows/build-and-deploy-snapshot.yml new file mode 100644 index 000000000..8850cec14 --- /dev/null +++ b/.github/workflows/build-and-deploy-snapshot.yml @@ -0,0 +1,45 @@ +name: Build and Deploy Snapshot +on: + push: + branches: + - main +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} +jobs: + build-and-deploy-snapshot: + name: Build and Deploy Snapshot + if: ${{ github.repository == 'spring-projects/spring-restdocs' }} + runs-on: ${{ vars.UBUNTU_MEDIUM || 'ubuntu-latest' }} + steps: + - name: Check Out Code + uses: actions/checkout@v4 + - name: Build and Publish + id: build-and-publish + uses: ./.github/actions/build + with: + develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + gradle-cache-read-only: false + publish: true + - name: Deploy + uses: spring-io/artifactory-deploy-action@26bbe925a75f4f863e1e529e85be2d0093cac116 # v0.0.1 + with: + artifact-properties: | + /**/spring-restdocs-*.zip::zip.type=docs,zip.deployed=false + build-name: 'spring-restdocs-4.0.x' + folder: 'deployment-repository' + password: ${{ secrets.ARTIFACTORY_PASSWORD }} + repository: ${{ 'libs-snapshot-local' }} + signing-key: ${{ secrets.GPG_PRIVATE_KEY }} + signing-passphrase: ${{ secrets.GPG_PASSPHRASE }} + uri: 'https://repo.spring.io' + username: ${{ secrets.ARTIFACTORY_USERNAME }} + - name: Send Notification + if: always() + uses: ./.github/actions/send-notification + with: + build-scan-url: ${{ steps.build-and-publish.outputs.build-scan-url }} + run-name: ${{ format('{0} | Linux | Java 17', github.ref_name) }} + status: ${{ job.status }} + webhook-url: ${{ secrets.GOOGLE_CHAT_WEBHOOK_URL }} + outputs: + version: ${{ steps.build-and-publish.outputs.version }} diff --git a/.github/workflows/build-pull-request.yml b/.github/workflows/build-pull-request.yml new file mode 100644 index 000000000..164c04dc2 --- /dev/null +++ b/.github/workflows/build-pull-request.yml @@ -0,0 +1,24 @@ +name: Build Pull Request +on: pull_request +permissions: + contents: read +jobs: + build: + name: Build Pull Request + if: ${{ github.repository == 'spring-projects/spring-restdocs' }} + runs-on: ${{ vars.UBUNTU_MEDIUM || 'ubuntu-latest' }} + steps: + - name: Check Out Code + uses: actions/checkout@v4 + - name: Build + id: build + uses: ./.github/actions/build + - name: Print JVM Thread Dumps When Cancelled + if: cancelled() + uses: ./.github/actions/print-jvm-thread-dumps + - name: Upload Build Reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: build-reports + path: '**/build/reports/' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..4df789601 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,59 @@ +name: CI +on: + push: + branches: + - main +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} +jobs: + ci: + name: '${{ matrix.os.name}} | Java ${{ matrix.java.version}}' + if: ${{ github.repository == 'spring-projects/spring-restdocs' }} + runs-on: ${{ matrix.os.id }} + strategy: + fail-fast: false + matrix: + os: + - id: ${{ vars.UBUNTU_MEDIUM || 'ubuntu-latest' }} + name: Linux + - id: windows-latest + name: Windows + java: + - version: 17 + toolchain: false + - version: 21 + toolchain: false + - version: 24 + toolchain: false + exclude: + - os: + name: Linux + java: + version: 17 + steps: + - name: Prepare Windows runner + if: ${{ runner.os == 'Windows' }} + run: | + git config --global core.autocrlf true + git config --global core.longPaths true + Stop-Service -name Docker + - name: Check Out Code + uses: actions/checkout@v4 + - name: Build + id: build + uses: ./.github/actions/build + with: + develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + gradle-cache-read-only: false + java-early-access: ${{ matrix.java.early-access || 'false' }} + java-distribution: ${{ matrix.java.distribution }} + java-toolchain: ${{ matrix.java.toolchain }} + java-version: ${{ matrix.java.version }} + - name: Send Notification + if: always() + uses: ./.github/actions/send-notification + with: + build-scan-url: ${{ steps.build.outputs.build-scan-url }} + run-name: ${{ format('{0} | {1} | Java {2}', github.ref_name, matrix.os.name, matrix.java.version) }} + status: ${{ job.status }} + webhook-url: ${{ secrets.GOOGLE_CHAT_WEBHOOK_URL }} diff --git a/.github/workflows/delete-staged-release.yml b/.github/workflows/delete-staged-release.yml new file mode 100644 index 000000000..56aff2b40 --- /dev/null +++ b/.github/workflows/delete-staged-release.yml @@ -0,0 +1,18 @@ +name: Delete Staged Release +on: + workflow_dispatch: + inputs: + build-version: + description: 'Version of the build to delete' + required: true +jobs: + delete-staged-release: + name: Delete Staged Release + runs-on: ubuntu-latest + steps: + - name: Set up JFrog CLI + uses: jfrog/setup-jfrog-cli@9fe0f98bd45b19e6e931d457f4e98f8f84461fb5 # v4.4.1 + env: + JF_ENV_SPRING: ${{ secrets.JF_ARTIFACTORY_SPRING }} + - name: Delete Build + run: jfrog rt delete --build spring-restdocs-${{ github.event.inputs.build-version }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..ef92b5cb7 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,80 @@ +name: Release +on: + push: + tags: + - v3.0.[0-9]+ +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} +jobs: + build-and-stage-release: + name: Build and Stage Release + if: ${{ github.repository == 'spring-projects/spring-restdocs' }} + runs-on: ${{ vars.UBUNTU_MEDIUIM || 'ubuntu-latest' }} + steps: + - name: Check Out Code + uses: actions/checkout@v4 + - name: Build and Publish + id: build-and-publish + uses: ./.github/actions/build + with: + develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + gradle-cache-read-only: false + publish: true + - name: Stage Release + uses: spring-io/artifactory-deploy-action@26bbe925a75f4f863e1e529e85be2d0093cac116 # v0.0.1 + with: + artifact-properties: | + /**/spring-restdocs-*.zip::zip.type=docs,zip.deployed=false + build-name: ${{ format('spring-restdocs-{0}', steps.build-and-publish.outputs.version) }} + folder: 'deployment-repository' + password: ${{ secrets.ARTIFACTORY_PASSWORD }} + repository: 'libs-staging-local' + signing-key: ${{ secrets.GPG_PRIVATE_KEY }} + signing-passphrase: ${{ secrets.GPG_PASSPHRASE }} + uri: 'https://repo.spring.io' + username: ${{ secrets.ARTIFACTORY_USERNAME }} + outputs: + version: ${{ steps.build-and-publish.outputs.version }} + sync-to-maven-central: + name: Sync to Maven Central + needs: + - build-and-stage-release + runs-on: ${{ vars.UBUNTU_SMALL || 'ubuntu-latest' }} + steps: + - name: Check Out Code + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - name: Sync to Maven Central + uses: ./.github/actions/sync-to-maven-central + with: + jfrog-cli-config-token: ${{ secrets.JF_ARTIFACTORY_SPRING }} + ossrh-s01-staging-profile: ${{ secrets.OSSRH_S01_STAGING_PROFILE }} + ossrh-s01-token-password: ${{ secrets.OSSRH_S01_TOKEN_PASSWORD }} + ossrh-s01-token-username: ${{ secrets.OSSRH_S01_TOKEN_USERNAME }} + spring-restdocs-version: ${{ needs.build-and-stage-release.outputs.version }} + promote-release: + name: Promote Release + needs: + - build-and-stage-release + - sync-to-maven-central + runs-on: ${{ vars.UBUNTU_SMALL || 'ubuntu-latest' }} + steps: + - name: Set up JFrog CLI + uses: jfrog/setup-jfrog-cli@9fe0f98bd45b19e6e931d457f4e98f8f84461fb5 # v4.4.1 + env: + JF_ENV_SPRING: ${{ secrets.JF_ARTIFACTORY_SPRING }} + - name: Promote Open Source Build + run: jfrog rt build-promote ${{ format('spring-restdocs-{0}', needs.build-and-stage-release.outputs.version)}} ${{ github.run_number }} libs-release-local + create-github-release: + name: Create GitHub Release + needs: + - build-and-stage-release + - promote-release + runs-on: ${{ vars.UBUNTU_SMALL || 'ubuntu-latest' }} + steps: + - name: Check Out Code + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - name: Create GitHub Release + uses: ./.github/actions/create-github-release + with: + milestone: ${{ needs.build-and-stage-release.outputs.version }} + token: ${{ secrets.GH_ACTIONS_REPO_TOKEN }} diff --git a/.gitignore b/.gitignore index c508c0c30..c01583a59 100644 --- a/.gitignore +++ b/.gitignore @@ -6,5 +6,6 @@ bin build !buildSrc/src/main/groovy/org/springframework/restdocs/build/ target -.idea +.idea/* +!.idea/icon.svg *.iml \ No newline at end of file diff --git a/.idea/icon.svg b/.idea/icon.svg new file mode 100644 index 000000000..5e6592046 --- /dev/null +++ b/.idea/icon.svg @@ -0,0 +1,8 @@ + + + + + \ No newline at end of file diff --git a/.sdkmanrc b/.sdkmanrc index 55b7d1b70..bea2d5156 100644 --- a/.sdkmanrc +++ b/.sdkmanrc @@ -1,3 +1,3 @@ # Enable auto-env through the sdkman_auto_env config # Add key=value pairs of SDKs to use below -java=8.0.422-librca +java=17.0.15-librca diff --git a/.springjavaformatconfig b/.springjavaformatconfig deleted file mode 100644 index 6d408bb83..000000000 --- a/.springjavaformatconfig +++ /dev/null @@ -1 +0,0 @@ -java-baseline=8 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 34627e39f..24e7b4254 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,11 +8,10 @@ If you would like to contribute something, or simply want to work with the code, This project adheres to the Contributor Covenant [code of conduct][1]. By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io. -## Sign the contributor license agreement - -Before we accept a non-trivial patch or pull request we will need you to sign the [contributor's license agreement (CLA)][2]. -Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. +## Include a Signed-off-by Trailer +All commits must include a _Signed-off-by_ trailer at the end of each commit message to indicate that the contributor agrees to the [Developer Certificate of Origin (DCO)](https://en.wikipedia.org/wiki/Developer_Certificate_of_Origin). +For additional details, please refer to the ["Hello DCO, Goodbye CLA: Simplifying Contributions to Spring"](https://spring.io/blog/2025/01/06/hello-dco-goodbye-cla-simplifying-contributions-to-spring) blog post. ## Code conventions and housekeeping @@ -31,7 +30,7 @@ None of these is essential for a pull request, but they will all help ### Building from source -To build the source you will need Java 8 or later. +To build the source you will need Java 17 or later. The code is built with Gradle: ``` diff --git a/README.md b/README.md index a29c58913..e3dec714d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Spring REST Docs [![Build status][1]][2] +# Spring REST Docs [![Build status][1]][2] [![Revved up by Develocity][23]][24] ## Overview @@ -14,7 +14,7 @@ To learn more about Spring REST Docs, please consult the [reference documentatio ## Building from source -You will need Java 8 or later to build Spring REST Docs. +You will need Java 17 or later to build Spring REST Docs. It is built using [Gradle][10]: ``` @@ -29,23 +29,22 @@ There are several that you can contribute to Spring REST Docs: - Open a [pull request][12]. Please see the [contributor guidelines][13] for details - Ask and answer questions on Stack Overflow using the [`spring-restdocs`][15] tag - - Chat with fellow users [on Gitter][16] ## Third-party extensions | Name | Description | | ---- | ----------- | -| [restdocs-wiremock][17] | Auto-generate WireMock stubs as part of documenting your RESTful API | -| [restdocsext-jersey][18] | Enables Spring REST Docs to be used with [Jersey's test framework][19] | -| [spring-auto-restdocs][20] | Uses introspection and Javadoc to automatically document request and response parameters | -| [restdocs-api-spec][21] | A Spring REST Docs extension that adds API specification support. It currently supports [OpenAPI 2][22] and [OpenAPI 3][23] | +| [restdocs-wiremock][16] | Auto-generate WireMock stubs as part of documenting your RESTful API | +| [restdocsext-jersey][17] | Enables Spring REST Docs to be used with [Jersey's test framework][18] | +| [spring-auto-restdocs][19] | Uses introspection and Javadoc to automatically document request and response parameters | +| [restdocs-api-spec][20] | A Spring REST Docs extension that adds API specification support. It currently supports [OpenAPI 2][21] and [OpenAPI 3][22] | ## Licence Spring REST Docs is open source software released under the [Apache 2.0 license][14]. -[1]: https://ci.spring.io/api/v1/teams/spring-restdocs/pipelines/spring-restdocs-2.0.x/jobs/build/badge (Build status) -[2]: https://ci.spring.io/teams/spring-restdocs/pipelines/spring-restdocs-2.0.x?groups=build +[1]: https://github.com/spring-projects/spring-restdocs/actions/workflows/build-and-deploy-snapshot.yml/badge.svg?branch=main (Build status) +[2]: https://github.com/spring-projects/spring-restdocs/actions/workflows/build-and-deploy-snapshot.yml [3]: https://asciidoctor.org [4]: https://docs.spring.io/spring-framework/docs/4.1.x/spring-framework-reference/htmlsingle/#spring-mvc-test-framework [5]: https://developer.github.com/v3/ @@ -59,11 +58,12 @@ Spring REST Docs is open source software released under the [Apache 2.0 license] [13]: CONTRIBUTING.md [14]: https://www.apache.org/licenses/LICENSE-2.0.html [15]: https://stackoverflow.com/tags/spring-restdocs -[16]: https://gitter.im/spring-projects/spring-restdocs -[17]: https://github.com/ePages-de/restdocs-wiremock -[18]: https://github.com/RESTDocsEXT/restdocsext-jersey -[19]: https://jersey.java.net/documentation/latest/test-framework.html -[20]: https://github.com/ScaCap/spring-auto-restdocs -[21]: https://github.com/ePages-de/restdocs-api-spec -[22]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md -[23]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md +[16]: https://github.com/ePages-de/restdocs-wiremock +[17]: https://github.com/RESTDocsEXT/restdocsext-jersey +[18]: https://jersey.java.net/documentation/latest/test-framework.html +[19]: https://github.com/ScaCap/spring-auto-restdocs +[20]: https://github.com/ePages-de/restdocs-api-spec +[21]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md +[22]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md +[23]: https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?logo=Gradle&labelColor=02303A +[24]: https://ge.spring.io/scans?search.rootProjectNames=spring-restdocs diff --git a/build.gradle b/build.gradle index 7bccc4951..32bea2f44 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ plugins { id 'base' id 'io.spring.javaformat' version "$javaFormatVersion" apply false - id 'io.spring.nohttp' version '0.0.10' apply false + id 'io.spring.nohttp' version '0.0.11' apply false id 'maven-publish' } @@ -10,32 +10,33 @@ allprojects { repositories { mavenCentral() maven { - url "https://repo.spring.io/snapshot" + url = "https://repo.spring.io/milestone" content { - includeGroup("org.springframework") + includeGroup "io.micrometer" + includeGroup "io.projectreactor" + includeGroup "org.springframework" } } + if (version.endsWith('-SNAPSHOT')) { + maven { url = "https://repo.spring.io/snapshot" } + } } } -apply plugin: "samples" apply plugin: "io.spring.nohttp" apply from: "${rootProject.projectDir}/gradle/publish-maven.gradle" nohttp { - source.exclude "samples/rest-notes-slate/slate/**" source.exclude "buildSrc/.gradle/**" source.exclude "**/build/**" source.exclude "**/target/**" } ext { - springVersion = "5.0.15.RELEASE" javadocLinks = [ - "https://docs.oracle.com/javase/8/docs/api/", - "https://docs.spring.io/spring-framework/docs/$springVersion/javadoc-api/", - "https://docs.jboss.org/hibernate/validator/6.0/api/", - "https://jakarta.ee/specifications/bean-validation/2.0/apidocs/" + "https://docs.spring.io/spring-framework/docs/$springFrameworkVersion/javadoc-api/", + "https://docs.jboss.org/hibernate/validator/9.0/api/", + "https://jakarta.ee/specifications/bean-validation/3.1/apidocs/" ] as String[] } @@ -48,10 +49,15 @@ subprojects { subproject -> subproject.apply plugin: "io.spring.javaformat" subproject.apply plugin: "checkstyle" - sourceCompatibility = 1.8 - targetCompatibility = 1.8 + java { + sourceCompatibility = 17 + targetCompatibility = 17 + } configurations { + all { + resolutionStrategy.cacheChangingModulesFor 0, "minutes" + } internal { canBeConsumed = false canBeResolved = false @@ -64,7 +70,7 @@ subprojects { subproject -> test { testLogging { - exceptionFormat "full" + exceptionFormat = "full" } } @@ -80,16 +86,15 @@ subprojects { subproject -> checkstyle { configFile = rootProject.file("config/checkstyle/checkstyle.xml") configProperties = [ "checkstyle.config.dir" : rootProject.file("config/checkstyle") ] - toolVersion = "10.11.0" + toolVersion = "10.12.4" } dependencies { - checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:$javaFormatVersion") + checkstyle("com.puppycrawl.tools:checkstyle:${checkstyle.toolVersion}") + checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:${javaFormatVersion}") } plugins.withType(MavenPublishPlugin) { - subproject.apply from: "${rootProject.projectDir}/gradle/publish-maven.gradle" - javadoc { description = "Generates project-level javadoc for use in -javadoc jar" options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED @@ -99,7 +104,7 @@ subprojects { subproject -> options.links = javadocLinks options.addStringOption "-quiet" options.encoding = "UTF-8" - options.source = "1.8" + options.source = "17" } java { @@ -108,51 +113,15 @@ subprojects { subproject -> } } } - + plugins.withType(MavenPublishPlugin) { + subproject.apply from: "${rootProject.projectDir}/gradle/publish-maven.gradle" + } tasks.withType(GenerateModuleMetadata) { enabled = false } } -samples { - dependOn "spring-restdocs-core:publishToMavenLocal" - dependOn "spring-restdocs-mockmvc:publishToMavenLocal" - dependOn "spring-restdocs-restassured:publishToMavenLocal" - dependOn "spring-restdocs-webtestclient:publishToMavenLocal" - dependOn "spring-restdocs-asciidoctor:publishToMavenLocal" - - restNotesSpringHateoas { - workingDir "$projectDir/samples/rest-notes-spring-hateoas" - } - - restNotesSpringDataRest { - workingDir "$projectDir/samples/rest-notes-spring-data-rest" - } - - testNg { - workingDir "$projectDir/samples/testng" - } - - restAssured { - workingDir "$projectDir/samples/rest-assured" - } - - webTestClient { - workingDir "$projectDir/samples/web-test-client" - } - - slate { - workingDir "$projectDir/samples/rest-notes-slate" - build false - } - - junit5 { - workingDir "$projectDir/samples/junit5" - } - -} - task api (type: Javadoc) { group = "Documentation" description = "Generates aggregated Javadoc API documentation." @@ -172,7 +141,7 @@ task api (type: Javadoc) { encoding = "UTF-8" memberLevel = "protected" outputLevel = "quiet" - source = "1.8" + source = "17" splitIndex = true use = true windowTitle = "Spring REST Docs ${project.version} API" @@ -180,7 +149,7 @@ task api (type: Javadoc) { } } -task docsZip(type: Zip, dependsOn: [":docs:asciidoctor", ":api", ":restNotesSpringHateoasGradle"]) { +task docsZip(type: Zip, dependsOn: [":docs:asciidoctor", ":api"]) { group = "Distribution" archiveBaseName = "spring-restdocs" archiveClassifier = "docs" @@ -188,16 +157,12 @@ task docsZip(type: Zip, dependsOn: [":docs:asciidoctor", ":api", ":restNotesSpri destinationDirectory = file("${project.buildDir}/distributions") from(project.tasks.findByPath(":docs:asciidoctor")) { - into "reference/html5" + into "reference/htmlsingle" } from(api) { into "api" } - - from(file("samples/rest-notes-spring-hateoas/build/docs/asciidoc")) { - into "samples/restful-notes" - } } publishing { diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 400a425c5..6746f1805 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -1,4 +1,3 @@ plugins { id "java-gradle-plugin" - id "groovy-gradle-plugin" } diff --git a/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SampleBuildConfigurer.groovy b/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SampleBuildConfigurer.groovy deleted file mode 100644 index 530f8ae17..000000000 --- a/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SampleBuildConfigurer.groovy +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2014-2021 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.restdocs.build.samples - -import org.gradle.api.GradleException -import org.gradle.api.Project -import org.gradle.api.Task -import org.gradle.api.tasks.Exec -import org.gradle.api.tasks.Copy -import org.gradle.api.tasks.GradleBuild - -class SampleBuildConfigurer { - - private final String name - - private String workingDir - - private boolean build = true - - SampleBuildConfigurer(String name) { - this.name = name - } - - void workingDir(String workingDir) { - this.workingDir = workingDir - } - - void build(boolean build) { - this.build = build - } - - Task createTask(Project project, Object... dependencies) { - File sampleDir = new File(this.workingDir).absoluteFile - - Task sampleBuild = project.tasks.create name - sampleBuild.description = "Builds the ${name} sample" - sampleBuild.group = "Build" - - if (new File(sampleDir, 'build.gradle').isFile()) { - Task gradleVersionsUpdate = createGradleVersionsUpdate(project) - sampleBuild.dependsOn gradleVersionsUpdate - if (build) { - Task gradleBuild = createGradleBuild(project, sampleDir, dependencies) - Task verifyIncludesTask = createVerifyIncludes(project, new File(sampleDir, 'build/docs/asciidoc')) - verifyIncludesTask.dependsOn gradleBuild - sampleBuild.dependsOn verifyIncludesTask - gradleBuild.dependsOn gradleVersionsUpdate - } - } - else if (new File(sampleDir, 'pom.xml').isFile()) { - Task mavenVersionsUpdate = createMavenVersionsUpdate(project) - sampleBuild.dependsOn mavenVersionsUpdate - if (build) { - Task mavenBuild = createMavenBuild(project, sampleDir, dependencies) - Task verifyIncludesTask = createVerifyIncludes(project, new File(sampleDir, 'target/generated-docs')) - verifyIncludesTask.dependsOn(mavenBuild) - sampleBuild.dependsOn verifyIncludesTask - mavenBuild.dependsOn mavenVersionsUpdate - } - } - else { - throw new IllegalStateException("No pom.xml or build.gradle was found in $sampleDir") - } - return sampleBuild - } - - private Task createMavenVersionsUpdate(Project project) { - Task mavenVersionsUpdate = project.tasks.create "${name}MavenVersionUpdates" - mavenVersionsUpdate.doFirst { - replaceVersion(new File(this.workingDir, 'pom.xml'), - '.*', - "${project.version}") - } - return mavenVersionsUpdate - } - - private Task createGradleVersionsUpdate(Project project) { - Task gradleVersionsUpdate = project.tasks.create "${name}GradleVersionUpdates" - gradleVersionsUpdate.doFirst { - replaceVersion(new File(this.workingDir, 'build.gradle'), - "ext\\['spring-restdocs.version'\\] = '.*'", - "ext['spring-restdocs.version'] = '${project.version}'") - replaceVersion(new File(this.workingDir, 'build.gradle'), - "restDocsVersion = \".*\"", - "restDocsVersion = \"${project.version}\"") - } - return gradleVersionsUpdate - } - - private Task createMavenBuild(Project project, File sampleDir, Object... dependencies) { - Task mavenBuild = project.tasks.create("${name}Maven", Exec) - mavenBuild.description = "Builds the ${name} sample with Maven" - mavenBuild.group = "Build" - mavenBuild.workingDir = this.workingDir - mavenBuild.commandLine = [isWindows() ? "${sampleDir.absolutePath}/mvnw.cmd" : './mvnw', 'clean', 'package'] - mavenBuild.dependsOn dependencies - return mavenBuild - } - - private boolean isWindows() { - return File.separatorChar == '\\' - } - - private Task createGradleBuild(Project project, File sampleDir, Object... dependencies) { - Task gradleBuild = project.tasks.create("${name}Gradle", Exec) - gradleBuild.description = "Builds the ${name} sample with Gradle" - gradleBuild.group = "Build" - gradleBuild.workingDir = this.workingDir - gradleBuild.commandLine = [isWindows() ? "${sampleDir.absolutePath}/gradlew.bat" : './gradlew', 'clean', 'build', '--no-daemon'] - gradleBuild.dependsOn dependencies - return gradleBuild - } - - private void replaceVersion(File target, String pattern, String replacement) { - def lines = target.readLines() - target.withWriter { writer -> - lines.each { line -> - writer.println(line.replaceAll(pattern, replacement)) - } - } - } - - private Task createVerifyIncludes(Project project, File buildDir) { - Task verifyIncludesTask = project.tasks.create("${name}VerifyIncludes") - verifyIncludesTask.description = "Verifies the includes in the ${name} sample" - verifyIncludesTask.doLast { - Map unprocessedIncludes = [:] - buildDir.eachFileRecurse { file -> - if (file.name.endsWith('.html')) { - file.eachLine { line -> - if (line.contains(new File(this.workingDir).absolutePath)) { - unprocessedIncludes.get(file, []).add(line) - } - } - } - } - if (unprocessedIncludes) { - StringWriter message = new StringWriter() - PrintWriter writer = new PrintWriter(message) - writer.println 'Found unprocessed includes:' - unprocessedIncludes.each { file, lines -> - writer.println " ${file}:" - lines.each { line -> writer.println " ${line}" } - } - throw new GradleException(message.toString()) - } - } - return verifyIncludesTask - } -} diff --git a/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SamplesExtension.groovy b/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SamplesExtension.groovy deleted file mode 100644 index f606e2d6d..000000000 --- a/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SamplesExtension.groovy +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2014-2021 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.restdocs.build.samples - -import org.gradle.api.Project -import org.gradle.api.Task - -class SamplesExtension { - - Project Project - - Task buildSamplesTask - - Object[] dependencies = [] - - SamplesExtension(Project project, Task buildSamplesTask) { - this.project = project - this.buildSamplesTask = buildSamplesTask - } - - void dependOn(Object... paths) { - this.dependencies += paths - } - - def methodMissing(String name, args) { - SampleBuildConfigurer configurer = new SampleBuildConfigurer(name) - Closure closure = args[0] - closure.delegate = configurer - closure.resolveStrategy = Closure.DELEGATE_FIRST - closure.call() - Task task = configurer.createTask(this.project, this.dependencies) - this.buildSamplesTask.dependsOn task - } - -} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SamplesPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SamplesPlugin.groovy deleted file mode 100644 index f2f65317a..000000000 --- a/buildSrc/src/main/groovy/org/springframework/restdocs/build/samples/SamplesPlugin.groovy +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2014-2021 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.restdocs.build.samples - -import org.gradle.api.Plugin -import org.gradle.api.Project - -class SamplesPlugin implements Plugin { - - void apply(Project project) { - def buildSamplesTask = project.tasks.create('buildSamples') - buildSamplesTask.description = 'Builds the configured samples' - buildSamplesTask.group = 'Build' - project.extensions.create('samples', SamplesExtension, project, buildSamplesTask) - } - -} \ No newline at end of file diff --git a/buildSrc/src/main/java/org/springframework/restdocs/build/optional/OptionalDependenciesPlugin.java b/buildSrc/src/main/java/org/springframework/restdocs/build/optional/OptionalDependenciesPlugin.java index c389b1454..cb8642785 100644 --- a/buildSrc/src/main/java/org/springframework/restdocs/build/optional/OptionalDependenciesPlugin.java +++ b/buildSrc/src/main/java/org/springframework/restdocs/build/optional/OptionalDependenciesPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2024 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. @@ -21,7 +21,7 @@ import org.gradle.api.artifacts.Configuration; import org.gradle.api.attributes.Usage; import org.gradle.api.plugins.JavaPlugin; -import org.gradle.api.plugins.JavaPluginConvention; +import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.api.tasks.javadoc.Javadoc; import org.gradle.plugins.ide.eclipse.EclipsePlugin; @@ -46,14 +46,14 @@ public class OptionalDependenciesPlugin implements Plugin { public void apply(Project project) { Configuration optional = project.getConfigurations().create(OPTIONAL_CONFIGURATION_NAME); project.getConfigurations().all((configuration) -> { - if (configuration.getName().startsWith("testRuntimeClasspath_")) { + if (configuration.getName().startsWith("testRuntimeClasspath_") || configuration.getName().startsWith("testCompileClasspath_")) { configuration.extendsFrom(optional); } }); optional.attributes((attributes) -> attributes.attribute(Usage.USAGE_ATTRIBUTE, project.getObjects().named(Usage.class, Usage.JAVA_RUNTIME))); project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> { - SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class) + SourceSetContainer sourceSets = project.getExtensions().getByType(JavaPluginExtension.class) .getSourceSets(); sourceSets.all((sourceSet) -> { sourceSet.setCompileClasspath(sourceSet.getCompileClasspath().plus(optional)); diff --git a/buildSrc/src/main/resources/META-INF/gradle-plugins/samples.properties b/buildSrc/src/main/resources/META-INF/gradle-plugins/samples.properties deleted file mode 100644 index 062b9c795..000000000 --- a/buildSrc/src/main/resources/META-INF/gradle-plugins/samples.properties +++ /dev/null @@ -1 +0,0 @@ -implementation-class: org.springframework.restdocs.build.samples.SamplesPlugin \ No newline at end of file diff --git a/ci/README.adoc b/ci/README.adoc deleted file mode 100644 index 396bbcf98..000000000 --- a/ci/README.adoc +++ /dev/null @@ -1,17 +0,0 @@ -== Concourse pipeline - -Ensure that you've setup the spring-restdocs target and can login - -[source] ----- -$ fly -t spring-restdocs login -n spring-restdocs -c https://ci.spring.io ----- - -The pipeline can be deployed using the following command: - -[source] ----- -$ fly -t spring-restdocs set-pipeline -p spring-restdocs-2.0.x -c ci/pipeline.yml -l ci/parameters.yml ----- - -NOTE: This assumes that you have Vault integration configured with the appropriate secrets. diff --git a/ci/config/release-scripts.yml b/ci/config/release-scripts.yml deleted file mode 100644 index 5199d1818..000000000 --- a/ci/config/release-scripts.yml +++ /dev/null @@ -1,10 +0,0 @@ -logging: - level: - io.spring.concourse: DEBUG -spring: - main: - banner-mode: off -sonatype: - exclude: - - 'build-info\.json' - - 'org/springframework/restdocs/spring-restdocs/.*' diff --git a/ci/images/README.adoc b/ci/images/README.adoc deleted file mode 100644 index 92fa3c2ec..000000000 --- a/ci/images/README.adoc +++ /dev/null @@ -1,21 +0,0 @@ -== CI Images - -These images are used by CI to run the actual builds. - -To build the image locally run the following from this directory: - ----- -$ docker build --no-cache -f /Dockerfile . ----- - -For example - ----- -$ docker build --no-cache -f ci-image/Dockerfile . ----- - -To test run: - ----- -$ docker run -it --entrypoint /bin/bash ----- diff --git a/ci/images/ci-image/Dockerfile b/ci/images/ci-image/Dockerfile deleted file mode 100644 index 5c2ed726d..000000000 --- a/ci/images/ci-image/Dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM ubuntu:focal-20220531 - -ADD setup.sh /setup.sh -ADD get-jdk-url.sh /get-jdk-url.sh -RUN ./setup.sh java8 - -ENV JAVA_HOME /opt/openjdk -ENV PATH $JAVA_HOME/bin:$PATH diff --git a/ci/images/get-jdk-url.sh b/ci/images/get-jdk-url.sh deleted file mode 100755 index 8a0416791..000000000 --- a/ci/images/get-jdk-url.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -set -e - -case "$1" in - java8) - echo "https://github.com/bell-sw/Liberica/releases/download/8u333+2/bellsoft-jdk8u333+2-linux-amd64.tar.gz" - ;; - *) - echo $"Unknown java version" - exit 1 -esac diff --git a/ci/images/setup.sh b/ci/images/setup.sh deleted file mode 100755 index 6661b0587..000000000 --- a/ci/images/setup.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash -set -ex - -########################################################### -# UTILS -########################################################### - -export DEBIAN_FRONTEND=noninteractive -apt-get update -apt-get install --no-install-recommends -y tzdata ca-certificates net-tools libxml2-utils git curl libudev1 libxml2-utils iptables iproute2 jq unzip -ln -fs /usr/share/zoneinfo/UTC /etc/localtime -dpkg-reconfigure --frontend noninteractive tzdata -rm -rf /var/lib/apt/lists/* - -curl https://raw.githubusercontent.com/spring-io/concourse-java-scripts/v0.0.4/concourse-java.sh > /opt/concourse-java.sh - -########################################################### -# JAVA -########################################################### -JDK_URL=$( ./get-jdk-url.sh $1 ) - -mkdir -p /opt/openjdk -cd /opt/openjdk -curl -L ${JDK_URL} | tar zx --strip-components=1 -test -f /opt/openjdk/bin/java -test -f /opt/openjdk/bin/javac - -########################################################### -# GRADLE ENTERPRISE -########################################################### -mkdir ~/.gradle -echo 'systemProp.user.name=concourse' > ~/.gradle/gradle.properties \ No newline at end of file diff --git a/ci/parameters.yml b/ci/parameters.yml deleted file mode 100644 index c882eafb7..000000000 --- a/ci/parameters.yml +++ /dev/null @@ -1,12 +0,0 @@ -github-organization: "spring-projects" -github-repository: "spring-restdocs" -docker-hub-organization: "springci" -artifactory-server: "https://repo.spring.io" -branch: "2.0.x" -milestone: "2.0.x" -build-name: "spring-restdocs" -concourse-url: "https://ci.spring.io" -task-timeout: 1h00m -registry-mirror-host: docker.repo.spring.io -registry-mirror-username: ((artifactory-username)) -registry-mirror-password: ((artifactory-password)) \ No newline at end of file diff --git a/ci/pipeline.yml b/ci/pipeline.yml deleted file mode 100644 index 6444a71da..000000000 --- a/ci/pipeline.yml +++ /dev/null @@ -1,408 +0,0 @@ -anchors: - git-repo-resource-source: &git-repo-resource-source - uri: "https://github.com/((github-organization))/((github-repository)).git" - username: ((github-username)) - password: ((github-password)) - branch: ((branch)) - registry-image-resource-source: ®istry-image-resource-source - username: ((docker-hub-username)) - password: ((docker-hub-password)) - tag: ((milestone)) - gradle-enterprise-task-params: &gradle-enterprise-task-params - GRADLE_ENTERPRISE_ACCESS_KEY: ((gradle_enterprise_secret_access_key)) - GRADLE_ENTERPRISE_CACHE_USERNAME: ((gradle_enterprise_cache_user.username)) - GRADLE_ENTERPRISE_CACHE_PASSWORD: ((gradle_enterprise_cache_user.password)) - docker-hub-task-params: &docker-hub-task-params - DOCKER_HUB_USERNAME: ((docker-hub-username)) - DOCKER_HUB_PASSWORD: ((docker-hub-password)) - github-task-params: &github-task-params - GITHUB_REPO: ((github-repository)) - GITHUB_ORGANIZATION: ((github-organization)) - GITHUB_PASSWORD: ((github-ci-release-token)) - GITHUB_USERNAME: ((github-username)) - MILESTONE: ((milestone)) - sontatype-task-params: &sonatype-task-params - SONATYPE_USERNAME: ((s01-user-token)) - SONATYPE_PASSWORD: ((s01-user-token-password)) - SONATYPE_URL: ((sonatype-url)) - SONATYPE_STAGING_PROFILE_ID: ((sonatype-staging-profile-id)) - artifactory-task-params: &artifactory-task-params - ARTIFACTORY_SERVER: ((artifactory-server)) - ARTIFACTORY_USERNAME: ((artifactory-username)) - ARTIFACTORY_PASSWORD: ((artifactory-password)) - build-project-task-params: &build-project-task-params - privileged: true - timeout: ((task-timeout)) - file: git-repo/ci/tasks/build-project.yml - params: - BRANCH: ((branch)) - <<: *gradle-enterprise-task-params - <<: *docker-hub-task-params - artifactory-repo-put-params: &artifactory-repo-put-params - signing_key: ((signing-key)) - signing_passphrase: ((signing-passphrase)) - repo: libs-snapshot-local - folder: distribution-repository - build_uri: "https://ci.spring.io/teams/${BUILD_TEAM_NAME}/pipelines/${BUILD_PIPELINE_NAME}/jobs/${BUILD_JOB_NAME}/builds/${BUILD_NAME}" - build_number: "${BUILD_PIPELINE_NAME}-${BUILD_JOB_NAME}-${BUILD_NAME}" - disable_checksum_uploads: true - threads: 8 - artifact_set: - - include: - - "/**/spring-restdocs-*.zip" - properties: - "zip.type": "docs" - "zip.deployed": "false" - slack-fail-params: &slack-fail-params - text: > - :concourse-failed: - [$TEXT_FILE_CONTENT] - text_file: git-repo/build/build-scan-uri.txt - silent: true - icon_emoji: ":concourse:" - username: concourse-ci - slack-success-params: &slack-success-params - text: > - :concourse-succeeded: - [$TEXT_FILE_CONTENT] - text_file: git-repo/build/build-scan-uri.txt - silent: true - icon_emoji: ":concourse:" - username: concourse-ci - registry-mirror-vars: ®istry-mirror-vars - registry-mirror-host: ((registry-mirror-host)) - registry-mirror-username: ((registry-mirror-username)) - registry-mirror-password: ((registry-mirror-password)) -resource_types: -- name: artifactory-resource - type: registry-image - source: - <<: *registry-image-resource-source - repository: springio/artifactory-resource - tag: 0.0.17 -- name: github-status-resource - type: registry-image - source: - <<: *registry-image-resource-source - repository: dpb587/github-status-resource - tag: master -- name: slack-notification - type: registry-image - source: - <<: *registry-image-resource-source - repository: cfcommunity/slack-notification-resource - tag: latest -- name: github-release - type: registry-image - source: - <<: *registry-image-resource-source - repository: concourse/github-release-resource - tag: 1.7.2 -resources: -- name: git-repo - type: git - icon: github - source: - <<: *git-repo-resource-source -- name: git-repo-windows - type: git - icon: github - source: - <<: *git-repo-resource-source - git_config: - - name: core.autocrlf - value: true -- name: github-pre-release - type: github-release - icon: briefcase-download-outline - source: - owner: ((github-organization)) - repository: ((github-repository)) - access_token: ((github-ci-release-token)) - pre_release: true - release: false -- name: github-release - type: github-release - icon: briefcase-download - source: - owner: ((github-organization)) - repository: ((github-repository)) - access_token: ((github-ci-release-token)) - pre_release: false -- name: ci-images-git-repo - type: git - icon: github - source: - uri: https://github.com/((github-organization))/((github-repository)).git - branch: ((branch)) - paths: ["ci/images/*"] -- name: ci-image - type: registry-image - icon: docker - source: - <<: *registry-image-resource-source - repository: ((docker-hub-organization))/((github-repository))-ci -- name: artifactory-repo - type: artifactory-resource - icon: package-variant - source: - uri: ((artifactory-server)) - username: ((artifactory-username)) - password: ((artifactory-password)) - build_name: ((build-name)) -- name: repo-status-build - type: github-status-resource - icon: eye-check-outline - source: - repository: ((github-organization))/((github-repository)) - access_token: ((github-ci-status-token)) - branch: ((branch)) - context: build -- name: slack-alert - type: slack-notification - icon: slack - source: - url: ((slack-webhook-url)) -- name: daily - type: time - icon: clock-outline - source: { interval: "24h" } -jobs: -- name: build-ci-images - plan: - - get: ci-images-git-repo - trigger: true - - get: git-repo - - task: build-ci-image - privileged: true - file: git-repo/ci/tasks/build-ci-image.yml - output_mapping: - image: ci-image - vars: - ci-image-name: ci-image - <<: *registry-mirror-vars - - put: ci-image - params: - image: ci-image/image.tar -- name: build - serial: true - public: true - plan: - - get: ci-image - - get: git-repo - trigger: true - - put: repo-status-build - params: { state: "pending", commit: "git-repo" } - - do: - - task: build-project - image: ci-image - <<: *build-project-task-params - on_failure: - do: - - put: repo-status-build - params: { state: "failure", commit: "git-repo" } - - put: slack-alert - params: - <<: *slack-fail-params - - put: repo-status-build - params: { state: "success", commit: "git-repo" } - - put: artifactory-repo - params: - <<: *artifactory-repo-put-params - get_params: - threads: 8 - on_failure: - do: - - put: slack-alert - params: - <<: *slack-fail-params - - put: slack-alert - params: - <<: *slack-success-params -- name: windows-build - serial: true - plan: - - get: git-repo - resource: git-repo-windows - - get: daily - trigger: true - - do: - - task: build-project - privileged: true - file: git-repo/ci/tasks/build-project-windows.yml - tags: - - WIN64 - timeout: ((task-timeout)) - params: - BRANCH: ((branch)) - <<: *gradle-enterprise-task-params - on_failure: - do: - - put: slack-alert - params: - <<: *slack-fail-params - - put: slack-alert - params: - <<: *slack-success-params -- name: stage-milestone - serial: true - plan: - - get: ci-image - - get: git-repo - trigger: false - - task: stage - image: ci-image - file: git-repo/ci/tasks/stage.yml - params: - RELEASE_TYPE: M - <<: *gradle-enterprise-task-params - <<: *docker-hub-task-params - - put: artifactory-repo - params: - <<: *artifactory-repo-put-params - repo: libs-staging-local - - put: git-repo - params: - repository: stage-git-repo -- name: stage-rc - serial: true - plan: - - get: ci-image - - get: git-repo - trigger: false - - task: stage - image: ci-image - file: git-repo/ci/tasks/stage.yml - params: - RELEASE_TYPE: RC - <<: *gradle-enterprise-task-params - <<: *docker-hub-task-params - - put: artifactory-repo - params: - <<: *artifactory-repo-put-params - repo: libs-staging-local - - put: git-repo - params: - repository: stage-git-repo -- name: stage-release - serial: true - plan: - - get: ci-image - - get: git-repo - trigger: false - - task: stage - image: ci-image - file: git-repo/ci/tasks/stage.yml - params: - RELEASE_TYPE: RELEASE - <<: *gradle-enterprise-task-params - <<: *docker-hub-task-params - - put: artifactory-repo - params: - <<: *artifactory-repo-put-params - repo: libs-staging-local - - put: git-repo - params: - repository: stage-git-repo -- name: promote-milestone - serial: true - plan: - - get: git-repo - trigger: false - - get: artifactory-repo - trigger: false - passed: [stage-milestone] - params: - download_artifacts: false - save_build_info: true - - task: promote - file: git-repo/ci/tasks/promote.yml - params: - RELEASE_TYPE: M - <<: *artifactory-task-params - - task: generate-changelog - file: git-repo/ci/tasks/generate-changelog.yml - params: - RELEASE_TYPE: M - GITHUB_USERNAME: ((github-username)) - GITHUB_TOKEN: ((github-ci-release-token)) - - put: github-pre-release - params: - name: generated-changelog/tag - tag: generated-changelog/tag - body: generated-changelog/changelog.md -- name: promote-rc - serial: true - plan: - - get: git-repo - trigger: false - - get: artifactory-repo - trigger: false - passed: [stage-rc] - params: - download_artifacts: false - save_build_info: true - - task: promote - file: git-repo/ci/tasks/promote.yml - params: - RELEASE_TYPE: RC - <<: *artifactory-task-params - - task: generate-changelog - file: git-repo/ci/tasks/generate-changelog.yml - params: - RELEASE_TYPE: RC - GITHUB_USERNAME: ((github-username)) - GITHUB_TOKEN: ((github-ci-release-token)) - - put: github-pre-release - params: - name: generated-changelog/tag - tag: generated-changelog/tag - body: generated-changelog/changelog.md -- name: promote-release - serial: true - plan: - - get: git-repo - trigger: false - - get: artifactory-repo - trigger: false - passed: [stage-release] - params: - download_artifacts: true - save_build_info: true - - task: promote - file: git-repo/ci/tasks/promote.yml - params: - RELEASE_TYPE: RELEASE - <<: *artifactory-task-params - <<: *sonatype-task-params -- name: create-github-release - serial: true - plan: - - get: ci-image - - get: git-repo - - get: artifactory-repo - trigger: true - passed: [promote-release] - params: - download_artifacts: false - save_build_info: true - - task: generate-changelog - file: git-repo/ci/tasks/generate-changelog.yml - params: - RELEASE_TYPE: RELEASE - GITHUB_USERNAME: ((github-username)) - GITHUB_TOKEN: ((github-ci-release-token)) - vars: - <<: *registry-mirror-vars - - put: github-release - params: - name: generated-changelog/tag - tag: generated-changelog/tag - body: generated-changelog/changelog.md -groups: -- name: "builds" - jobs: ["build", "windows-build"] -- name: "releases" - jobs: ["stage-milestone", "stage-rc", "stage-release", "promote-milestone", "promote-rc", "promote-release", "create-github-release"] -- name: "ci-images" - jobs: ["build-ci-images"] diff --git a/ci/scripts/build-project-windows.bat b/ci/scripts/build-project-windows.bat deleted file mode 100755 index 297740fa3..000000000 --- a/ci/scripts/build-project-windows.bat +++ /dev/null @@ -1,4 +0,0 @@ -SET "JAVA_HOME=C:\opt\jdk-8" -SET PATH=%PATH%;C:\Program Files\Git\usr\bin -cd git-repo -.\gradlew -Dorg.gradle.internal.launcher.welcomeMessageEnabled=false --no-daemon --max-workers=4 build buildSamples diff --git a/ci/scripts/build-project.sh b/ci/scripts/build-project.sh deleted file mode 100755 index d0ae3118b..000000000 --- a/ci/scripts/build-project.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -set -e - -source $(dirname $0)/common.sh -repository=$(pwd)/distribution-repository - -pushd git-repo > /dev/null -./gradlew -Dorg.gradle.internal.launcher.welcomeMessageEnabled=false --no-daemon --max-workers=4 -PdeploymentRepository=${repository} build buildSamples publishAllPublicationsToDeploymentRepository -popd > /dev/null diff --git a/ci/scripts/common.sh b/ci/scripts/common.sh deleted file mode 100644 index 85bd12338..000000000 --- a/ci/scripts/common.sh +++ /dev/null @@ -1,4 +0,0 @@ -source /opt/concourse-java.sh - -setup_symlinks -cleanup_maven_repo "org.springframework.restdocs" diff --git a/ci/scripts/generate-changelog.sh b/ci/scripts/generate-changelog.sh deleted file mode 100755 index d3d2b97e5..000000000 --- a/ci/scripts/generate-changelog.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -set -e - -CONFIG_DIR=git-repo/ci/config -version=$( cat artifactory-repo/build-info.json | jq -r '.buildInfo.modules[0].id' | sed 's/.*:.*:\(.*\)/\1/' ) - -java -jar /github-changelog-generator.jar \ - --spring.config.location=${CONFIG_DIR}/changelog-generator.yml \ - ${version} generated-changelog/changelog.md - -echo ${version} > generated-changelog/version -echo v${version} > generated-changelog/tag diff --git a/ci/scripts/promote.sh b/ci/scripts/promote.sh deleted file mode 100755 index bd1600191..000000000 --- a/ci/scripts/promote.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash - -CONFIG_DIR=git-repo/ci/config - -version=$( cat artifactory-repo/build-info.json | jq -r '.buildInfo.modules[0].id' | sed 's/.*:.*:\(.*\)/\1/' ) -export BUILD_INFO_LOCATION=$(pwd)/artifactory-repo/build-info.json - -java -jar /concourse-release-scripts.jar \ - --spring.config.location=${CONFIG_DIR}/release-scripts.yml \ - publishToCentral $RELEASE_TYPE $BUILD_INFO_LOCATION artifactory-repo || { exit 1; } - -java -jar /concourse-release-scripts.jar \ - --spring.config.location=${CONFIG_DIR}/release-scripts.yml \ - promote $RELEASE_TYPE $BUILD_INFO_LOCATION || { exit 1; } - -echo "Promotion complete" -echo $version > version/version diff --git a/ci/scripts/stage.sh b/ci/scripts/stage.sh deleted file mode 100755 index 6126c5424..000000000 --- a/ci/scripts/stage.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash -set -e - -source $(dirname $0)/common.sh -repository=$(pwd)/distribution-repository - -pushd git-repo > /dev/null -git fetch --tags --all > /dev/null -popd > /dev/null - -git clone git-repo stage-git-repo > /dev/null - -pushd stage-git-repo > /dev/null - -snapshotVersion=$( awk -F '=' '$1 == "version" { print $2 }' gradle.properties ) -if [[ $RELEASE_TYPE = "M" ]]; then - stageVersion=$( get_next_milestone_release $snapshotVersion) - nextVersion=$snapshotVersion -elif [[ $RELEASE_TYPE = "RC" ]]; then - stageVersion=$( get_next_rc_release $snapshotVersion) - nextVersion=$snapshotVersion -elif [[ $RELEASE_TYPE = "RELEASE" ]]; then - stageVersion=$( get_next_release $snapshotVersion "RELEASE") - nextVersion=$( bump_version_number $snapshotVersion) -else - echo "Unknown release type $RELEASE_TYPE" >&2; exit 1; -fi - -echo "Staging $stageVersion (next version will be $nextVersion)" -sed -i "s/version=$snapshotVersion/version=$stageVersion/" gradle.properties - -git config user.name "Spring Builds" > /dev/null -git config user.email "spring-builds@users.noreply.github.com" > /dev/null -git add gradle.properties > /dev/null -git commit -m"Release v$stageVersion" > /dev/null -git tag -a "v$stageVersion" -m"Release v$stageVersion" > /dev/null - -./gradlew --no-daemon --max-workers=4 -PdeploymentRepository=${repository} build buildSamples publishAllPublicationsToDeploymentRepository - -git reset --hard HEAD^ > /dev/null -if [[ $nextVersion != $snapshotVersion ]]; then - echo "Setting next development version (v$nextVersion)" - sed -i "s/version=$snapshotVersion/version=$nextVersion/" gradle.properties - git add gradle.properties > /dev/null - git commit -m"Next development version (v$nextVersion)" > /dev/null -fi - -echo "DONE" - -popd > /dev/null diff --git a/ci/tasks/build-ci-image.yml b/ci/tasks/build-ci-image.yml deleted file mode 100644 index 4d588c31c..000000000 --- a/ci/tasks/build-ci-image.yml +++ /dev/null @@ -1,31 +0,0 @@ ---- -platform: linux -image_resource: - type: registry-image - source: - repository: concourse/oci-build-task - tag: 0.9.0 - registry_mirror: - host: ((registry-mirror-host)) - username: ((registry-mirror-username)) - password: ((registry-mirror-password)) -inputs: -- name: ci-images-git-repo -outputs: -- name: image -caches: -- path: ci-image-cache -params: - CONTEXT: ci-images-git-repo/ci/images - DOCKERFILE: ci-images-git-repo/ci/images/((ci-image-name))/Dockerfile - DOCKER_HUB_AUTH: ((docker-hub-auth)) -run: - path: /bin/sh - args: - - "-c" - - | - mkdir -p /root/.docker - cat > /root/.docker/config.json < - diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 3de6d5ac3..612ebd174 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -5,7 +5,8 @@ - + diff --git a/docs/build.gradle b/docs/build.gradle index 828afaa94..fefe9a5fa 100644 --- a/docs/build.gradle +++ b/docs/build.gradle @@ -1,5 +1,5 @@ plugins { - id "org.asciidoctor.jvm.convert" version "3.2.0" + id "org.asciidoctor.jvm.convert" version "4.0.4" id "java-library" } @@ -8,16 +8,16 @@ configurations { } dependencies { - asciidoctorExt("io.spring.asciidoctor:spring-asciidoctor-extensions-block-switch:0.6.1") + asciidoctorExt("io.spring.asciidoctor.backends:spring-asciidoctor-backends:0.0.5") internal(platform(project(":spring-restdocs-platform"))) - internal(enforcedPlatform("org.springframework:spring-framework-bom:5.3.8")) + internal(enforcedPlatform("org.springframework:spring-framework-bom:$springFrameworkVersion")) testImplementation(project(":spring-restdocs-mockmvc")) testImplementation(project(":spring-restdocs-restassured")) testImplementation(project(":spring-restdocs-webtestclient")) - testImplementation("javax.validation:validation-api") - testImplementation("junit:junit") + testImplementation("jakarta.servlet:jakarta.servlet-api") + testImplementation("jakarta.validation:jakarta.validation-api") testImplementation("org.testng:testng:6.9.10") testImplementation("org.junit.jupiter:junit-jupiter-api") } @@ -42,6 +42,10 @@ asciidoctor { include "index.adoc" } attributes "revnumber": project.version, + "spring-Framework-version": springFrameworkVersion, "branch-or-tag": project.version.endsWith("SNAPSHOT") ? "main": "v${project.version}" inputs.files(sourceSets.test.java) + outputOptions { + backends "spring-html" + } } diff --git a/docs/src/docs/asciidoc/configuration.adoc b/docs/src/docs/asciidoc/configuration.adoc index 772f03590..24c23a47e 100644 --- a/docs/src/docs/asciidoc/configuration.adoc +++ b/docs/src/docs/asciidoc/configuration.adoc @@ -48,9 +48,11 @@ TIP: To configure a request's context path, use the `contextPath` method on `Moc [[configuration-uris-rest-assured]] ==== REST Assured URI Customization -REST Assured tests a service by making actual HTTP requests. -As a result, URIs must be customized once the operation on the service has been performed but before it is documented. -A <> is provided for this purpose. +REST Assured tests a service by making actual HTTP requests. As a result, URIs must be +customized once the operation on the service has been performed but before it is +documented. A +<> is provided for this purpose. diff --git a/docs/src/docs/asciidoc/customizing-requests-and-responses.adoc b/docs/src/docs/asciidoc/customizing-requests-and-responses.adoc index 3d34e18a8..b51512697 100644 --- a/docs/src/docs/asciidoc/customizing-requests-and-responses.adoc +++ b/docs/src/docs/asciidoc/customizing-requests-and-responses.adoc @@ -108,12 +108,10 @@ You can also specify a different replacement if you wish. -[[customizing-requests-and-responses-preprocessors-remove-headers]] -==== Removing Headers +[[customizing-requests-and-responses-preprocessors-modify-headers]] +==== Modifying Headers -`removeHeaders` on `Preprocessors` removes any headers from the request or response where the name is equal to any of the given header names. - -`removeMatchingHeaders` on `Preprocessors` removes any headers from the request or response where the name matches any of the given regular expression patterns. +You can use `modifyHeaders` on `Preprocessors` to add, set, and remove request or response headers. @@ -125,13 +123,6 @@ Any occurrences that match a regular expression are replaced. -[[customizing-requests-and-responses-preprocessors-modify-request-parameters]] -==== Modifying Request Parameters - -You can use `modifyParameters` on `Preprocessors` to add, set, and remove request parameters. - - - [[customizing-requests-and-responses-preprocessors-modify-uris]] ==== Modifying URIs diff --git a/docs/src/docs/asciidoc/documenting-your-api.adoc b/docs/src/docs/asciidoc/documenting-your-api.adoc index 43b95aa13..cb9ce82a3 100644 --- a/docs/src/docs/asciidoc/documenting-your-api.adoc +++ b/docs/src/docs/asciidoc/documenting-your-api.adoc @@ -39,9 +39,10 @@ Uses the static `linkWithRel` method on `org.springframework.restdocs.hypermedia include::{examples-dir}/com/example/restassured/Hypermedia.java[tag=links] ---- <1> Configure Spring REST docs to produce a snippet describing the response's links. -Uses the static `links` method on `org.springframework.restdocs.hypermedia.HypermediaDocumentation`. -<2> Expect a link whose `rel` is `alpha`. -Uses the static `linkWithRel` method on `org.springframework.restdocs.hypermedia.HypermediaDocumentation`. + Uses the static `links` method on + `org.springframework.restdocs.hypermedia.HypermediaDocumentation`. +<2> Expect a link whose `rel` is `alpha`. Uses the static `linkWithRel` method on + `org.springframework.restdocs.hypermedia.HypermediaDocumentation`. <3> Expect a link whose `rel` is `bravo`. The result is a snippet named `links.adoc` that contains a table describing the resource's links. @@ -95,8 +96,8 @@ Uses the static `halLinks` method on `org.springframework.restdocs.hypermedia.Hy ---- include::{examples-dir}/com/example/restassured/Hypermedia.java[tag=explicit-extractor] ---- -<1> Indicate that the links are in HAL format. -Uses the static `halLinks` method on `org.springframework.restdocs.hypermedia.HypermediaDocumentation`. +<1> Indicate that the links are in HAL format. Uses the static `halLinks` method on +`org.springframework.restdocs.hypermedia.HypermediaDocumentation`. If your API represents its links in a format other than Atom or HAL, you can provide your own implementation of the `LinkExtractor` interface to extract the links from the response. @@ -178,7 +179,7 @@ include::{examples-dir}/com/example/restassured/Payload.java[tags=response] To document a request, you can use `requestFields`. Both are static methods on `org.springframework.restdocs.payload.PayloadDocumentation`. <2> Expect a field with the path `contact.email`. -Uses the static `fieldWithPath` method on `org.springframework.restdocs.payload.PayloadDocumentation`. +Uses the static `fieldWithPath` method on `org.springframework.restdocs.payload.PayloadDocumentation`. <3> Expect a field with the path `contact.name`. The result is a snippet that contains a table describing the fields. @@ -214,8 +215,7 @@ Uses the static `subsectionWithPath` method on `org.springframework.restdocs.pay ---- include::{examples-dir}/com/example/restassured/Payload.java[tags=subsection] ---- -<1> Document the subsection with the path `contact`. -`contact.email` and `contact.name` are now seen as having also been documented. +<1> Document the subsection with the path `contact`. `contact.email` and `contact.name` are now seen as having also been documented. Uses the static `subsectionWithPath` method on `org.springframework.restdocs.payload.PayloadDocumentation`. `subsectionWithPath` can be useful for providing a high-level overview of a particular section of a payload. @@ -344,6 +344,8 @@ For example, `users.*.role` could be used to document the role of every user in } ---- + + [[documenting-your-api-request-response-payloads-fields-json-field-types]] ====== JSON Field Types @@ -510,6 +512,8 @@ include::{examples-dir}/com/example/webtestclient/Payload.java[tags=book-array] <1> Document the array. <2> Document `[].title` and `[].author` by using the existing descriptors prefixed with `[].` + + [source,java,indent=0,role="secondary"] .REST Assured ---- @@ -633,8 +637,9 @@ Uses the static `beneathPath` method on `org.springframework.restdocs.payload.Pa ---- include::{examples-dir}/com/example/restassured/Payload.java[tags=fields-subsection] ---- -<1> Produce a snippet describing the fields in the subsection of the response payload beneath the path `weather.temperature`. -Uses the static `beneathPath` method on `org.springframework.restdocs.payload.PayloadDocumentation`. +<1> Produce a snippet describing the fields in the subsection of the response payload + beneath the path `weather.temperature`. Uses the static `beneathPath` method on + `org.springframework.restdocs.payload.PayloadDocumentation`. <2> Document the `high` and `low` fields. The result is a snippet that contains a table describing the `high` and `low` fields of `weather.temperature`. @@ -644,33 +649,34 @@ For example, the preceding code results in a snippet named `response-fields-bene -[[documenting-your-api-request-parameters]] -=== Request Parameters +[[documenting-your-api-query-parameters]] +=== Query Parameters -You can document a request's parameters by using `requestParameters`. -You can include request parameters in a `GET` request's query string. +You can document a request's query parameters by using `queryParameters`. The following examples show how to do so: [source,java,indent=0,role="primary"] .MockMvc ---- -include::{examples-dir}/com/example/mockmvc/RequestParameters.java[tags=request-parameters-query-string] +include::{examples-dir}/com/example/mockmvc/QueryParameters.java[tags=query-parameters] ---- <1> Perform a `GET` request with two parameters, `page` and `per_page`, in the query string. -<2> Configure Spring REST Docs to produce a snippet describing the request's parameters. -Uses the static `requestParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. -<3> Document the `page` parameter. +Query parameters should be included in the URL, as shown here, or specified using the request builder's `queryParam` or `queryParams` method. +The `param` and `params` methods should be avoided as the source of the parameters is then ambiguous. +<2> Configure Spring REST Docs to produce a snippet describing the request's query parameters. +Uses the static `queryParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +<3> Document the `page` query parameter. Uses the static `parameterWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. -<4> Document the `per_page` parameter. +<4> Document the `per_page` query parameter. [source,java,indent=0,role="secondary"] .WebTestClient ---- -include::{examples-dir}/com/example/webtestclient/RequestParameters.java[tags=request-parameters-query-string] +include::{examples-dir}/com/example/webtestclient/QueryParameters.java[tags=query-parameters] ---- <1> Perform a `GET` request with two parameters, `page` and `per_page`, in the query string. -<2> Configure Spring REST Docs to produce a snippet describing the request's parameters. -Uses the static `requestParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +<2> Configure Spring REST Docs to produce a snippet describing the request's query parameters. +Uses the static `queryParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. <3> Document the `page` parameter. Uses the static `parameterWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. <4> Document the `per_page` parameter. @@ -678,51 +684,77 @@ Uses the static `parameterWithName` method on `org.springframework.restdocs.requ [source,java,indent=0,role="secondary"] .REST Assured ---- -include::{examples-dir}/com/example/restassured/RequestParameters.java[tags=request-parameters-query-string] +include::{examples-dir}/com/example/restassured/QueryParameters.java[tags=query-parameters] ---- -<1> Configure Spring REST Docs to produce a snippet describing the request's parameters. -Uses the static `requestParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +<1> Configure Spring REST Docs to produce a snippet describing the request's query parameters. +Uses the static `queryParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. <2> Document the `page` parameter. Uses the static `parameterWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. <3> Document the `per_page` parameter. <4> Perform a `GET` request with two parameters, `page` and `per_page`, in the query string. -You can also include request parameters as form data in the body of a POST request. +When documenting query parameters, the test fails if an undocumented query parameter is used in the request's query string. +Similarly, the test also fails if a documented query parameter is not found in the request's query string and the parameter has not been marked as optional. + +If you do not want to document a query parameter, you can mark it as ignored. +This prevents it from appearing in the generated snippet while avoiding the failure described above. + +You can also document query parameters in a relaxed mode where any undocumented parameters do not cause a test failure. +To do so, use the `relaxedQueryParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +This can be useful when documenting a particular scenario where you only want to focus on a subset of the query parameters. + + + +[[documenting-your-api-form-parameters]] +=== Form Parameters + +You can document a request's form parameters by using `formParameters`. The following examples show how to do so: [source,java,indent=0,role="primary"] .MockMvc ---- -include::{examples-dir}/com/example/mockmvc/RequestParameters.java[tags=request-parameters-form-data] +include::{examples-dir}/com/example/mockmvc/FormParameters.java[tags=form-parameters] ---- -<1> Perform a `POST` request with a single parameter, `username`. +<1> Perform a `POST` request with a single form parameter, `username`. +<2> Configure Spring REST Docs to produce a snippet describing the request's form parameters. +Uses the static `formParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +<3> Document the `username` parameter. +Uses the static `parameterWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. [source,java,indent=0,role="secondary"] .WebTestClient ---- -include::{examples-dir}/com/example/webtestclient/RequestParameters.java[tags=request-parameters-form-data] +include::{examples-dir}/com/example/webtestclient/FormParameters.java[tags=form-parameters] ---- -<1> Perform a `POST` request with a single parameter, `username`. +<1> Perform a `POST` request with a single form parameter, `username`. +<2> Configure Spring REST Docs to produce a snippet describing the request's form parameters. +Uses the static `formParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +<3> Document the `username` parameter. +Uses the static `parameterWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. [source,java,indent=0,role="secondary"] .REST Assured ---- -include::{examples-dir}/com/example/restassured/RequestParameters.java[tags=request-parameters-form-data] +include::{examples-dir}/com/example/restassured/FormParameters.java[tags=form-parameters] ---- -<1> Configure the `username` parameter. -<2> Perform the `POST` request. +<1> Configure Spring REST Docs to produce a snippet describing the request's form parameters. +Uses the static `formParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +<2> Document the `username` parameter. +Uses the static `parameterWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. +<3> Perform a `POST` request with a single form parameter, `username`. -In all cases, the result is a snippet named `request-parameters.adoc` that contains a table describing the parameters that are supported by the resource. +In all cases, the result is a snippet named `form-parameters.adoc` that contains a table describing the form parameters that are supported by the resource. -When documenting request parameters, the test fails if an undocumented request parameter is used in the request. -Similarly, the test also fails if a documented request parameter is not found in the request and the request parameter has not been marked as optional. +When documenting form parameters, the test fails if an undocumented form parameter is used in the request body. +Similarly, the test also fails if a documented form parameter is not found in the request body and the form parameter has not been marked as optional. -If you do not want to document a request parameter, you can mark it as ignored. +If you do not want to document a form parameter, you can mark it as ignored. This prevents it from appearing in the generated snippet while avoiding the failure described above. -You can also document request parameters in a relaxed mode where any undocumented parameters do not cause a test failure. -To do so, use the `relaxedRequestParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. -This can be useful when documenting a particular scenario where you only want to focus on a subset of the request parameters. +You can also document form parameters in a relaxed mode where any undocumented parameters do not cause a test failure. +To do so, use the `relaxedFormParameters` method on `org.springframework.restdocs.request.RequestDocumentation`. +This can be useful when documenting a particular scenario where you only want to focus on a subset of the form parameters. @@ -770,8 +802,6 @@ Uses the static `parameterWithName` method on `org.springframework.restdocs.requ The result is a snippet named `path-parameters.adoc` that contains a table describing the path parameters that are supported by the resource. -TIP: If you use MockMvc, to make the path parameters available for documentation, you must build the request by using one of the methods on `RestDocumentationRequestBuilders` rather than `MockMvcRequestBuilders`. - When documenting path parameters, the test fails if an undocumented path parameter is used in the request. Similarly, the test also fails if a documented path parameter is not found in the request and the path parameter has not been marked as optional. @@ -819,8 +849,7 @@ include::{examples-dir}/com/example/restassured/RequestParts.java[tags=request-p ---- <1> Configure Spring REST Docs to produce a snippet describing the request's parts. Uses the static `requestParts` method on `org.springframework.restdocs.request.RequestDocumentation`. -<2> Document the part named `file`. -Uses the static `partWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. +<2> Document the part named `file`. Uses the static `partWithName` method on `org.springframework.restdocs.request.RequestDocumentation`. <3> Configure the request with the part named `file`. <4> Perform the `POST` request to `/upload`. @@ -985,6 +1014,64 @@ When documenting HTTP Headers, the test fails if a documented header is not foun +[[documenting-your-api-http-cookies]] +=== HTTP Cookies + +You can document the cookies in a request or response by using `requestCookies` and `responseCookies`, respectively. +The following examples show how to do so: + +[source,java,indent=0,role="primary"] +.MockMvc +---- +include::{examples-dir}/com/example/mockmvc/HttpCookies.java[tags=cookies] +---- +<1> Make a GET request with a `JSESSIONID` cookie. +<2> Configure Spring REST Docs to produce a snippet describing the request's cookies. + Uses the static `requestCookies` method on `org.springframework.restdocs.cookies.CookieDocumentation`. +<3> Document the `JSESSIONID` cookie. Uses the static `cookieWithName` method on `org.springframework.restdocs.cookies.CookieDocumentation`. +<4> Produce a snippet describing the response's cookies. + Uses the static `responseCookies` method on `org.springframework.restdocs.cookies.CookieDocumentation`. + +[source,java,indent=0,role="secondary"] +.WebTestClient +---- +include::{examples-dir}/com/example/webtestclient/HttpCookies.java[tags=cookies] +---- +<1> Make a GET request with a `JSESSIONID` cookie. +<2> Configure Spring REST Docs to produce a snippet describing the request's cookies. + Uses the static `requestCookies` method on + `org.springframework.restdocs.cookies.CookieDocumentation`. +<3> Document the `JSESSIONID` cookie. + Uses the static `cookieWithName` method on `org.springframework.restdocs.cookies.CookieDocumentation`. +<4> Produce a snippet describing the response's cookies. + Uses the static `responseCookies` method on `org.springframework.restdocs.cookies.CookieDocumentation`. + +[source,java,indent=0,role="secondary"] +.REST Assured +---- +include::{examples-dir}/com/example/restassured/HttpCookies.java[tags=cookies] +---- +<1> Configure Spring REST Docs to produce a snippet describing the request's cookies. + Uses the static `requestCookies` method on `org.springframework.restdocs.cookies.CookieDocumentation`. +<2> Document the `JSESSIONID` cookie. + Uses the static `cookieWithName` method on `org.springframework.restdocs.cookies.CookieDocumentation`. +<3> Produce a snippet describing the response's cookies. + Uses the static `responseCookies` method on `org.springframework.restdocs.cookies.CookieDocumentation`. +<4> Send a `JSESSIONID` cookie with the request. + +The result is a snippet named `request-cookies.adoc` and a snippet named `response-cookies.adoc`. +Each contains a table describing the cookies. + +When documenting HTTP cookies, the test fails if an undocumented cookie is found in the request or response. +Similarly, the test also fails if a documented cookie is not found and the cookie has not been marked as optional. +You can also document cookies in a relaxed mode, where any undocumented cookies do not cause a test failure. +To do so, use the `relaxedRequestCookies` and `relaxedResponseCookies` methods on `org.springframework.restdocs.cookies.CookieDocumentation`. +This can be useful when documenting a particular scenario where you only want to focus on a subset of the cookies. +If you do not want to document a cookie, you can mark it as ignored. +Doing so prevents it from appearing in the generated snippet while avoiding the failure described earlier. + + + [[documenting-your-api-reusing-snippets]] === Reusing Snippets @@ -1042,7 +1129,7 @@ include::{examples-dir}/com/example/Constraints.java[tags=constraints] <2> Get the descriptions of the `name` property's constraints. This list contains two descriptions: one for the `NotNull` constraint and one for the `Size` constraint. -The {samples}/rest-notes-spring-hateoas/src/test/java/com/example/notes/ApiDocumentation.java[`ApiDocumentation`] class in the Spring HATEOAS sample shows this functionality in action. +The {samples}/restful-notes-spring-hateoas/src/test/java/com/example/notes/ApiDocumentation.java[`ApiDocumentation`] class in the Spring HATEOAS sample shows this functionality in action. @@ -1059,7 +1146,7 @@ To take complete control of constraint resolution, you can use your own implemen [[documenting-your-api-constraints-describing]] ==== Describing Constraints -Default descriptions are provided for all of Bean Validation 2.0's constraints: +Default descriptions are provided for all of Bean Validation 3.1's constraints: * `AssertFalse` * `AssertTrue` @@ -1104,10 +1191,10 @@ Validator: * `URL` To override the default descriptions or to provide a new description, you can create a resource bundle with a base name of `org.springframework.restdocs.constraints.ConstraintDescriptions`. -The Spring HATEOAS-based sample contains {samples}/rest-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/constraints/ConstraintDescriptions.properties[an example of such a resource bundle]. +The Spring HATEOAS-based sample contains {samples}/restful-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/constraints/ConstraintDescriptions.properties[an example of such a resource bundle]. Each key in the resource bundle is the fully-qualified name of a constraint plus a `.description`. -For example, the key for the standard `@NotNull` constraint is `javax.validation.constraints.NotNull.description`. +For example, the key for the standard `@NotNull` constraint is `jakarta.validation.constraints.NotNull.description`. You can use a property placeholder referring to a constraint's attributes in its description. For example, the default description of the `@Min` constraint, `Must be at least ${value}`, refers to the constraint's `value` attribute. @@ -1122,7 +1209,7 @@ To take complete control, you can create `ConstraintDescriptions` with a custom Once you have a constraint's descriptions, you are free to use them however you like in the generated snippets. For example, you may want to include the constraint descriptions as part of a field's description. Alternatively, you could include the constraints as <> in the request fields snippet. -The {samples}/rest-notes-spring-hateoas/src/test/java/com/example/notes/ApiDocumentation.java[`ApiDocumentation`] class in the Spring HATEOAS-based sample illustrates the latter approach. +The {samples}/restful-notes-spring-hateoas/src/test/java/com/example/notes/ApiDocumentation.java[`ApiDocumentation`] class in the Spring HATEOAS-based sample illustrates the latter approach. @@ -1164,9 +1251,7 @@ See the <> for more information. [[documentating-your-api-parameterized-output-directories]] === Using Parameterized Output Directories -When using MockMvc, REST Assured, or `WebTestClient` you can parameterize the output directory used by `document`. -Parameterizing output with `WebTestClient` requires Spring Framework 5.3.5 or later. - +You can parameterize the output directory used by `document`. The following parameters are supported: [cols="1,3"] @@ -1290,7 +1375,6 @@ include::{examples-dir}/com/example/restassured/Payload.java[tags=constraints] <3> Set the `constraints` attribute for the `email` field. The second step is to provide a custom template named `request-fields.snippet` that includes the information about the fields' constraints in the generated snippet's table and adds a title. -The following example shows how to do so: [source,indent=0] ---- @@ -1312,4 +1396,3 @@ The following example shows how to do so: <3> Include the descriptors' `constraints` attribute in each row of the table. - diff --git a/docs/src/docs/asciidoc/getting-started.adoc b/docs/src/docs/asciidoc/getting-started.adoc index 62a1b3e73..11be6100d 100644 --- a/docs/src/docs/asciidoc/getting-started.adoc +++ b/docs/src/docs/asciidoc/getting-started.adoc @@ -8,62 +8,7 @@ This section describes how to get started with Spring REST Docs. [[getting-started-sample-applications]] === Sample Applications -If you want to jump straight in, a number of sample applications are available: - -[cols="3,2,10"] -.MockMvc -|=== -| Sample | Build system | Description - -| {samples}/rest-notes-spring-data-rest[Spring Data REST] -| Maven -| Demonstrates the creation of a getting started guide and an API guide for a service implemented by using https://projects.spring.io/spring-data-rest/[Spring Data REST]. - -| {samples}/rest-notes-spring-hateoas[Spring HATEOAS] -| Gradle -| Demonstrates the creation of a getting started guide and an API guide for a service implemented by using https://projects.spring.io/spring-hateoas/[Spring HATEOAS]. -|=== - -[cols="3,2,10"] -.WebTestClient -|=== -| Sample | Build system | Description - -| {samples}/web-test-client[WebTestClient] -| Gradle -| Demonstrates the use of Spring REST docs with Spring WebFlux's WebTestClient. -|=== - - -[cols="3,2,10"] -.REST Assured -|=== -| Sample | Build system | Description - -| {samples}/rest-assured[REST Assured] -| Gradle -| Demonstrates the use of Spring REST Docs with https://rest-assured.io/[REST Assured]. -|=== - - -[cols="3,2,10"] -.Advanced -|=== -| Sample | Build system | Description - -| {samples}/rest-notes-slate[Slate] -| Gradle -| Demonstrates the use of Spring REST Docs with Markdown and - https://github.com/tripit/slate[Slate]. - -| {samples}/testng[TestNG] -| Gradle -| Demonstrates the use of Spring REST Docs with http://testng.org[TestNG]. - -| {samples}/junit5[JUnit 5] -| Gradle -| Demonstrates the use of Spring REST Docs with https://junit.org/junit5/[JUnit 5]. -|=== +If you want to jump straight in, a number of https://github.com/spring-projects/spring-restdocs-samples[sample applications are available]. @@ -72,10 +17,10 @@ If you want to jump straight in, a number of sample applications are available: Spring REST Docs has the following minimum requirements: -* Java 8 -* Spring Framework 5 (5.0.2 or later) +* Java 17 +* Spring Framework 7 -Additionally, the `spring-restdocs-restassured` module requires REST Assured 3.0. +Additionally, the `spring-restdocs-restassured` module requires REST Assured 5.2. @@ -83,7 +28,7 @@ Additionally, the `spring-restdocs-restassured` module requires REST Assured 3.0 === Build configuration The first step in using Spring REST Docs is to configure your project's build. -The {samples}/rest-notes-spring-hateoas[Spring HATEOAS] and {samples}/rest-notes-spring-data-rest[Spring Data REST] samples contain a `build.gradle` and `pom.xml`, respectively, that you may wish to use as a reference. +The {samples}/restful-notes-spring-hateoas[Spring HATEOAS] and {samples}/restful-notes-spring-data-rest[Spring Data REST] samples contain a `build.gradle` and `pom.xml`, respectively, that you may wish to use as a reference. The key parts of the configuration are described in the following listings: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] @@ -101,7 +46,7 @@ The key parts of the configuration are described in the following listings: <2> org.asciidoctor asciidoctor-maven-plugin - 1.5.8 + 2.2.1 generate-docs @@ -133,6 +78,7 @@ If you want to use `WebTestClient` or REST Assured rather than MockMvc, add a de <4> Add `spring-restdocs-asciidoctor` as a dependency of the Asciidoctor plugin. This will automatically configure the `snippets` attribute for use in your `.adoc` files to point to `target/generated-snippets`. It will also allow you to use the `operation` block macro. +It requires AsciidoctorJ 3.0. [source,indent=0,subs="verbatim,attributes",role="secondary"] .Gradle @@ -169,6 +115,7 @@ It will also allow you to use the `operation` block macro. <3> Add a dependency on `spring-restdocs-asciidoctor` in the `asciidoctorExt` configuration. This will automatically configure the `snippets` attribute for use in your `.adoc` files to point to `build/generated-snippets`. It will also allow you to use the `operation` block macro. +It requires AsciidoctorJ 3.0. <4> Add a dependency on `spring-restdocs-mockmvc` in the `testImplementation` configuration. If you want to use `WebTestClient` or REST Assured rather than MockMvc, add a dependency on `spring-restdocs-webtestclient` or `spring-restdocs-restassured` respectively instead. <5> Configure a `snippetsDir` property that defines the output location for generated snippets. @@ -201,7 +148,6 @@ The following listings show how to do so in both Maven and Gradle: <2> maven-resources-plugin - 2.7 copy-resources @@ -227,6 +173,7 @@ The following listings show how to do so in both Maven and Gradle: ---- <1> The existing declaration for the Asciidoctor plugin. <2> The resource plugin must be declared after the Asciidoctor plugin as they are bound to the same phase (`prepare-package`) and the resource plugin must run after the Asciidoctor plugin to ensure that the documentation is generated before it's copied. +If you are not using Spring Boot and its plugin management, declare the plugin with an appropriate ``. <3> Copy the generated documentation into the build output's `static/docs` directory, from where it will be included in the jar file. [source,indent=0,role="secondary"] @@ -234,7 +181,7 @@ The following listings show how to do so in both Maven and Gradle: ---- bootJar { dependsOn asciidoctor <1> - from ("${asciidoctor.outputDir}/html5") { <2> + from ("${asciidoctor.outputDir}") { <2> into 'static/docs' } } @@ -256,77 +203,11 @@ It then produces documentation snippets for the request and the resulting respon ==== Setting up Your Tests Exactly how you set up your tests depends on the test framework that you use. -Spring REST Docs provides first-class support for JUnit 4 and JUnit 5. +Spring REST Docs provides first-class support for JUnit 5. Other frameworks, such as TestNG, are also supported, although slightly more setup is required. -[[getting-started-documentation-snippets-setup-junit]] -===== Setting up Your JUnit 4 Tests - -When using JUnit 4, the first step in generating documentation snippets is to declare a `public` `JUnitRestDocumentation` field that is annotated as a JUnit `@Rule`. -The following example shows how to do so: - -[source,java,indent=0] ----- -@Rule -public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); ----- - -By default, the `JUnitRestDocumentation` rule is automatically configured with an output directory based on your project's build tool: - -[cols="2,5"] -|=== -| Build tool | Output directory - -| Maven -| `target/generated-snippets` - -| Gradle -| `build/generated-snippets` -|=== - -You can override the default by providing an output directory when you create the `JUnitRestDocumentation` instance. -The following example shows how to do so: - -[source,java,indent=0] ----- -@Rule -public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("custom"); ----- - -Next, you must provide an `@Before` method to configure MockMvc, WebTestClient or REST Assured. -The following examples show how to do so: - -[source,java,indent=0,role="primary"] -.MockMvc ----- -include::{examples-dir}/com/example/mockmvc/ExampleApplicationTests.java[tags=setup] ----- -<1> The `MockMvc` instance is configured by using a `MockMvcRestDocumentationConfigurer`. -You can obtain an instance of this class from the static `documentationConfiguration()` method on `org.springframework.restdocs.mockmvc.MockMvcRestDocumentation`. - -[source,java,indent=0,role="secondary"] -.WebTestClient ----- -include::{examples-dir}/com/example/webtestclient/ExampleApplicationTests.java[tags=setup] ----- -<1> The `WebTestClient` instance is configured by adding a `WebTestclientRestDocumentationConfigurer` as an `ExchangeFilterFunction`. -You can obtain an instance of this class from the static `documentationConfiguration()` method on `org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation`. - -[source,java,indent=0,role="secondary"] -.REST Assured ----- -include::{examples-dir}/com/example/restassured/ExampleApplicationTests.java[tags=setup] ----- -<1> REST Assured is configured by adding a `RestAssuredRestDocumentationConfigurer` as a `Filter`. -You can obtain an instance of this class from the static `documentationConfiguration()` method on `RestAssuredRestDocumentation` in the `org.springframework.restdocs.restassured3` package. - -The configurer applies sensible defaults and also provides an API for customizing the configuration. -See the <> for more information. - - - [[getting-started-documentation-snippets-setup-junit-5]] ===== Setting up Your JUnit 5 Tests @@ -373,13 +254,13 @@ public class JUnit5ExampleTests { } ---- -Next, you must provide a `@BeforeEach` method to configure MockMvc, WebTestClient, or REST Assured. +Next, you must provide a `@BeforeEach` method to configure MockMvc or WebTestClient, or REST Assured. The following listings show how to do so: [source,java,indent=0,role="primary"] .MockMvc ---- -include::{examples-dir}/com/example/mockmvc/ExampleApplicationJUnit5Tests.java[tags=setup] +include::{examples-dir}/com/example/mockmvc/ExampleApplicationTests.java[tags=setup] ---- <1> The `MockMvc` instance is configured by using a `MockMvcRestDocumentationConfigurer`. You can obtain an instance of this class from the static `documentationConfiguration()` method on `org.springframework.restdocs.mockmvc.MockMvcRestDocumentation`. @@ -387,7 +268,7 @@ You can obtain an instance of this class from the static `documentationConfigura [source,java,indent=0,role="secondary"] .WebTestClient ---- -include::{examples-dir}/com/example/webtestclient/ExampleApplicationJUnit5Tests.java[tags=setup] +include::{examples-dir}/com/example/webtestclient/ExampleApplicationTests.java[tags=setup] ---- <1> The `WebTestClient` instance is configured by adding a `WebTestClientRestDocumentationConfigurer` as an `ExchangeFilterFunction`. You can obtain an instance of this class from the static `documentationConfiguration()` method on `org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation`. @@ -395,26 +276,25 @@ You can obtain an instance of this class from the static `documentationConfigura [source,java,indent=0,role="secondary"] .REST Assured ---- -include::{examples-dir}/com/example/restassured/ExampleApplicationJUnit5Tests.java[tags=setup] +include::{examples-dir}/com/example/restassured/ExampleApplicationTests.java[tags=setup] ---- <1> REST Assured is configured by adding a `RestAssuredRestDocumentationConfigurer` as a `Filter`. -You can obtain an instance of this class from the static `documentationConfiguration()` method on `RestAssuredRestDocumentation` in the `org.springframework.restdocs.restassured3` package. +You can obtain an instance of this class from the static `documentationConfiguration()` method on `RestAssuredRestDocumentation` in the `org.springframework.restdocs.restassured` package. The configurer applies sensible defaults and also provides an API for customizing the configuration. See the <> for more information. + [[getting-started-documentation-snippets-setup-manual]] ===== Setting up your tests without JUnit -The configuration when JUnit is not being used is largely similar to when it is being used. -This section describes the key differences. -The {samples}/testng[TestNG sample] also illustrates the approach. +The configuration when JUnit is not being used is a little more involved as the test class must perform some lifecycle management. +The {samples}/testng[TestNG sample] illustrates the approach. -The first difference is that you should use `ManualRestDocumentation` in place of `JUnitRestDocumentation`. -Also, you do not need the `@Rule` annotation. -The following example shows how to use `ManualRestDocumentation`: +First, you need a `ManualRestDocumentation` field. +The following example shows how to define it: [source,java,indent=0] ---- @@ -448,7 +328,7 @@ The following example shows how to do so with TestNG: [source,java,indent=0] ---- -include::{examples-dir}/com/example/restassured/ExampleApplicationTestNgTests.java[tags=teardown] +include::{examples-dir}/com/example/mockmvc/ExampleApplicationTestNgTests.java[tags=teardown] ---- @@ -490,7 +370,7 @@ include::{examples-dir}/com/example/restassured/InvokeService.java[tags=invoke-s <2> Indicate that an `application/json` response is required. <3> Document the call to the service, writing the snippets into a directory named `index` (which is located beneath the configured output directory). The snippets are written by a `RestDocumentationFilter`. -You can obtain an instance of this class from the static `document` method on `RestAssuredRestDocumentation` in the `org.springframework.restdocs.restassured3` package. +You can obtain an instance of this class from the static `document` method on `RestAssuredRestDocumentation` in the `org.springframework.restdocs.restassured` package. <4> Invoke the root (`/`) of the service. <5> Assert that the service produce the expected response. diff --git a/docs/src/docs/asciidoc/index.adoc b/docs/src/docs/asciidoc/index.adoc index 16f9c9dc5..c231d8728 100644 --- a/docs/src/docs/asciidoc/index.adoc +++ b/docs/src/docs/asciidoc/index.adoc @@ -10,15 +10,15 @@ Andy Wilkinson; Jay Bryant :examples-dir: ../../test/java :github: https://github.com/spring-projects/spring-restdocs :source: {github}/tree/{branch-or-tag} -:samples: {source}/samples +:samples: https://github.com/spring-projects/spring-restdocs-samples/tree/main :templates: {source}spring-restdocs/src/main/resources/org/springframework/restdocs/templates :spring-boot-docs: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle -:spring-framework-docs: https://docs.spring.io/spring-framework/docs/5.0.x/spring-framework-reference -:spring-framework-api: https://docs.spring.io/spring-framework/docs/5.0.x/javadoc-api +:spring-framework-docs: https://docs.spring.io/spring-framework/docs/{spring-framework-version}/reference/html/ +:spring-framework-api: https://docs.spring.io/spring-framework/docs/{spring-framework-version}/javadoc-api [[abstract]] -Document RESTful services by combining hand-written documentation with auto-generated snippets produced with Spring MVC Test, WebTestClient, or REST Assured. +Document RESTful services by combining hand-written documentation with auto-generated snippets produced with Spring MVC Test or WebTestClient. include::introduction.adoc[] include::getting-started.adoc[] diff --git a/docs/src/docs/asciidoc/introduction.adoc b/docs/src/docs/asciidoc/introduction.adoc index 62e66375e..eb40443be 100644 --- a/docs/src/docs/asciidoc/introduction.adoc +++ b/docs/src/docs/asciidoc/introduction.adoc @@ -9,7 +9,7 @@ To this end, Spring REST Docs uses https://asciidoctor.org[Asciidoctor] by defau Asciidoctor processes plain text and produces HTML, styled and laid out to suit your needs. If you prefer, you can also configure Spring REST Docs to use Markdown. -Spring REST Docs uses snippets produced by tests written with Spring MVC's {spring-framework-docs}/testing.html#spring-mvc-test-framework[test framework], Spring WebFlux's {spring-framework-docs}/testing.html#webtestclient[`WebTestClient`] or https://rest-assured.io/[REST Assured 3]. +Spring REST Docs uses snippets produced by tests written with Spring MVC's {spring-framework-docs}/testing.html#spring-mvc-test-framework[test framework], Spring WebFlux's {spring-framework-docs}/testing.html#webtestclient[`WebTestClient`] or https://rest-assured.io/[REST Assured 5]. This test-driven approach helps to guarantee the accuracy of your service's documentation. If a snippet is incorrect, the test that produces it fails. diff --git a/docs/src/docs/asciidoc/working-with-asciidoctor.adoc b/docs/src/docs/asciidoc/working-with-asciidoctor.adoc index 068590384..698d5e460 100644 --- a/docs/src/docs/asciidoc/working-with-asciidoctor.adoc +++ b/docs/src/docs/asciidoc/working-with-asciidoctor.adoc @@ -28,6 +28,7 @@ This section covers how to include Asciidoc snippets. You can use a macro named `operation` to import all or some of the snippets that have been generated for a specific operation. It is made available by including `spring-restdocs-asciidoctor` in your project's <>. +`spring-restdocs-asciidoctor` requires AsciidoctorJ 3.0. The target of the macro is the name of the operation. In its simplest form, you can use the macro to include all of the snippets for an operation, as shown in the following example: diff --git a/docs/src/test/java/com/example/Constraints.java b/docs/src/test/java/com/example/Constraints.java index 649128745..6d8ef1fcd 100644 --- a/docs/src/test/java/com/example/Constraints.java +++ b/docs/src/test/java/com/example/Constraints.java @@ -18,8 +18,8 @@ import java.util.List; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import org.springframework.restdocs.constraints.ConstraintDescriptions; diff --git a/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java b/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java index c28fb1a5e..5aec4248d 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java +++ b/docs/src/test/java/com/example/mockmvc/CustomDefaultOperationPreprocessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,34 +16,33 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; -public class CustomDefaultOperationPreprocessors { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomDefaultOperationPreprocessors { private WebApplicationContext context; @SuppressWarnings("unused") private MockMvc mockMvc; - @Before - public void setup() { + @BeforeEach + void setup(RestDocumentationContextProvider restDocumentation) { // tag::custom-default-operation-preprocessors[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> + .apply(documentationConfiguration(restDocumentation).operationPreprocessors() + .withRequestDefaults(modifyHeaders().remove("Foo")) // <1> .withResponseDefaults(prettyPrint())) // <2> .build(); // end::custom-default-operation-preprocessors[] diff --git a/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java b/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java index e5905a6eb..860e8e1e2 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java +++ b/docs/src/test/java/com/example/mockmvc/CustomDefaultSnippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,11 +16,12 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @@ -28,10 +29,8 @@ import static org.springframework.restdocs.cli.CliDocumentation.curlRequest; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -public class CustomDefaultSnippets { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomDefaultSnippets { @Autowired private WebApplicationContext context; @@ -39,11 +38,11 @@ public class CustomDefaultSnippets { @SuppressWarnings("unused") private MockMvc mockMvc; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-default-snippets[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).snippets().withDefaults(curlRequest())) + .apply(documentationConfiguration(restDocumentation).snippets().withDefaults(curlRequest())) .build(); // end::custom-default-snippets[] } diff --git a/docs/src/test/java/com/example/mockmvc/CustomEncoding.java b/docs/src/test/java/com/example/mockmvc/CustomEncoding.java index fbca4c617..7b6d1a42d 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomEncoding.java +++ b/docs/src/test/java/com/example/mockmvc/CustomEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,21 +16,20 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -public class CustomEncoding { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomEncoding { @Autowired private WebApplicationContext context; @@ -38,11 +37,11 @@ public class CustomEncoding { @SuppressWarnings("unused") private MockMvc mockMvc; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-encoding[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).snippets().withEncoding("ISO-8859-1")) + .apply(documentationConfiguration(restDocumentation).snippets().withEncoding("ISO-8859-1")) .build(); // end::custom-encoding[] } diff --git a/docs/src/test/java/com/example/mockmvc/CustomFormat.java b/docs/src/test/java/com/example/mockmvc/CustomFormat.java index 7427491f0..75a304654 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomFormat.java +++ b/docs/src/test/java/com/example/mockmvc/CustomFormat.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,11 +16,12 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -28,10 +29,8 @@ import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -public class CustomFormat { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomFormat { @Autowired private WebApplicationContext context; @@ -39,11 +38,11 @@ public class CustomFormat { @SuppressWarnings("unused") private MockMvc mockMvc; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-format[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).snippets() + .apply(documentationConfiguration(restDocumentation).snippets() .withTemplateFormat(TemplateFormats.markdown())) .build(); // end::custom-format[] diff --git a/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java b/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java index 7b3a1ef97..7af440b08 100644 --- a/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java +++ b/docs/src/test/java/com/example/mockmvc/CustomUriConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,21 +16,20 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -public class CustomUriConfiguration { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomUriConfiguration { @Autowired private WebApplicationContext context; @@ -38,11 +37,11 @@ public class CustomUriConfiguration { @SuppressWarnings("unused") private MockMvc mockMvc; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-uri-configuration[] this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).uris() + .apply(documentationConfiguration(restDocumentation).uris() .withScheme("https") .withHost("example.com") .withPort(443)) diff --git a/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java b/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java index e99defe15..dcf4d44af 100644 --- a/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java +++ b/docs/src/test/java/com/example/mockmvc/EveryTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,10 +16,11 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @@ -29,25 +30,23 @@ import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +@ExtendWith(RestDocumentationExtension.class) public class EveryTestPreprocessing { - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - private WebApplicationContext context; // tag::setup[] private MockMvc mockMvc; - @Before - public void setup() { + @BeforeEach + void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> + .apply(documentationConfiguration(restDocumentation).operationPreprocessors() + .withRequestDefaults(modifyHeaders().remove("Foo")) // <1> .withResponseDefaults(prettyPrint())) // <2> .build(); } diff --git a/docs/src/test/java/com/example/mockmvc/ExampleApplicationJUnit5Tests.java b/docs/src/test/java/com/example/mockmvc/ExampleApplicationJUnit5Tests.java deleted file mode 100644 index c012699e7..000000000 --- a/docs/src/test/java/com/example/mockmvc/ExampleApplicationJUnit5Tests.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2014-2023 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.mockmvc; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.restdocs.RestDocumentationContextProvider; -import org.springframework.restdocs.RestDocumentationExtension; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; - -@ExtendWith(RestDocumentationExtension.class) -class ExampleApplicationJUnit5Tests { - - @SuppressWarnings("unused") - // tag::setup[] - private MockMvc mockMvc; - - @BeforeEach - void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { - this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) - .apply(documentationConfiguration(restDocumentation)) // <1> - .build(); - } - // end::setup[] - -} diff --git a/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java b/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java index 3e6647853..24c0a3f4b 100644 --- a/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java +++ b/docs/src/test/java/com/example/mockmvc/ExampleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,33 +16,28 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -public class ExampleApplicationTests { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class ExampleApplicationTests { @SuppressWarnings("unused") // tag::setup[] private MockMvc mockMvc; - @Autowired - private WebApplicationContext context; - - @Before - public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) // <1> + @BeforeEach + void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .apply(documentationConfiguration(restDocumentation)) // <1> .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/mockmvc/FormParameters.java b/docs/src/test/java/com/example/mockmvc/FormParameters.java new file mode 100644 index 000000000..ff1472c1c --- /dev/null +++ b/docs/src/test/java/com/example/mockmvc/FormParameters.java @@ -0,0 +1,41 @@ +/* + * Copyright 2014-2023 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.mockmvc; + +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.request.RequestDocumentation.formParameters; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +public class FormParameters { + + private MockMvc mockMvc; + + public void postFormDataSnippet() throws Exception { + // tag::form-parameters[] + this.mockMvc.perform(post("/users").param("username", "Tester")) // <1> + .andExpect(status().isCreated()) + .andDo(document("create-user", formParameters(// <2> + parameterWithName("username").description("The user's username") // <3> + ))); + // end::form-parameters[] + } + +} diff --git a/docs/src/test/java/com/example/mockmvc/HttpCookies.java b/docs/src/test/java/com/example/mockmvc/HttpCookies.java new file mode 100644 index 000000000..ad609bf59 --- /dev/null +++ b/docs/src/test/java/com/example/mockmvc/HttpCookies.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014-2023 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.mockmvc; + +import jakarta.servlet.http.Cookie; + +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.restdocs.cookies.CookieDocumentation.cookieWithName; +import static org.springframework.restdocs.cookies.CookieDocumentation.requestCookies; +import static org.springframework.restdocs.cookies.CookieDocumentation.responseCookies; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +public class HttpCookies { + + private MockMvc mockMvc; + + public void cookies() throws Exception { + // tag::cookies[] + this.mockMvc.perform(get("/").cookie(new Cookie("JSESSIONID", "ACBCDFD0FF93D5BB"))) // <1> + .andExpect(status().isOk()) + .andDo(document("cookies", requestCookies(// <2> + cookieWithName("JSESSIONID").description("Session token")), // <3> + responseCookies(// <4> + cookieWithName("JSESSIONID").description("Updated session token"), + cookieWithName("logged_in") + .description("Set to true if the user is currently logged in")))); + // end::cookies[] + } + +} diff --git a/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java b/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java index 436643222..831c9a4ae 100644 --- a/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java +++ b/docs/src/test/java/com/example/mockmvc/ParameterizedOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,10 +16,11 @@ package com.example.mockmvc; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @@ -27,10 +28,8 @@ import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -public class ParameterizedOutput { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class ParameterizedOutput { @SuppressWarnings("unused") private MockMvc mockMvc; @@ -38,10 +37,10 @@ public class ParameterizedOutput { private WebApplicationContext context; // tag::parameterized-output[] - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) + .apply(documentationConfiguration(restDocumentation)) .alwaysDo(document("{method-name}/{step}/")) .build(); } diff --git a/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java b/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java index e99b79513..75f91610e 100644 --- a/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java +++ b/docs/src/test/java/com/example/mockmvc/PerTestPreprocessing.java @@ -20,10 +20,10 @@ import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class PerTestPreprocessing { @@ -34,7 +34,7 @@ public void general() throws Exception { // tag::preprocessing[] this.mockMvc.perform(get("/")) .andExpect(status().isOk()) - .andDo(document("index", preprocessRequest(removeHeaders("Foo")), // <1> + .andDo(document("index", preprocessRequest(modifyHeaders().remove("Foo")), // <1> preprocessResponse(prettyPrint()))); // <2> // end::preprocessing[] } diff --git a/docs/src/test/java/com/example/mockmvc/RequestParameters.java b/docs/src/test/java/com/example/mockmvc/QueryParameters.java similarity index 68% rename from docs/src/test/java/com/example/mockmvc/RequestParameters.java rename to docs/src/test/java/com/example/mockmvc/QueryParameters.java index a88a71b7d..68c60f917 100644 --- a/docs/src/test/java/com/example/mockmvc/RequestParameters.java +++ b/docs/src/test/java/com/example/mockmvc/QueryParameters.java @@ -20,33 +20,23 @@ import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -public class RequestParameters { +public class QueryParameters { private MockMvc mockMvc; public void getQueryStringSnippet() throws Exception { - // tag::request-parameters-query-string[] + // tag::query-parameters[] this.mockMvc.perform(get("/users?page=2&per_page=100")) // <1> .andExpect(status().isOk()) - .andDo(document("users", requestParameters(// <2> + .andDo(document("users", queryParameters(// <2> parameterWithName("page").description("The page to retrieve"), // <3> parameterWithName("per_page").description("Entries per page") // <4> ))); - // end::request-parameters-query-string[] - } - - public void postFormDataSnippet() throws Exception { - // tag::request-parameters-form-data[] - this.mockMvc.perform(post("/users").param("username", "Tester")) // <1> - .andExpect(status().isCreated()) - .andDo(document("create-user", - requestParameters(parameterWithName("username").description("The user's username")))); - // end::request-parameters-form-data[] + // end::query-parameters[] } } diff --git a/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java b/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java index 30dfaca92..2d0fa772d 100644 --- a/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java +++ b/docs/src/test/java/com/example/restassured/CustomDefaultOperationPreprocessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,29 +18,28 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; -public class CustomDefaultOperationPreprocessors { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomDefaultOperationPreprocessors { @SuppressWarnings("unused") private RequestSpecification spec; - @Before - public void setup() { + @BeforeEach + void setup(RestDocumentationContextProvider restDocumentation) { // tag::custom-default-operation-preprocessors[] this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> + .addFilter(documentationConfiguration(restDocumentation).operationPreprocessors() + .withRequestDefaults(modifyHeaders().remove("Foo")) // <1> .withResponseDefaults(prettyPrint())) // <2> .build(); // end::custom-default-operation-preprocessors[] diff --git a/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java b/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java index d3d514042..3b6d175f1 100644 --- a/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java +++ b/docs/src/test/java/com/example/restassured/CustomDefaultSnippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,27 +18,26 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import static org.springframework.restdocs.cli.CliDocumentation.curlRequest; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; -public class CustomDefaultSnippets { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomDefaultSnippets { @SuppressWarnings("unused") private RequestSpecification spec; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-default-snippets[] this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).snippets().withDefaults(curlRequest())) + .addFilter(documentationConfiguration(restDocumentation).snippets().withDefaults(curlRequest())) .build(); // end::custom-default-snippets[] } diff --git a/docs/src/test/java/com/example/restassured/CustomEncoding.java b/docs/src/test/java/com/example/restassured/CustomEncoding.java index c77d883e7..316b19a21 100644 --- a/docs/src/test/java/com/example/restassured/CustomEncoding.java +++ b/docs/src/test/java/com/example/restassured/CustomEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,26 +18,25 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; -public class CustomEncoding { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomEncoding { @SuppressWarnings("unused") private RequestSpecification spec; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-encoding[] this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).snippets().withEncoding("ISO-8859-1")) + .addFilter(documentationConfiguration(restDocumentation).snippets().withEncoding("ISO-8859-1")) .build(); // end::custom-encoding[] } diff --git a/docs/src/test/java/com/example/restassured/CustomFormat.java b/docs/src/test/java/com/example/restassured/CustomFormat.java index c1f52357a..5f690f1b3 100644 --- a/docs/src/test/java/com/example/restassured/CustomFormat.java +++ b/docs/src/test/java/com/example/restassured/CustomFormat.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,27 +18,26 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.templates.TemplateFormats; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; -public class CustomFormat { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomFormat { @SuppressWarnings("unused") private RequestSpecification spec; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-format[] this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).snippets() + .addFilter(documentationConfiguration(restDocumentation).snippets() .withTemplateFormat(TemplateFormats.markdown())) .build(); // end::custom-format[] diff --git a/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java b/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java index 227ff3307..741cfdfe9 100644 --- a/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java +++ b/docs/src/test/java/com/example/restassured/EveryTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -19,38 +19,37 @@ import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import static org.hamcrest.CoreMatchers.is; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; -public class EveryTestPreprocessing { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class EveryTestPreprocessing { // tag::setup[] private RequestSpecification spec; - @Before - public void setup() { + @BeforeEach + void setup(RestDocumentationContextProvider restDocumentation) { this.spec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> + .addFilter(documentationConfiguration(restDocumentation).operationPreprocessors() + .withRequestDefaults(modifyHeaders().remove("Foo")) // <1> .withResponseDefaults(prettyPrint())) // <2> .build(); } // end::setup[] - public void use() { + void use() { // tag::use[] RestAssured.given(this.spec) .filter(document("index", links(linkWithRel("self").description("Canonical self link")))) diff --git a/docs/src/test/java/com/example/restassured/ExampleApplicationJUnit5Tests.java b/docs/src/test/java/com/example/restassured/ExampleApplicationJUnit5Tests.java deleted file mode 100644 index bd2022df1..000000000 --- a/docs/src/test/java/com/example/restassured/ExampleApplicationJUnit5Tests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014-2023 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.restassured; - -import io.restassured.builder.RequestSpecBuilder; -import io.restassured.specification.RequestSpecification; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.restdocs.RestDocumentationContextProvider; -import org.springframework.restdocs.RestDocumentationExtension; - -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; - -@ExtendWith(RestDocumentationExtension.class) -class ExampleApplicationJUnit5Tests { - - @SuppressWarnings("unused") - // tag::setup[] - private RequestSpecification spec; - - @BeforeEach - void setUp(RestDocumentationContextProvider restDocumentation) { - this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(restDocumentation)) // <1> - .build(); - } - // end::setup[] - -} diff --git a/docs/src/test/java/com/example/restassured/ExampleApplicationTestNgTests.java b/docs/src/test/java/com/example/restassured/ExampleApplicationTestNgTests.java index 22af139a4..d1e07b215 100644 --- a/docs/src/test/java/com/example/restassured/ExampleApplicationTestNgTests.java +++ b/docs/src/test/java/com/example/restassured/ExampleApplicationTestNgTests.java @@ -25,7 +25,7 @@ import org.springframework.restdocs.ManualRestDocumentation; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; public class ExampleApplicationTestNgTests { diff --git a/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java b/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java index 5f4a2cca5..7affb1ef2 100644 --- a/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java +++ b/docs/src/test/java/com/example/restassured/ExampleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,25 +18,24 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; -public class ExampleApplicationTests { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class ExampleApplicationTests { @SuppressWarnings("unused") // tag::setup[] private RequestSpecification spec; - @Before - public void setUp() { - this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(this.restDocumentation)) // <1> + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { + this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(restDocumentation)) // <1> .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/restassured/FormParameters.java b/docs/src/test/java/com/example/restassured/FormParameters.java new file mode 100644 index 000000000..88a720f14 --- /dev/null +++ b/docs/src/test/java/com/example/restassured/FormParameters.java @@ -0,0 +1,45 @@ +/* + * Copyright 2014-2023 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.restassured; + +import io.restassured.RestAssured; +import io.restassured.specification.RequestSpecification; + +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.restdocs.request.RequestDocumentation.formParameters; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; + +public class FormParameters { + + private RequestSpecification spec; + + public void postFormDataSnippet() { + // tag::form-parameters[] + RestAssured.given(this.spec) + .filter(document("create-user", formParameters(// <1> + parameterWithName("username").description("The user's username")))) // <2> + .formParam("username", "Tester") + .when() + .post("/users") // <3> + .then() + .assertThat() + .statusCode(is(200)); + // end::form-parameters[] + } + +} diff --git a/docs/src/test/java/com/example/restassured/HttpCookies.java b/docs/src/test/java/com/example/restassured/HttpCookies.java new file mode 100644 index 000000000..3ad4993ca --- /dev/null +++ b/docs/src/test/java/com/example/restassured/HttpCookies.java @@ -0,0 +1,49 @@ +/* + * Copyright 2014-2023 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.restassured; + +import io.restassured.RestAssured; +import io.restassured.specification.RequestSpecification; + +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.restdocs.cookies.CookieDocumentation.cookieWithName; +import static org.springframework.restdocs.cookies.CookieDocumentation.requestCookies; +import static org.springframework.restdocs.cookies.CookieDocumentation.responseCookies; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; + +public class HttpCookies { + + private RequestSpecification spec; + + public void cookies() { + // tag::cookies[] + RestAssured.given(this.spec) + .filter(document("cookies", requestCookies(// <1> + cookieWithName("JSESSIONID").description("Saved session token")), // <2> + responseCookies(// <3> + cookieWithName("logged_in").description("If user is logged in"), + cookieWithName("JSESSIONID").description("Updated session token")))) + .cookie("JSESSIONID", "ACBCDFD0FF93D5BB") // <4> + .when() + .get("/people") + .then() + .assertThat() + .statusCode(is(200)); + // end::cookies[] + } + +} diff --git a/docs/src/test/java/com/example/restassured/HttpHeaders.java b/docs/src/test/java/com/example/restassured/HttpHeaders.java index 7bab4375c..4595c351c 100644 --- a/docs/src/test/java/com/example/restassured/HttpHeaders.java +++ b/docs/src/test/java/com/example/restassured/HttpHeaders.java @@ -23,7 +23,7 @@ import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class HttpHeaders { diff --git a/docs/src/test/java/com/example/restassured/Hypermedia.java b/docs/src/test/java/com/example/restassured/Hypermedia.java index d357ec168..410daca80 100644 --- a/docs/src/test/java/com/example/restassured/Hypermedia.java +++ b/docs/src/test/java/com/example/restassured/Hypermedia.java @@ -23,7 +23,7 @@ import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.halLinks; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class Hypermedia { diff --git a/docs/src/test/java/com/example/restassured/InvokeService.java b/docs/src/test/java/com/example/restassured/InvokeService.java index befb550ac..8d5de1b7d 100644 --- a/docs/src/test/java/com/example/restassured/InvokeService.java +++ b/docs/src/test/java/com/example/restassured/InvokeService.java @@ -20,7 +20,7 @@ import io.restassured.specification.RequestSpecification; import static org.hamcrest.CoreMatchers.is; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class InvokeService { diff --git a/docs/src/test/java/com/example/restassured/ParameterizedOutput.java b/docs/src/test/java/com/example/restassured/ParameterizedOutput.java index aa6680637..7471d1772 100644 --- a/docs/src/test/java/com/example/restassured/ParameterizedOutput.java +++ b/docs/src/test/java/com/example/restassured/ParameterizedOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,26 +18,25 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; +@ExtendWith(RestDocumentationExtension.class) public class ParameterizedOutput { - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - @SuppressWarnings("unused") private RequestSpecification spec; // tag::parameterized-output[] - @Before - public void setUp() { - this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(this.restDocumentation)) + @BeforeEach + public void setUp(RestDocumentationContextProvider restDocumentation) { + this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(restDocumentation)) .addFilter(document("{method-name}/{step}")) .build(); } diff --git a/docs/src/test/java/com/example/restassured/PathParameters.java b/docs/src/test/java/com/example/restassured/PathParameters.java index b76d588ce..dc2f3306b 100644 --- a/docs/src/test/java/com/example/restassured/PathParameters.java +++ b/docs/src/test/java/com/example/restassured/PathParameters.java @@ -22,7 +22,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class PathParameters { diff --git a/docs/src/test/java/com/example/restassured/Payload.java b/docs/src/test/java/com/example/restassured/Payload.java index 44da28f3a..6c90f2299 100644 --- a/docs/src/test/java/com/example/restassured/Payload.java +++ b/docs/src/test/java/com/example/restassured/Payload.java @@ -29,7 +29,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.responseBody; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; diff --git a/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java b/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java index dd7d395dc..eeb937af5 100644 --- a/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java +++ b/docs/src/test/java/com/example/restassured/PerTestPreprocessing.java @@ -20,11 +20,11 @@ import io.restassured.specification.RequestSpecification; import static org.hamcrest.CoreMatchers.is; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class PerTestPreprocessing { @@ -33,7 +33,7 @@ public class PerTestPreprocessing { public void general() { // tag::preprocessing[] RestAssured.given(this.spec) - .filter(document("index", preprocessRequest(removeHeaders("Foo")), // <1> + .filter(document("index", preprocessRequest(modifyHeaders().remove("Foo")), // <1> preprocessResponse(prettyPrint()))) // <2> .when() .get("/") diff --git a/docs/src/test/java/com/example/restassured/RequestParameters.java b/docs/src/test/java/com/example/restassured/QueryParameters.java similarity index 65% rename from docs/src/test/java/com/example/restassured/RequestParameters.java rename to docs/src/test/java/com/example/restassured/QueryParameters.java index 61bfbcdfb..27488ed93 100644 --- a/docs/src/test/java/com/example/restassured/RequestParameters.java +++ b/docs/src/test/java/com/example/restassured/QueryParameters.java @@ -21,17 +21,17 @@ import static org.hamcrest.CoreMatchers.is; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; -public class RequestParameters { +public class QueryParameters { private RequestSpecification spec; public void getQueryStringSnippet() { - // tag::request-parameters-query-string[] + // tag::query-parameters[] RestAssured.given(this.spec) - .filter(document("users", requestParameters(// <1> + .filter(document("users", queryParameters(// <1> parameterWithName("page").description("The page to retrieve"), // <2> parameterWithName("per_page").description("Entries per page")))) // <3> .when() @@ -39,21 +39,7 @@ public void getQueryStringSnippet() { .then() .assertThat() .statusCode(is(200)); - // end::request-parameters-query-string[] - } - - public void postFormDataSnippet() { - // tag::request-parameters-form-data[] - RestAssured.given(this.spec) - .filter(document("create-user", - requestParameters(parameterWithName("username").description("The user's username")))) - .formParam("username", "Tester") // <1> - .when() - .post("/users") // <2> - .then() - .assertThat() - .statusCode(is(200)); - // end::request-parameters-form-data[] + // end::query-parameters[] } } diff --git a/docs/src/test/java/com/example/restassured/RequestPartPayload.java b/docs/src/test/java/com/example/restassured/RequestPartPayload.java index abed650ff..2566c37a9 100644 --- a/docs/src/test/java/com/example/restassured/RequestPartPayload.java +++ b/docs/src/test/java/com/example/restassured/RequestPartPayload.java @@ -27,7 +27,7 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestPartBody; import static org.springframework.restdocs.payload.PayloadDocumentation.requestPartFields; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class RequestPartPayload { diff --git a/docs/src/test/java/com/example/restassured/RequestParts.java b/docs/src/test/java/com/example/restassured/RequestParts.java index 534e18ebc..ee3547367 100644 --- a/docs/src/test/java/com/example/restassured/RequestParts.java +++ b/docs/src/test/java/com/example/restassured/RequestParts.java @@ -22,7 +22,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class RequestParts { diff --git a/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java b/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java index cc7cc6eee..800903a00 100644 --- a/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java +++ b/docs/src/test/java/com/example/restassured/RestAssuredSnippetReuse.java @@ -22,7 +22,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; public class RestAssuredSnippetReuse extends SnippetReuse { diff --git a/docs/src/test/java/com/example/webtestclient/CustomDefaultOperationPreprocessors.java b/docs/src/test/java/com/example/webtestclient/CustomDefaultOperationPreprocessors.java index d1688d53c..17ee06b44 100644 --- a/docs/src/test/java/com/example/webtestclient/CustomDefaultOperationPreprocessors.java +++ b/docs/src/test/java/com/example/webtestclient/CustomDefaultOperationPreprocessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -16,37 +16,36 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class CustomDefaultOperationPreprocessors { +@ExtendWith(RestDocumentationExtension.class) +class CustomDefaultOperationPreprocessors { // @formatter:off - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - private ApplicationContext context; @SuppressWarnings("unused") private WebTestClient webTestClient; - @Before - public void setup() { + @BeforeEach + void setup(RestDocumentationContextProvider restDocumentation) { // tag::custom-default-operation-preprocessors[] this.webTestClient = WebTestClient.bindToApplicationContext(this.context) .configureClient() - .filter(documentationConfiguration(this.restDocumentation) + .filter(documentationConfiguration(restDocumentation) .operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> + .withRequestDefaults(modifyHeaders().remove("Foo")) // <1> .withResponseDefaults(prettyPrint())) // <2> .build(); // end::custom-default-operation-preprocessors[] diff --git a/docs/src/test/java/com/example/webtestclient/CustomDefaultSnippets.java b/docs/src/test/java/com/example/webtestclient/CustomDefaultSnippets.java index 5910ac713..420a52f49 100644 --- a/docs/src/test/java/com/example/webtestclient/CustomDefaultSnippets.java +++ b/docs/src/test/java/com/example/webtestclient/CustomDefaultSnippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -16,36 +16,35 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.cli.CliDocumentation.curlRequest; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class CustomDefaultSnippets { +@ExtendWith(RestDocumentationExtension.class) +class CustomDefaultSnippets { // @formatter:off - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - @Autowired private ApplicationContext context; @SuppressWarnings("unused") private WebTestClient webTestClient; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-default-snippets[] this.webTestClient = WebTestClient.bindToApplicationContext(this.context) .configureClient().filter( - documentationConfiguration(this.restDocumentation) + documentationConfiguration(restDocumentation) .snippets().withDefaults(curlRequest())) .build(); // end::custom-default-snippets[] diff --git a/docs/src/test/java/com/example/webtestclient/CustomEncoding.java b/docs/src/test/java/com/example/webtestclient/CustomEncoding.java index fd8176713..42800d797 100644 --- a/docs/src/test/java/com/example/webtestclient/CustomEncoding.java +++ b/docs/src/test/java/com/example/webtestclient/CustomEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -16,34 +16,33 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class CustomEncoding { +@ExtendWith(RestDocumentationExtension.class) +class CustomEncoding { // @formatter:off - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - @Autowired private ApplicationContext context; @SuppressWarnings("unused") private WebTestClient webTestClient; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-encoding[] this.webTestClient = WebTestClient.bindToApplicationContext(this.context).configureClient() - .filter(documentationConfiguration(this.restDocumentation) + .filter(documentationConfiguration(restDocumentation) .snippets().withEncoding("ISO-8859-1")) .build(); // end::custom-encoding[] diff --git a/docs/src/test/java/com/example/webtestclient/CustomFormat.java b/docs/src/test/java/com/example/webtestclient/CustomFormat.java index 9021a39ac..ab57f1846 100644 --- a/docs/src/test/java/com/example/webtestclient/CustomFormat.java +++ b/docs/src/test/java/com/example/webtestclient/CustomFormat.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -16,35 +16,34 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class CustomFormat { +@ExtendWith(RestDocumentationExtension.class) +class CustomFormat { // @formatter:off - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - @Autowired private ApplicationContext context; @SuppressWarnings("unused") private WebTestClient webTestClient; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { // tag::custom-format[] this.webTestClient = WebTestClient.bindToApplicationContext(this.context).configureClient() - .filter(documentationConfiguration(this.restDocumentation) + .filter(documentationConfiguration(restDocumentation) .snippets().withTemplateFormat(TemplateFormats.markdown())) .build(); // end::custom-format[] diff --git a/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java b/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java index 94d842477..9db88cded 100644 --- a/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java +++ b/docs/src/test/java/com/example/webtestclient/CustomUriConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,20 +16,19 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class CustomUriConfiguration { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class CustomUriConfiguration { @SuppressWarnings("unused") private WebTestClient webTestClient; @@ -38,12 +37,12 @@ public class CustomUriConfiguration { private ApplicationContext context; // tag::custom-uri-configuration[] - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { this.webTestClient = WebTestClient.bindToApplicationContext(this.context) .configureClient() .baseUrl("https://api.example.com") // <1> - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .build(); } // end::custom-uri-configuration[] diff --git a/docs/src/test/java/com/example/webtestclient/EveryTestPreprocessing.java b/docs/src/test/java/com/example/webtestclient/EveryTestPreprocessing.java index f628ab234..e6ff7ceb9 100644 --- a/docs/src/test/java/com/example/webtestclient/EveryTestPreprocessing.java +++ b/docs/src/test/java/com/example/webtestclient/EveryTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2025 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. @@ -16,45 +16,44 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class EveryTestPreprocessing { +@ExtendWith(RestDocumentationExtension.class) +class EveryTestPreprocessing { // @formatter:off - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - private ApplicationContext context; // tag::setup[] private WebTestClient webTestClient; - @Before - public void setup() { + @BeforeEach + void setup(RestDocumentationContextProvider restDocumentation) { this.webTestClient = WebTestClient.bindToApplicationContext(this.context) .configureClient() - .filter(documentationConfiguration(this.restDocumentation) + .filter(documentationConfiguration(restDocumentation) .operationPreprocessors() - .withRequestDefaults(removeHeaders("Foo")) // <1> + .withRequestDefaults(modifyHeaders().remove("Foo")) // <1> .withResponseDefaults(prettyPrint())) // <2> .build(); } // end::setup[] - public void use() { + void use() { // tag::use[] this.webTestClient.get().uri("/").exchange().expectStatus().isOk() .expectBody().consumeWith(document("index", diff --git a/docs/src/test/java/com/example/webtestclient/ExampleApplicationJUnit5Tests.java b/docs/src/test/java/com/example/webtestclient/ExampleApplicationJUnit5Tests.java deleted file mode 100644 index 4739440f5..000000000 --- a/docs/src/test/java/com/example/webtestclient/ExampleApplicationJUnit5Tests.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2014-2023 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.webtestclient; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.RestDocumentationContextProvider; -import org.springframework.restdocs.RestDocumentationExtension; -import org.springframework.test.web.reactive.server.WebTestClient; - -import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; - -@ExtendWith(RestDocumentationExtension.class) -class ExampleApplicationJUnit5Tests { - - @SuppressWarnings("unused") - // tag::setup[] - private WebTestClient webTestClient; - - @BeforeEach - void setUp(ApplicationContext applicationContext, RestDocumentationContextProvider restDocumentation) { - this.webTestClient = WebTestClient.bindToApplicationContext(applicationContext) - .configureClient() - .filter(documentationConfiguration(restDocumentation)) // <1> - .build(); - } - // end::setup[] - -} diff --git a/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java b/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java index 0ec72a4ea..3126487ad 100644 --- a/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java +++ b/docs/src/test/java/com/example/webtestclient/ExampleApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,33 +16,28 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class ExampleApplicationTests { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class ExampleApplicationTests { @SuppressWarnings("unused") // tag::setup[] private WebTestClient webTestClient; - @Autowired - private ApplicationContext context; - - @Before - public void setUp() { - this.webTestClient = WebTestClient.bindToApplicationContext(this.context) + @BeforeEach + void setUp(ApplicationContext applicationContext, RestDocumentationContextProvider restDocumentation) { + this.webTestClient = WebTestClient.bindToApplicationContext(applicationContext) .configureClient() - .filter(documentationConfiguration(this.restDocumentation)) // <1> + .filter(documentationConfiguration(restDocumentation)) // <1> .build(); } // end::setup[] diff --git a/docs/src/test/java/com/example/webtestclient/RequestParameters.java b/docs/src/test/java/com/example/webtestclient/FormParameters.java similarity index 64% rename from docs/src/test/java/com/example/webtestclient/RequestParameters.java rename to docs/src/test/java/com/example/webtestclient/FormParameters.java index de0cb2394..0bfdbc0c1 100644 --- a/docs/src/test/java/com/example/webtestclient/RequestParameters.java +++ b/docs/src/test/java/com/example/webtestclient/FormParameters.java @@ -21,37 +21,26 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; +import static org.springframework.restdocs.request.RequestDocumentation.formParameters; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; -public class RequestParameters { +public class FormParameters { // @formatter:off private WebTestClient webTestClient; - public void getQueryStringSnippet() { - // tag::request-parameters-query-string[] - this.webTestClient.get().uri("/users?page=2&per_page=100") // <1> - .exchange().expectStatus().isOk().expectBody() - .consumeWith(document("users", requestParameters(// <2> - parameterWithName("page").description("The page to retrieve"), // <3> - parameterWithName("per_page").description("Entries per page") // <4> - ))); - // end::request-parameters-query-string[] - } - public void postFormDataSnippet() { - // tag::request-parameters-form-data[] + // tag::form-parameters[] MultiValueMap formData = new LinkedMultiValueMap<>(); formData.add("username", "Tester"); this.webTestClient.post().uri("/users").body(BodyInserters.fromFormData(formData)) // <1> - .exchange().expectStatus().isCreated().expectBody() - .consumeWith(document("create-user", requestParameters( - parameterWithName("username").description("The user's username") - ))); - // end::request-parameters-form-data[] + .exchange().expectStatus().isCreated().expectBody() + .consumeWith(document("create-user", formParameters(// <2> + parameterWithName("username").description("The user's username") // <3> + ))); + // end::form-parameters[] } } diff --git a/docs/src/test/java/com/example/webtestclient/HttpCookies.java b/docs/src/test/java/com/example/webtestclient/HttpCookies.java new file mode 100644 index 000000000..1db0fe475 --- /dev/null +++ b/docs/src/test/java/com/example/webtestclient/HttpCookies.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014-2023 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.webtestclient; + +import org.springframework.test.web.reactive.server.WebTestClient; + +import static org.springframework.restdocs.cookies.CookieDocumentation.cookieWithName; +import static org.springframework.restdocs.cookies.CookieDocumentation.requestCookies; +import static org.springframework.restdocs.cookies.CookieDocumentation.responseCookies; +import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; + +public class HttpCookies { + + private WebTestClient webTestClient; + + public void cookies() { + // tag::cookies[] + this.webTestClient.get() + .uri("/people") + .cookie("JSESSIONID", "ACBCDFD0FF93D5BB=") // <1> + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("cookies", requestCookies(// <2> + cookieWithName("JSESSIONID").description("Session token")), // <3> + responseCookies(// <4> + cookieWithName("JSESSIONID").description("Updated session token"), + cookieWithName("logged_in").description("User is logged in")))); + // end::cookies[] + } + +} diff --git a/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java b/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java index 6d1dae319..f37702746 100644 --- a/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java +++ b/docs/src/test/java/com/example/webtestclient/ParameterizedOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,21 +16,20 @@ package com.example.webtestclient; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -public class ParameterizedOutput { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class ParameterizedOutput { @SuppressWarnings("unused") private WebTestClient webTestClient; @@ -39,11 +38,11 @@ public class ParameterizedOutput { private ApplicationContext context; // tag::parameterized-output[] - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { this.webTestClient = WebTestClient.bindToApplicationContext(this.context) .configureClient() - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .entityExchangeResultConsumer(document("{method-name}/{step}")) .build(); } diff --git a/docs/src/test/java/com/example/webtestclient/PerTestPreprocessing.java b/docs/src/test/java/com/example/webtestclient/PerTestPreprocessing.java index f6d45f185..cd1254efe 100644 --- a/docs/src/test/java/com/example/webtestclient/PerTestPreprocessing.java +++ b/docs/src/test/java/com/example/webtestclient/PerTestPreprocessing.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2022 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. @@ -18,10 +18,10 @@ import org.springframework.test.web.reactive.server.WebTestClient; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; public class PerTestPreprocessing { @@ -34,7 +34,7 @@ public void general() { // tag::preprocessing[] this.webTestClient.get().uri("/").exchange().expectStatus().isOk().expectBody() .consumeWith(document("index", - preprocessRequest(removeHeaders("Foo")), // <1> + preprocessRequest(modifyHeaders().remove("Foo")), // <1> preprocessResponse(prettyPrint()))); // <2> // end::preprocessing[] } diff --git a/docs/src/test/java/com/example/webtestclient/QueryParameters.java b/docs/src/test/java/com/example/webtestclient/QueryParameters.java new file mode 100644 index 000000000..347c700b6 --- /dev/null +++ b/docs/src/test/java/com/example/webtestclient/QueryParameters.java @@ -0,0 +1,42 @@ +/* + * Copyright 2014-2022 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.webtestclient; + +import org.springframework.test.web.reactive.server.WebTestClient; + +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; +import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; + +public class QueryParameters { + + // @formatter:off + + private WebTestClient webTestClient; + + public void getQueryStringSnippet() { + // tag::query-parameters[] + this.webTestClient.get().uri("/users?page=2&per_page=100") // <1> + .exchange().expectStatus().isOk().expectBody() + .consumeWith(document("users", queryParameters(// <2> + parameterWithName("page").description("The page to retrieve"), // <3> + parameterWithName("per_page").description("Entries per page") // <4> + ))); + // end::query-parameters[] + } + +} diff --git a/git/hooks/forward-merge b/git/hooks/forward-merge new file mode 100755 index 000000000..a042bb460 --- /dev/null +++ b/git/hooks/forward-merge @@ -0,0 +1,146 @@ +#!/usr/bin/ruby +require 'json' +require 'net/http' +require 'yaml' +require 'logger' + +$log = Logger.new(STDOUT) +$log.level = Logger::WARN + +class ForwardMerge + attr_reader :issue, :milestone, :message, :line + def initialize(issue, milestone, message, line) + @issue = issue + @milestone = milestone + @message = message + @line = line + end +end + +def find_forward_merges(message_file) + + $log.debug "Searching for forward merge" + branch=`git rev-parse -q --abbrev-ref HEAD`.strip + $log.debug "Found #{branch} from git rev-parse --abbrev-ref" + if( branch == "docs-build") then + $log.debug "Skipping docs build" + return nil + end + rev=`git rev-parse -q --verify MERGE_HEAD`.strip + $log.debug "Found #{rev} from git rev-parse" + return nil unless rev + message = File.read(message_file) + forward_merges = [] + message.each_line do |line| + $log.debug "Checking #{line} for message" + match = /^(?:Fixes|Closes) gh-(\d+) in (\d\.\d\.[\dx](?:[\.\-](?:M|RC)\d)?)$/.match(line) + if match then + issue = match[1] + milestone = match[2] + $log.debug "Matched reference to issue #{issue} in milestone #{milestone}" + forward_merges << ForwardMerge.new(issue, milestone, message, line) + end + end + $log.debug "No match in merge message" unless forward_merges + return forward_merges +end + +def get_issue(username, password, repository, number) + $log.debug "Getting issue #{number} from GitHub repository #{repository}" + uri = URI("https://api.github.com/repos/#{repository}/issues/#{number}") + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl=true + request = Net::HTTP::Get.new(uri.path) + request.basic_auth(username, password) + response = http.request(request) + $log.debug "Get HTTP response #{response.code}" + return JSON.parse(response.body) unless response.code != '200' + puts "Failed to retrieve issue #{number}: #{response.message}" + exit 1 +end + +def find_milestone(username, password, repository, title) + $log.debug "Finding milestone #{title} from GitHub repository #{repository}" + uri = URI("https://api.github.com/repos/#{repository}/milestones") + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl=true + request = Net::HTTP::Get.new(uri.path) + request.basic_auth(username, password) + response = http.request(request) + milestones = JSON.parse(response.body) + if title.end_with?(".x") + prefix = title.delete_suffix('.x') + $log.debug "Finding nearest milestone from candidates starting with #{prefix}" + titles = milestones.map { |milestone| milestone['title'] } + titles = titles.select{ |title| title.start_with?(prefix) unless title.end_with?('.x') || (title.count('.') > 2)} + titles = titles.sort_by { |v| Gem::Version.new(v) } + $log.debug "Considering candidates #{titles}" + if(titles.empty?) + puts "Cannot find nearest milestone for prefix #{title}" + exit 1 + end + title = titles.first + $log.debug "Found nearest milestone #{title}" + end + milestones.each do |milestone| + $log.debug "Considering #{milestone['title']}" + return milestone['number'] if milestone['title'] == title + end + puts "Milestone #{title} not found" + exit 1 +end + +def create_issue(username, password, repository, original, title, labels, milestone, milestone_name, dry_run) + $log.debug "Finding forward-merge issue in GitHub repository #{repository} for '#{title}'" + uri = URI("https://api.github.com/repos/#{repository}/issues") + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl=true + request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json') + request.basic_auth(username, password) + request.body = { + title: title, + labels: labels, + milestone: milestone.to_i, + body: "Forward port of issue ##{original} to #{milestone_name}." + }.to_json + if dry_run then + puts "Dry run" + puts "POSTing to #{uri} with body #{request.body}" + return "dry-run" + end + response = JSON.parse(http.request(request).body) + $log.debug "Created new issue #{response['number']}" + return response['number'] +end + +$log.debug "Running forward-merge hook script" +message_file=ARGV[0] + +forward_merges = find_forward_merges(message_file) +exit 0 unless forward_merges + +$log.debug "Loading config from ~/.spring-restdocs/forward-merge.yml" +config = YAML.load_file(File.join(Dir.home, '.spring-restdocs', 'forward-merge.yml')) +username = config['github']['credentials']['username'] +password = config['github']['credentials']['password'] +dry_run = config['dry_run'] + +gradleProperties = IO.read('gradle.properties') +springBuildType = gradleProperties.match(/^spring\.build-type\s?=\s?(.*)$/) +repository = (springBuildType && springBuildType[1] != 'oss') ? "spring-projects/spring-restdocs-#{springBuildType[1]}" : "spring-projects/spring-restdocs"; +$log.debug "Targeting repository #{repository}" + +forward_merges.each do |forward_merge| + existing_issue = get_issue(username, password, repository, forward_merge.issue) + title = existing_issue['title'] + labels = existing_issue['labels'].map { |label| label['name'] } + labels << "status: forward-port" + $log.debug "Processing issue '#{title}'" + + milestone = find_milestone(username, password, repository, forward_merge.milestone) + new_issue_number = create_issue(username, password, repository, forward_merge.issue, title, labels, milestone, forward_merge.milestone, dry_run) + + puts "Created gh-#{new_issue_number} for forward port of gh-#{forward_merge.issue} into #{forward_merge.milestone}" + rewritten_message = forward_merge.message.sub(forward_merge.line, "Closes gh-#{new_issue_number}\n") + File.write(message_file, rewritten_message) +end diff --git a/git/hooks/prepare-forward-merge b/git/hooks/prepare-forward-merge new file mode 100755 index 000000000..fbdb1e194 --- /dev/null +++ b/git/hooks/prepare-forward-merge @@ -0,0 +1,71 @@ +#!/usr/bin/ruby +require 'json' +require 'net/http' +require 'yaml' +require 'logger' + +$main_branch = "4.0.x" + +$log = Logger.new(STDOUT) +$log.level = Logger::WARN + +def get_fixed_issues() + $log.debug "Searching for forward merge" + rev=`git rev-parse -q --verify MERGE_HEAD`.strip + $log.debug "Found #{rev} from git rev-parse" + return nil unless rev + fixed = [] + message = `git log -1 --pretty=%B #{rev}` + message.each_line do |line| + $log.debug "Checking #{line} for message" + fixed << line.strip if /^(?:Fixes|Closes) gh-(\d+)/.match(line) + end + $log.debug "Found fixed issues #{fixed}" + return fixed; +end + +def rewrite_message(message_file, fixed) + current_branch = `git rev-parse --abbrev-ref HEAD`.strip + if current_branch == "main" + current_branch = $main_branch + end + rewritten_message = "" + message = File.read(message_file) + message.each_line do |line| + match = /^Merge.*branch\ '(.*)'(?:\ into\ (.*))?$/.match(line) + if match + from_branch = match[1] + if from_branch.include? "/" + from_branch = from_branch.partition("/").last + end + to_branch = match[2] + $log.debug "Rewriting merge message" + line = "Merge branch '#{from_branch}'" + (to_branch ? " into #{to_branch}\n" : "\n") + end + if fixed and line.start_with?("#") + $log.debug "Adding fixed" + rewritten_message << "\n" + fixed.each do |fixes| + rewritten_message << "#{fixes} in #{current_branch}\n" + end + fixed = nil + end + rewritten_message << line + end + return rewritten_message +end + +$log.debug "Running prepare-forward-merge hook script" + +message_file=ARGV[0] +message_type=ARGV[1] + +if message_type != "merge" + $log.debug "Not a merge commit" + exit 0; +end + +$log.debug "Searching for forward merge" +fixed = get_fixed_issues() +rewritten_message = rewrite_message(message_file, fixed) +File.write(message_file, rewritten_message) diff --git a/gradle.properties b/gradle.properties index 33a77abc2..5cc794136 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,17 +1,9 @@ -version=2.0.9.BUILD-SNAPSHOT +version=4.0.0-SNAPSHOT org.gradle.caching=true org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 org.gradle.parallel=true -asciidoctorj15Version=1.5.8.1 -asciidoctorj16Version=1.6.2 -asciidoctorj20Version=2.0.0 -asciidoctorj21Version=2.1.0 -asciidoctorj22Version=2.2.0 -asciidoctorj23Version=2.3.0 -asciidoctorj24Version=2.4.3 -asciidoctorj25Version=2.5.1 - -javaFormatVersion=0.0.39 -jmustacheVersion=1.12 +javaFormatVersion=0.0.43 +jmustacheVersion=1.15 +springFrameworkVersion=7.0.0-M1 diff --git a/gradle/publish-maven.gradle b/gradle/publish-maven.gradle index c04bca254..3c50ccb7f 100644 --- a/gradle/publish-maven.gradle +++ b/gradle/publish-maven.gradle @@ -21,6 +21,9 @@ plugins.withType(MavenPublishPlugin) { } } } + project.plugins.withType(JavaPlatformPlugin) { + from components.javaPlatform + } pom { name = project.provider { project.description } description = project.provider { project.description } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c02..1b33c55ba 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 442d9132e..002b867c4 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c8..23d15a936 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,81 +15,115 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar +CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd32c..db3a6ac20 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,32 +59,34 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar +set CLASSPATH= @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/samples/junit5/build.gradle b/samples/junit5/build.gradle deleted file mode 100644 index d157c2882..000000000 --- a/samples/junit5/build.gradle +++ /dev/null @@ -1,64 +0,0 @@ -plugins { - id "eclipse" - id "java" - id "org.asciidoctor.jvm.convert" version "3.3.2" - id "org.springframework.boot" version "2.6.2" -} - -apply plugin: 'io.spring.dependency-management' - -repositories { - mavenLocal() - maven { url 'https://repo.spring.io/milestone' } - maven { url 'https://repo.spring.io/snapshot' } - mavenCentral() -} - -group = 'com.example' - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -ext { - snippetsDir = file('build/generated-snippets') -} - -ext['spring-restdocs.version'] = '2.0.7.BUILD-SNAPSHOT' - -configurations { - asciidoctorExtensions -} - -dependencies { - asciidoctorExtensions 'org.springframework.restdocs:spring-restdocs-asciidoctor' - - implementation 'org.springframework.boot:spring-boot-starter-web' - - testImplementation('org.springframework.boot:spring-boot-starter-test') { - exclude group: 'junit', module: 'junit;' - } - testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' - testImplementation 'org.junit.jupiter:junit-jupiter-api' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' -} - -test { - outputs.dir snippetsDir - useJUnitPlatform() -} - -asciidoctor { - configurations "asciidoctorExtensions" - inputs.dir snippetsDir - dependsOn test -} - -bootJar { - dependsOn asciidoctor - from ("${asciidoctor.outputDir}/html5") { - into 'static/docs' - } -} - -eclipseJdt.onlyIf { false } -cleanEclipseJdt.onlyIf { false } diff --git a/samples/junit5/gradle/wrapper/gradle-wrapper.jar b/samples/junit5/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 62d4c0535..000000000 Binary files a/samples/junit5/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/samples/junit5/gradle/wrapper/gradle-wrapper.properties b/samples/junit5/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 442d9132e..000000000 --- a/samples/junit5/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/samples/junit5/gradlew b/samples/junit5/gradlew deleted file mode 100755 index fbd7c5158..000000000 --- a/samples/junit5/gradlew +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/samples/junit5/gradlew.bat b/samples/junit5/gradlew.bat deleted file mode 100644 index 5093609d5..000000000 --- a/samples/junit5/gradlew.bat +++ /dev/null @@ -1,104 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/samples/junit5/settings.gradle b/samples/junit5/settings.gradle deleted file mode 100644 index e69de29bb..000000000 diff --git a/samples/junit5/src/docs/asciidoc/index.adoc b/samples/junit5/src/docs/asciidoc/index.adoc deleted file mode 100644 index 68e690a94..000000000 --- a/samples/junit5/src/docs/asciidoc/index.adoc +++ /dev/null @@ -1,22 +0,0 @@ -= Spring REST Docs JUnit 5 Sample -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs - -Sample application demonstrating how to use Spring REST Docs with JUnit 5. - -`SampleJUnit5ApplicationTests` makes a call to a very simple service and produces three -documentation snippets. - -One showing how to make a request using cURL: - -include::{snippets}/sample/curl-request.adoc[] - -One showing the HTTP request: - -include::{snippets}/sample/http-request.adoc[] - -And one showing the HTTP response: - -include::{snippets}/sample/http-response.adoc[] diff --git a/samples/junit5/src/main/java/com/example/junit5/SampleJUnit5Application.java b/samples/junit5/src/main/java/com/example/junit5/SampleJUnit5Application.java deleted file mode 100644 index fec007f6e..000000000 --- a/samples/junit5/src/main/java/com/example/junit5/SampleJUnit5Application.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2014-2017 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.junit5; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@SpringBootApplication -public class SampleJUnit5Application { - - public static void main(String[] args) { - new SpringApplication(SampleJUnit5Application.class).run(args); - } - - @RestController - private static class SampleController { - - @RequestMapping("/") - public String index() { - return "Hello, World"; - } - - } - -} diff --git a/samples/junit5/src/test/java/com/example/junit5/SampleJUnit5ApplicationTests.java b/samples/junit5/src/test/java/com/example/junit5/SampleJUnit5ApplicationTests.java deleted file mode 100644 index a6e4169d8..000000000 --- a/samples/junit5/src/test/java/com/example/junit5/SampleJUnit5ApplicationTests.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2014-2018 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.junit5; - -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.restdocs.RestDocumentationContextProvider; -import org.springframework.restdocs.RestDocumentationExtension; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -@SpringBootTest -@ExtendWith({RestDocumentationExtension.class, SpringExtension.class}) -public class SampleJUnit5ApplicationTests { - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @BeforeEach - public void setUp(RestDocumentationContextProvider restDocumentation) { - this.mockMvc = MockMvcBuilders.webAppContextSetup(context) - .apply(documentationConfiguration(restDocumentation)).build(); - } - - @Test - public void sample() throws Exception { - this.mockMvc.perform(get("/")) - .andExpect(status().isOk()) - .andDo(document("sample")); - } - -} diff --git a/samples/rest-assured/build.gradle b/samples/rest-assured/build.gradle deleted file mode 100644 index 7d1739e1f..000000000 --- a/samples/rest-assured/build.gradle +++ /dev/null @@ -1,63 +0,0 @@ -plugins { - id "eclipse" - id "java" - id "org.asciidoctor.jvm.convert" version "3.3.2" - id "org.springframework.boot" version "2.6.2" -} - -apply plugin: 'io.spring.dependency-management' - -repositories { - mavenLocal() - maven { url 'https://repo.spring.io/milestone' } - maven { url 'https://repo.spring.io/snapshot' } - mavenCentral() -} - -group = 'com.example' - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -ext { - snippetsDir = file('build/generated-snippets') -} - -ext['spring-restdocs.version'] = '2.0.7.BUILD-SNAPSHOT' - -configurations { - asciidoctorExtensions -} - -dependencies { - asciidoctorExtensions 'org.springframework.restdocs:spring-restdocs-asciidoctor' - - implementation 'org.springframework.boot:spring-boot-starter-web' - - testImplementation 'io.rest-assured:rest-assured' - testImplementation('org.junit.vintage:junit-vintage-engine') { - exclude group: 'org.hamcrest', module: 'hamcrest-core' - } - testImplementation 'org.springframework.boot:spring-boot-starter-test' - testImplementation 'org.springframework.restdocs:spring-restdocs-restassured' -} - -test { - outputs.dir snippetsDir -} - -asciidoctor { - configurations "asciidoctorExtensions" - inputs.dir snippetsDir - dependsOn test -} - -bootJar { - dependsOn asciidoctor - from ("${asciidoctor.outputDir}/html5") { - into 'static/docs' - } -} - -eclipseJdt.onlyIf { false } -cleanEclipseJdt.onlyIf { false } diff --git a/samples/rest-assured/gradle/wrapper/gradle-wrapper.jar b/samples/rest-assured/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 62d4c0535..000000000 Binary files a/samples/rest-assured/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/samples/rest-assured/gradle/wrapper/gradle-wrapper.properties b/samples/rest-assured/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 442d9132e..000000000 --- a/samples/rest-assured/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/samples/rest-assured/gradlew b/samples/rest-assured/gradlew deleted file mode 100755 index fbd7c5158..000000000 --- a/samples/rest-assured/gradlew +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/samples/rest-assured/gradlew.bat b/samples/rest-assured/gradlew.bat deleted file mode 100644 index 5093609d5..000000000 --- a/samples/rest-assured/gradlew.bat +++ /dev/null @@ -1,104 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/samples/rest-assured/settings.gradle b/samples/rest-assured/settings.gradle deleted file mode 100644 index e69de29bb..000000000 diff --git a/samples/rest-assured/src/docs/asciidoc/index.adoc b/samples/rest-assured/src/docs/asciidoc/index.adoc deleted file mode 100644 index f89aeb6e1..000000000 --- a/samples/rest-assured/src/docs/asciidoc/index.adoc +++ /dev/null @@ -1,26 +0,0 @@ -= Spring REST Docs REST Assured Sample -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs - -Sample application demonstrating how to use Spring REST Docs with REST Assured. - -`SampleRestAssuredApplicationTests` makes a call to a very simple service. The service -that is being tested is running on a random port on `localhost`. The tests make use of a -preprocessor to modify the request so that it appears to have been sent to -`https://api.example.com`. If your service includes URIs in its responses, for example -because it uses hypermedia, similar preprocessing can be applied to the response before -it is documented. - -Three snippets are produced. One showing how to make a request using cURL: - -include::{snippets}/sample/curl-request.adoc[] - -One showing the HTTP request: - -include::{snippets}/sample/http-request.adoc[] - -And one showing the HTTP response: - -include::{snippets}/sample/http-response.adoc[] \ No newline at end of file diff --git a/samples/rest-assured/src/main/java/com/example/restassured/SampleRestAssuredApplication.java b/samples/rest-assured/src/main/java/com/example/restassured/SampleRestAssuredApplication.java deleted file mode 100644 index 1c127db72..000000000 --- a/samples/rest-assured/src/main/java/com/example/restassured/SampleRestAssuredApplication.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2014-2016 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.restassured; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@SpringBootApplication -public class SampleRestAssuredApplication { - - public static void main(String[] args) { - new SpringApplication(SampleRestAssuredApplication.class).run(args); - } - - @RestController - private static class SampleController { - - @RequestMapping("/") - public String index() { - return "Hello, World"; - } - - } - -} diff --git a/samples/rest-assured/src/test/java/com/example/restassured/SampleRestAssuredApplicationTests.java b/samples/rest-assured/src/test/java/com/example/restassured/SampleRestAssuredApplicationTests.java deleted file mode 100644 index cce7beb6c..000000000 --- a/samples/rest-assured/src/test/java/com/example/restassured/SampleRestAssuredApplicationTests.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2014-2022 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.restassured; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.CoreMatchers.is; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyUris; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import io.restassured.builder.RequestSpecBuilder; -import io.restassured.specification.RequestSpecification; - -@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) -@RunWith(SpringJUnit4ClassRunner.class) -public class SampleRestAssuredApplicationTests { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - private RequestSpecification documentationSpec; - - @LocalServerPort - private int port; - - @Before - public void setUp() { - this.documentationSpec = new RequestSpecBuilder() - .addFilter(documentationConfiguration(restDocumentation)).build(); - } - - @Test - public void sample() { - given(this.documentationSpec) - .accept("text/plain") - .filter(document("sample", - preprocessRequest(modifyUris() - .scheme("https") - .host("api.example.com") - .removePort()))) - .when() - .port(this.port) - .get("/") - .then() - .assertThat().statusCode(is(200)); - } - -} diff --git a/samples/rest-notes-slate/README.md b/samples/rest-notes-slate/README.md deleted file mode 100644 index df99663ca..000000000 --- a/samples/rest-notes-slate/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# REST Notes Slate - -This sample shows how to document a RESTful API using Spring REST Docs and [Slate][1]. -The sample can be built with Gradle, but requires Ruby and the `bundler` gem to -be installed. - -## Quickstart - -``` -./gradlew build -open build/docs/api-guide.html -``` - -## Details - -The bulk of the documentation is written in Markdown in the file named -[slate/source/api-guide.md.erb][2]. When the documentation is built, snippets generated by -Spring REST Docs in the [ApiDocumentation][3] tests are incorporated into this -documentation by [ERB][4]. The combined Markdown document is then turned into HTML. - -[1]: https://github.com/lord/slate -[2]: slate/source/api-guide.html.md.erb -[3]: src/test/java/com/example/notes/ApiDocumentation.java -[4]: https://ruby-doc.org/stdlib-2.2.3/libdoc/erb/rdoc/ERB.html \ No newline at end of file diff --git a/samples/rest-notes-slate/build.gradle b/samples/rest-notes-slate/build.gradle deleted file mode 100644 index 7791ba744..000000000 --- a/samples/rest-notes-slate/build.gradle +++ /dev/null @@ -1,64 +0,0 @@ -plugins { - id "eclipse" - id "java" - id "org.springframework.boot" version "2.6.2" -} - -apply plugin: 'io.spring.dependency-management' - -repositories { - mavenLocal() - maven { url 'https://repo.spring.io/milestone' } - maven { url 'https://repo.spring.io/snapshot' } - mavenCentral() -} - -group = 'com.example' - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -ext { - snippetsDir = file('build/generated-snippets') -} - -ext['spring-restdocs.version'] = '2.0.7.BUILD-SNAPSHOT' - -dependencies { - implementation 'org.springframework.boot:spring-boot-starter-data-jpa' - implementation 'org.springframework.boot:spring-boot-starter-data-rest' - - runtimeOnly 'com.h2database:h2' - runtimeOnly 'org.atteo:evo-inflector:1.2.1' - - testImplementation 'com.jayway.jsonpath:json-path' - testImplementation('org.junit.vintage:junit-vintage-engine') { - exclude group: 'org.hamcrest', module: 'hamcrest-core' - } - testImplementation 'org.springframework.boot:spring-boot-starter-test' - testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' -} - -test { - outputs.dir snippetsDir -} - -task(bundleInstall, type: Exec) { - workingDir file('slate') - executable 'bundle' - args 'install' -} - -task(slate, type: Exec) { - dependsOn 'bundleInstall', 'test' - workingDir file('slate') - executable 'bundle' - args 'exec', 'middleman', 'build' -} - -build { - dependsOn 'slate' -} - -eclipseJdt.onlyIf { false } -cleanEclipseJdt.onlyIf { false } diff --git a/samples/rest-notes-slate/gradle/wrapper/gradle-wrapper.jar b/samples/rest-notes-slate/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index e708b1c02..000000000 Binary files a/samples/rest-notes-slate/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/samples/rest-notes-slate/gradle/wrapper/gradle-wrapper.properties b/samples/rest-notes-slate/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 442d9132e..000000000 --- a/samples/rest-notes-slate/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/samples/rest-notes-slate/gradlew b/samples/rest-notes-slate/gradlew deleted file mode 100755 index 4f906e0c8..000000000 --- a/samples/rest-notes-slate/gradlew +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/samples/rest-notes-slate/gradlew.bat b/samples/rest-notes-slate/gradlew.bat deleted file mode 100644 index 107acd32c..000000000 --- a/samples/rest-notes-slate/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/samples/rest-notes-slate/settings.gradle b/samples/rest-notes-slate/settings.gradle deleted file mode 100644 index e69de29bb..000000000 diff --git a/samples/rest-notes-slate/slate/.dockerignore b/samples/rest-notes-slate/slate/.dockerignore deleted file mode 100644 index f64301752..000000000 --- a/samples/rest-notes-slate/slate/.dockerignore +++ /dev/null @@ -1,12 +0,0 @@ -.git/ -.github/ -build/ -.editorconfig -.gitattributes -.gitignore -CHANGELOG.md -CODE_OF_CONDUCT.md -deploy.sh -font-selection.json -README.md -Vagrantfile \ No newline at end of file diff --git a/samples/rest-notes-slate/slate/.gitignore b/samples/rest-notes-slate/slate/.gitignore deleted file mode 100644 index 1d5d08dd2..000000000 --- a/samples/rest-notes-slate/slate/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -*.gem -*.rbc -.bundle -.config -coverage -InstalledFiles -lib/bundler/man -pkg -rdoc -spec/reports -test/tmp -test/version_tmp -tmp -*.DS_STORE -build/ -.cache -.vagrant -.sass-cache - -# YARD artifacts -.yardoc -_yardoc -doc/ -.idea/ - -# Vagrant artifacts -ubuntu-*-console.log diff --git a/samples/rest-notes-slate/slate/CHANGELOG.md b/samples/rest-notes-slate/slate/CHANGELOG.md deleted file mode 100644 index 568509d6b..000000000 --- a/samples/rest-notes-slate/slate/CHANGELOG.md +++ /dev/null @@ -1,307 +0,0 @@ -# Changelog - -## Version 2.12.0 - -*November 04, 2021* - -* Bump nokogiri from 1.12.3 to 1.12.5 -* Bump ffi from 1.15.0 to 1.15.4 -* Bump rouge from 3.26.0 to 3.26.1 -* Bump middleman from 4.4.0 to 4.4.2 -* Remove unnecessary files from docker images - -## Version 2.11.0 - -*August 12, 2021* - -* __[Security]__ Bump addressable transitive dependency from 2.7.0 to 2.8.0 -* Support specifying custom meta tags in YAML front-matter -* Bump nokogiri from 1.11.3 to 1.12.3 (minimum supported version is 1.11.4) -* Bump middleman-autoprefixer from 2.10.1 to 3.0.0 -* Bump jquery from 3.5.1 to 3.6.0 -* Bump middleman from [`d180ca3`](https://github.com/middleman/middleman/commit/d180ca337202873f2601310c74ba2b6b4cf063ec) to 4.4.0 - -## Version 2.10.0 - -*April 13, 2021* - -* Add support for Ruby 3.0 (thanks @shaun-scale) -* Add requirement for Git on installing dependencies -* Bump nokogiri from 1.11.2 to 1.11.3 -* Bump middleman from 4.3.11 to [`d180ca3`](https://github.com/middleman/middleman/commit/d180ca337202873f2601310c74ba2b6b4cf063ec) - -## Version 2.9.2 - -*March 30, 2021* - -* __[Security]__ Bump kramdown from 2.3.0 to 2.3.1 -* Bump nokogiri from 1.11.1 to 1.11.2 - -## Version 2.9.1 - -*February 27, 2021* - -* Fix Slate language tabs not working if localStorage is disabled - -## Version 2.9.0 - -*January 19, 2021* - -* __Drop support for Ruby 2.3 and 2.4__ -* __[Security]__ Bump nokogiri from 1.10.10 to 1.11.1 -* __[Security]__ Bump redcarpet from 3.5.0 to 3.5.1 -* Specify slate is not supported on Ruby 3.x -* Bump rouge from 3.24.0 to 3.26.0 - -## Version 2.8.0 - -*October 27, 2020* - -* Remove last trailing newline when using the copy code button -* Rework docker image and make available at slatedocs/slate -* Improve Dockerfile layout to improve caching (thanks @micvbang) -* Bump rouge from 3.20 to 3.24 -* Bump nokogiri from 1.10.9 to 1.10.10 -* Bump middleman from 4.3.8 to 4.3.11 -* Bump lunr.js from 2.3.8 to 2.3.9 - -## Version 2.7.1 - -*August 13, 2020* - -* __[security]__ Bumped middleman from 4.3.7 to 4.3.8 - -_Note_: Slate uses redcarpet, not kramdown, for rendering markdown to HTML, and so was unaffected by the security vulnerability in middleman. -If you have changed slate to use kramdown, and with GFM, you may need to install the `kramdown-parser-gfm` gem. - -## Version 2.7.0 - -*June 21, 2020* - -* __[security]__ Bumped rack in Gemfile.lock from 2.2.2 to 2.2.3 -* Bumped bundled jQuery from 3.2.1 to 3.5.1 -* Bumped bundled lunr from 0.5.7 to 2.3.8 -* Bumped imagesloaded from 3.1.8 to 4.1.4 -* Bumped rouge from 3.17.0 to 3.20.0 -* Bumped redcarpet from 3.4.0 to 3.5.0 -* Fix color of highlighted code being unreadable when printing page -* Add clipboard icon for "Copy to Clipboard" functionality to code boxes (see note below) -* Fix handling of ToC selectors that contain punctutation (thanks @gruis) -* Fix language bar truncating languages that overflow screen width -* Strip HTML tags from ToC title before displaying it in title bar in JS (backup to stripping done in Ruby code) (thanks @atic) - -To enable the new clipboard icon, you need to add `code_clipboard: true` to the frontmatter of source/index.html.md. -See [this line](https://github.com/slatedocs/slate/blame/main/source/index.html.md#L19) for an example of usage. - -## Version 2.6.1 - -*May 30, 2020* - -* __[security]__ update child dependency activesupport in Gemfile.lock to 5.4.2.3 -* Update Middleman in Gemfile.lock to 4.3.7 -* Replace Travis-CI with GitHub actions for continuous integration -* Replace Spectrum with GitHub discussions - -## Version 2.6.0 - -*May 18, 2020* - -__Note__: 2.5.0 was "pulled" due to a breaking bug discovered after release. It is recommended to skip it, and move straight to 2.6.0. - -* Fix large whitespace gap in middle column for sections with codeblocks -* Fix highlighted code elements having a different background than rest of code block -* Change JSON keys to have a different font color than their values -* Disable asset hashing for woff and woff2 elements due to middleman bug breaking woff2 asset hashing in general -* Move Dockerfile to Debian from Alpine -* Converted repo to a [GitHub template](https://help.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-template-repository) -* Update sassc to 2.3.0 in Gemfile.lock - -## Version 2.5.0 - -*May 8, 2020* - -* __[security]__ update nokogiri to ~> 1.10.8 -* Update links in example docs to https://github.com/slatedocs/slate from https://github.com/lord/slate -* Update LICENSE to include full Apache 2.0 text -* Test slate against Ruby 2.5 and 2.6 on Travis-CI -* Update Vagrantfile to use Ubuntu 18.04 (thanks @bradthurber) -* Parse arguments and flags for deploy.sh on script start, instead of potentially after building source files -* Install nodejs inside Vagrantfile (thanks @fernandoaguilar) -* Add Dockerfile for running slate (thanks @redhatxl) -* update middleman-syntax and rouge to ~>3.2 -* update middleman to 4.3.6 - -## Version 2.4.0 - -*October 19, 2019* - -- Move repository from lord/slate to slatedocs/slate -- Fix documentation to point at new repo link, thanks to [Arun](https://github.com/slash-arun), [Gustavo Gawryszewski](https://github.com/gawry), and [Daniel Korbit](https://github.com/danielkorbit) -- Update `nokogiri` to 1.10.4 -- Update `ffi` in `Gemfile.lock` to fix security warnings, thanks to [Grey Baker](https://github.com/greysteil) and [jakemack](https://github.com/jakemack) -- Update `rack` to 2.0.7 in `Gemfile.lock` to fix security warnings, thanks to [Grey Baker](https://github.com/greysteil) and [jakemack](https://github.com/jakemack) -- Update middleman to `4.3` and relax constraints on middleman related gems, thanks to [jakemack](https://github.com/jakemack) -- Add sass gem, thanks to [jakemack](https://github.com/jakemack) -- Activate `asset_cache` in middleman to improve cacheability of static files, thanks to [Sam Gilman](https://github.com/thenengah) -- Update to using bundler 2 for `Gemfile.lock`, thanks to [jakemack](https://github.com/jakemack) - -## Version 2.3.1 - -*July 5, 2018* - -- Update `sprockets` in `Gemfile.lock` to fix security warnings - -## Version 2.3 - -*July 5, 2018* - -- Allows strikethrough in markdown by default. -- Upgrades jQuery to 3.2.1, thanks to [Tomi Takussaari](https://github.com/TomiTakussaari) -- Fixes invalid HTML in `layout.erb`, thanks to [Eric Scouten](https://github.com/scouten) for pointing out -- Hopefully fixes Vagrant memory issues, thanks to [Petter Blomberg](https://github.com/p-blomberg) for the suggestion -- Cleans HTML in headers before setting `document.title`, thanks to [Dan Levy](https://github.com/justsml) -- Allows trailing whitespace in markdown files, thanks to [Samuel Cousin](https://github.com/kuzyn) -- Fixes pushState/replaceState problems with scrolling not changing the document hash, thanks to [Andrey Fedorov](https://github.com/anfedorov) -- Removes some outdated examples, thanks [@al-tr](https://github.com/al-tr), [Jerome Dahdah](https://github.com/jdahdah), and [Ricardo Castro](https://github.com/mccricardo) -- Fixes `nav-padding` bug, thanks [Jerome Dahdah](https://github.com/jdahdah) -- Code style fixes thanks to [Sebastian Zaremba](https://github.com/vassyz) -- Nokogiri version bump thanks to [Grey Baker](https://github.com/greysteil) -- Fix to default `index.md` text thanks to [Nick Busey](https://github.com/NickBusey) - -Thanks to everyone who contributed to this release! - -## Version 2.2 - -*January 19, 2018* - -- Fixes bugs with some non-roman languages not generating unique headers -- Adds editorconfig, thanks to [Jay Thomas](https://github.com/jaythomas) -- Adds optional `NestingUniqueHeadCounter`, thanks to [Vladimir Morozov](https://github.com/greenhost87) -- Small fixes to typos and language, thx [Emir Ribić](https://github.com/ribice), [Gregor Martynus](https://github.com/gr2m), and [Martius](https://github.com/martiuslim)! -- Adds links to Spectrum chat for questions in README and ISSUE_TEMPLATE - -## Version 2.1 - -*October 30, 2017* - -- Right-to-left text stylesheet option, thanks to [Mohammad Hossein Rabiee](https://github.com/mhrabiee) -- Fix for HTML5 history state bug, thanks to [Zach Toolson](https://github.com/ztoolson) -- Small styling changes, typo fixes, small bug fixes from [Marian Friedmann](https://github.com/rnarian), [Ben Wilhelm](https://github.com/benwilhelm), [Fouad Matin](https://github.com/fouad), [Nicolas Bonduel](https://github.com/NicolasBonduel), [Christian Oliff](https://github.com/coliff) - -Thanks to everyone who submitted PRs for this version! - -## Version 2.0 - -*July 17, 2017* - -- All-new statically generated table of contents - - Should be much faster loading and scrolling for large pages - - Smaller Javascript file sizes - - Avoids the problem with the last link in the ToC not ever highlighting if the section was shorter than the page - - Fixes control-click not opening in a new page - - Automatically updates the HTML title as you scroll -- Updated design - - New default colors! - - New spacings and sizes! - - System-default typefaces, just like GitHub -- Added search input delay on large corpuses to reduce lag -- We even bumped the major version cause hey, why not? -- Various small bug fixes - -Thanks to everyone who helped debug or wrote code for this version! It was a serious community effort, and I couldn't have done it alone. - -## Version 1.5 - -*February 23, 2017* - -- Add [multiple tabs per programming language](https://github.com/lord/slate/wiki/Multiple-language-tabs-per-programming-language) feature -- Upgrade Middleman to add Ruby 1.4.0 compatibility -- Switch default code highlighting color scheme to better highlight JSON -- Various small typo and bug fixes - -## Version 1.4 - -*November 24, 2016* - -- Upgrade Middleman and Rouge gems, should hopefully solve a number of bugs -- Update some links in README -- Fix broken Vagrant startup script -- Fix some problems with deploy.sh help message -- Fix bug with language tabs not hiding properly if no error -- Add `!default` to SASS variables -- Fix bug with logo margin -- Bump tested Ruby versions in .travis.yml - -## Version 1.3.3 - -*June 11, 2016* - -Documentation and example changes. - -## Version 1.3.2 - -*February 3, 2016* - -A small bugfix for slightly incorrect background colors on code samples in some cases. - -## Version 1.3.1 - -*January 31, 2016* - -A small bugfix for incorrect whitespace in code blocks. - -## Version 1.3 - -*January 27, 2016* - -We've upgraded Middleman and a number of other dependencies, which should fix quite a few bugs. - -Instead of `rake build` and `rake deploy`, you should now run `bundle exec middleman build --clean` to build your server, and `./deploy.sh` to deploy it to Github Pages. - -## Version 1.2 - -*June 20, 2015* - -**Fixes:** - -- Remove crash on invalid languages -- Update Tocify to scroll to the highlighted header in the Table of Contents -- Fix variable leak and update search algorithms -- Update Python examples to be valid Python -- Update gems -- More misc. bugfixes of Javascript errors -- Add Dockerfile -- Remove unused gems -- Optimize images, fonts, and generated asset files -- Add chinese font support -- Remove RedCarpet header ID patch -- Update language tabs to not disturb existing query strings - -## Version 1.1 - -*July 27, 2014* - -**Fixes:** - -- Finally, a fix for the redcarpet upgrade bug - -## Version 1.0 - -*July 2, 2014* - -[View Issues](https://github.com/tripit/slate/issues?milestone=1&state=closed) - -**Features:** - -- Responsive designs for phones and tablets -- Started tagging versions - -**Fixes:** - -- Fixed 'unrecognized expression' error -- Fixed #undefined hash bug -- Fixed bug where the current language tab would be unselected -- Fixed bug where tocify wouldn't highlight the current section while searching -- Fixed bug where ids of header tags would have special characters that caused problems -- Updated layout so that pages with disabled search wouldn't load search.js -- Cleaned up Javascript diff --git a/samples/rest-notes-slate/slate/Dockerfile b/samples/rest-notes-slate/slate/Dockerfile deleted file mode 100644 index 504da654d..000000000 --- a/samples/rest-notes-slate/slate/Dockerfile +++ /dev/null @@ -1,29 +0,0 @@ -FROM ruby:2.6-slim - -WORKDIR /srv/slate - -VOLUME /srv/slate/build -VOLUME /srv/slate/source - -EXPOSE 4567 - -COPY Gemfile . -COPY Gemfile.lock . - -RUN apt-get update \ - && apt-get install -y --no-install-recommends \ - build-essential \ - git \ - nodejs \ - && gem install bundler \ - && bundle install \ - && apt-get remove -y build-essential git \ - && apt-get autoremove -y \ - && rm -rf /var/lib/apt/lists/* - -COPY . /srv/slate - -RUN chmod +x /srv/slate/slate.sh - -ENTRYPOINT ["/srv/slate/slate.sh"] -CMD ["build"] diff --git a/samples/rest-notes-slate/slate/Gemfile b/samples/rest-notes-slate/slate/Gemfile deleted file mode 100644 index 3b8c130da..000000000 --- a/samples/rest-notes-slate/slate/Gemfile +++ /dev/null @@ -1,13 +0,0 @@ -ruby '>= 2.5' -source 'https://rubygems.org' - -# Middleman -gem 'middleman', '~> 4.4' -gem 'middleman-syntax', '~> 3.2' -gem 'middleman-autoprefixer', '~> 3.0' -gem 'middleman-sprockets', '~> 4.1' -gem 'rouge', '~> 3.21' -gem 'redcarpet', '~> 3.5.0' -gem 'nokogiri', '~> 1.12.1' -gem 'sass' -gem 'webrick' diff --git a/samples/rest-notes-slate/slate/Gemfile.lock b/samples/rest-notes-slate/slate/Gemfile.lock deleted file mode 100644 index 18702217d..000000000 --- a/samples/rest-notes-slate/slate/Gemfile.lock +++ /dev/null @@ -1,145 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - activesupport (6.1.4.1) - concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (>= 1.6, < 2) - minitest (>= 5.1) - tzinfo (~> 2.0) - zeitwerk (~> 2.3) - addressable (2.8.0) - public_suffix (>= 2.0.2, < 5.0) - autoprefixer-rails (10.2.5.0) - execjs (< 2.8.0) - backports (3.21.0) - coffee-script (2.4.1) - coffee-script-source - execjs - coffee-script-source (1.12.2) - concurrent-ruby (1.1.9) - contracts (0.13.0) - dotenv (2.7.6) - erubis (2.7.0) - execjs (2.7.0) - fast_blank (1.0.1) - fastimage (2.2.5) - ffi (1.15.4) - haml (5.2.2) - temple (>= 0.8.0) - tilt - hamster (3.0.0) - concurrent-ruby (~> 1.0) - hashie (3.6.0) - i18n (1.6.0) - concurrent-ruby (~> 1.0) - kramdown (2.3.1) - rexml - listen (3.0.8) - rb-fsevent (~> 0.9, >= 0.9.4) - rb-inotify (~> 0.9, >= 0.9.7) - memoist (0.16.2) - middleman (4.4.2) - coffee-script (~> 2.2) - haml (>= 4.0.5) - kramdown (>= 2.3.0) - middleman-cli (= 4.4.2) - middleman-core (= 4.4.2) - middleman-autoprefixer (3.0.0) - autoprefixer-rails (~> 10.0) - middleman-core (>= 4.0.0) - middleman-cli (4.4.2) - thor (>= 0.17.0, < 2.0) - middleman-core (4.4.2) - activesupport (>= 6.1, < 7.0) - addressable (~> 2.4) - backports (~> 3.6) - bundler (~> 2.0) - contracts (~> 0.13.0) - dotenv - erubis - execjs (~> 2.0) - fast_blank - fastimage (~> 2.0) - hamster (~> 3.0) - hashie (~> 3.4) - i18n (~> 1.6.0) - listen (~> 3.0.0) - memoist (~> 0.14) - padrino-helpers (~> 0.15.0) - parallel - rack (>= 1.4.5, < 3) - sassc (~> 2.0) - servolux - tilt (~> 2.0.9) - toml - uglifier (~> 3.0) - webrick - middleman-sprockets (4.1.1) - middleman-core (~> 4.0) - sprockets (>= 3.0) - middleman-syntax (3.2.0) - middleman-core (>= 3.2) - rouge (~> 3.2) - mini_portile2 (2.6.1) - minitest (5.14.4) - nokogiri (1.12.5) - mini_portile2 (~> 2.6.1) - racc (~> 1.4) - padrino-helpers (0.15.1) - i18n (>= 0.6.7, < 2) - padrino-support (= 0.15.1) - tilt (>= 1.4.1, < 3) - padrino-support (0.15.1) - parallel (1.21.0) - parslet (2.0.0) - public_suffix (4.0.6) - racc (1.5.2) - rack (2.2.3) - rb-fsevent (0.11.0) - rb-inotify (0.10.1) - ffi (~> 1.0) - redcarpet (3.5.1) - rexml (3.2.5) - rouge (3.26.1) - sass (3.7.4) - sass-listen (~> 4.0.0) - sass-listen (4.0.0) - rb-fsevent (~> 0.9, >= 0.9.4) - rb-inotify (~> 0.9, >= 0.9.7) - sassc (2.4.0) - ffi (~> 1.9) - servolux (0.13.0) - sprockets (3.7.2) - concurrent-ruby (~> 1.0) - rack (> 1, < 3) - temple (0.8.2) - thor (1.1.0) - tilt (2.0.10) - toml (0.3.0) - parslet (>= 1.8.0, < 3.0.0) - tzinfo (2.0.4) - concurrent-ruby (~> 1.0) - uglifier (3.2.0) - execjs (>= 0.3.0, < 3) - webrick (1.7.0) - zeitwerk (2.5.1) - -PLATFORMS - ruby - -DEPENDENCIES - middleman (~> 4.4) - middleman-autoprefixer (~> 3.0) - middleman-sprockets (~> 4.1) - middleman-syntax (~> 3.2) - nokogiri (~> 1.12.1) - redcarpet (~> 3.5.0) - rouge (~> 3.21) - sass - webrick - -RUBY VERSION - ruby 2.7.2p137 - -BUNDLED WITH - 2.2.22 diff --git a/samples/rest-notes-slate/slate/LICENSE b/samples/rest-notes-slate/slate/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/samples/rest-notes-slate/slate/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) 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 - - (d) 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. - - 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 - - APPENDIX: 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. diff --git a/samples/rest-notes-slate/slate/README.md b/samples/rest-notes-slate/slate/README.md deleted file mode 100644 index 1560f2143..000000000 --- a/samples/rest-notes-slate/slate/README.md +++ /dev/null @@ -1,82 +0,0 @@ -

- Slate: API Documentation Generator -
- Build Status - Docker Version -

- -

Slate helps you create beautiful, intelligent, responsive API documentation.

- -

Screenshot of Example Documentation created with Slate

- -

The example above was created with Slate. Check it out at slatedocs.github.io/slate.

- -Features ------------- - -* **Clean, intuitive design** — With Slate, the description of your API is on the left side of your documentation, and all the code examples are on the right side. Inspired by [Stripe's](https://stripe.com/docs/api) and [PayPal's](https://developer.paypal.com/webapps/developer/docs/api/) API docs. Slate is responsive, so it looks great on tablets, phones, and even in print. - -* **Everything on a single page** — Gone are the days when your users had to search through a million pages to find what they wanted. Slate puts the entire documentation on a single page. We haven't sacrificed linkability, though. As you scroll, your browser's hash will update to the nearest header, so linking to a particular point in the documentation is still natural and easy. - -* **Slate is just Markdown** — When you write docs with Slate, you're just writing Markdown, which makes it simple to edit and understand. Everything is written in Markdown — even the code samples are just Markdown code blocks. - -* **Write code samples in multiple languages** — If your API has bindings in multiple programming languages, you can easily put in tabs to switch between them. In your document, you'll distinguish different languages by specifying the language name at the top of each code block, just like with GitHub Flavored Markdown. - -* **Out-of-the-box syntax highlighting** for [over 100 languages](https://github.com/rouge-ruby/rouge/wiki/List-of-supported-languages-and-lexers), no configuration required. - -* **Automatic, smoothly scrolling table of contents** on the far left of the page. As you scroll, it displays your current position in the document. It's fast, too. We're using Slate at TripIt to build documentation for our new API, where our table of contents has over 180 entries. We've made sure that the performance remains excellent, even for larger documents. - -* **Let your users update your documentation for you** — By default, your Slate-generated documentation is hosted in a public GitHub repository. Not only does this mean you get free hosting for your docs with GitHub Pages, but it also makes it simple for other developers to make pull requests to your docs if they find typos or other problems. Of course, if you don't want to use GitHub, you're also welcome to host your docs elsewhere. - -* **RTL Support** Full right-to-left layout for RTL languages such as Arabic, Persian (Farsi), Hebrew etc. - -Getting started with Slate is super easy! Simply press the green "use this template" button above and follow the instructions below. Or, if you'd like to check out what Slate is capable of, take a look at the [sample docs](https://slatedocs.github.io/slate/). - -Getting Started with Slate ------------------------------- - -To get started with Slate, please check out the [Getting Started](https://github.com/slatedocs/slate/wiki#getting-started) -section in our [wiki](https://github.com/slatedocs/slate/wiki). - -We support running Slate in three different ways: -* [Natively](https://github.com/slatedocs/slate/wiki/Using-Slate-Natively) -* [Using Vagrant](https://github.com/slatedocs/slate/wiki/Using-Slate-in-Vagrant) -* [Using Docker](https://github.com/slatedocs/slate/wiki/Using-Slate-in-Docker) - -Companies Using Slate ---------------------------------- - -* [NASA](https://api.nasa.gov) -* [Sony](http://developers.cimediacloud.com) -* [Best Buy](https://bestbuyapis.github.io/api-documentation/) -* [Travis-CI](https://docs.travis-ci.com/api/) -* [Greenhouse](https://developers.greenhouse.io/harvest.html) -* [WooCommerce](http://woocommerce.github.io/woocommerce-rest-api-docs/) -* [Dwolla](https://docs.dwolla.com/) -* [Clearbit](https://clearbit.com/docs) -* [Coinbase](https://developers.coinbase.com/api) -* [Parrot Drones](http://developer.parrot.com/docs/bebop/) -* [CoinAPI](https://docs.coinapi.io/) - -You can view more in [the list on the wiki](https://github.com/slatedocs/slate/wiki/Slate-in-the-Wild). - -Questions? Need Help? Found a bug? --------------------- - -If you've got questions about setup, deploying, special feature implementation in your fork, or just want to chat with the developer, please feel free to [start a thread in our Discussions tab](https://github.com/slatedocs/slate/discussions)! - -Found a bug with upstream Slate? Go ahead and [submit an issue](https://github.com/slatedocs/slate/issues). And, of course, feel free to submit pull requests with bug fixes or changes to the `dev` branch. - -Contributors --------------------- - -Slate was built by [Robert Lord](https://lord.io) while at [TripIt](https://www.tripit.com/). The project is now maintained by [Matthew Peveler](https://github.com/MasterOdin) and [Mike Ralphson](https://github.com/MikeRalphson). - -Thanks to the following people who have submitted major pull requests: - -- [@chrissrogers](https://github.com/chrissrogers) -- [@bootstraponline](https://github.com/bootstraponline) -- [@realityking](https://github.com/realityking) -- [@cvkef](https://github.com/cvkef) - -Also, thanks to [Sauce Labs](http://saucelabs.com) for sponsoring the development of the responsive styles. diff --git a/samples/rest-notes-slate/slate/Vagrantfile b/samples/rest-notes-slate/slate/Vagrantfile deleted file mode 100644 index 200839d02..000000000 --- a/samples/rest-notes-slate/slate/Vagrantfile +++ /dev/null @@ -1,47 +0,0 @@ -Vagrant.configure(2) do |config| - config.vm.box = "ubuntu/bionic64" - config.vm.network :forwarded_port, guest: 4567, host: 4567 - config.vm.provider "virtualbox" do |vb| - vb.memory = "2048" - end - - config.vm.provision "bootstrap", - type: "shell", - inline: <<-SHELL - # add nodejs v12 repository - curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - - - sudo apt-get update - sudo apt-get install -yq ruby ruby-dev - sudo apt-get install -yq pkg-config build-essential nodejs git libxml2-dev libxslt-dev - sudo apt-get autoremove -yq - gem install --no-ri --no-rdoc bundler - SHELL - - # add the local user git config to the vm - config.vm.provision "file", source: "~/.gitconfig", destination: ".gitconfig" - - config.vm.provision "install", - type: "shell", - privileged: false, - inline: <<-SHELL - echo "==============================================" - echo "Installing app dependencies" - cd /vagrant - sudo gem install bundler -v "$(grep -A 1 "BUNDLED WITH" Gemfile.lock | tail -n 1)" - bundle config build.nokogiri --use-system-libraries - bundle install - SHELL - - config.vm.provision "run", - type: "shell", - privileged: false, - run: "always", - inline: <<-SHELL - echo "==============================================" - echo "Starting up middleman at http://localhost:4567" - echo "If it does not come up, check the ~/middleman.log file for any error messages" - cd /vagrant - bundle exec middleman server --watcher-force-polling --watcher-latency=1 &> ~/middleman.log & - SHELL -end diff --git a/samples/rest-notes-slate/slate/config.rb b/samples/rest-notes-slate/slate/config.rb deleted file mode 100644 index 6f8b677f6..000000000 --- a/samples/rest-notes-slate/slate/config.rb +++ /dev/null @@ -1,63 +0,0 @@ -# Unique header generation -require './lib/unique_head.rb' - -# Markdown -set :markdown_engine, :redcarpet -set :markdown, - fenced_code_blocks: true, - smartypants: true, - disable_indented_code_blocks: true, - prettify: true, - strikethrough: true, - tables: true, - with_toc_data: true, - no_intra_emphasis: true, - renderer: UniqueHeadCounter - -# Assets -set :css_dir, 'stylesheets' -set :js_dir, 'javascripts' -set :images_dir, 'images' -set :fonts_dir, 'fonts' - -# Activate the syntax highlighter -activate :syntax -ready do - require './lib/monokai_sublime_slate.rb' - require './lib/multilang.rb' -end - -activate :sprockets - -activate :autoprefixer do |config| - config.browsers = ['last 2 version', 'Firefox ESR'] - config.cascade = false - config.inline = true -end - -# Github pages require relative links -activate :relative_assets -set :relative_links, true - -# Build Configuration -configure :build do - # We do want to hash woff and woff2 as there's a bug where woff2 will use - # woff asset hash which breaks things. Trying to use a combination of ignore and - # rewrite_ignore does not work as it conflicts weirdly with relative_assets. Disabling - # the .woff2 extension only does not work as .woff will still activate it so have to - # have both. See https://github.com/slatedocs/slate/issues/1171 for more details. - activate :asset_hash, :exts => app.config[:asset_extensions] - %w[.woff .woff2] - # If you're having trouble with Middleman hanging, commenting - # out the following two lines has been known to help - activate :minify_css - activate :minify_javascript - # activate :gzip -end - -# Deploy Configuration -# If you want Middleman to listen on a different port, you can set that below -set :port, 4567 - -helpers do - require './lib/toc_data.rb' -end diff --git a/samples/rest-notes-slate/slate/deploy.sh b/samples/rest-notes-slate/slate/deploy.sh deleted file mode 100755 index 9dbd7db9c..000000000 --- a/samples/rest-notes-slate/slate/deploy.sh +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env bash -set -o errexit #abort if any command fails -me=$(basename "$0") - -help_message="\ -Usage: $me [-c FILE] [] -Deploy generated files to a git branch. - -Options: - - -h, --help Show this help information. - -v, --verbose Increase verbosity. Useful for debugging. - -e, --allow-empty Allow deployment of an empty directory. - -m, --message MESSAGE Specify the message used when committing on the - deploy branch. - -n, --no-hash Don't append the source commit's hash to the deploy - commit's message. - --source-only Only build but not push - --push-only Only push but not build -" - - -run_build() { - bundle exec middleman build --clean -} - -parse_args() { - # Set args from a local environment file. - if [ -e ".env" ]; then - source .env - fi - - # Parse arg flags - # If something is exposed as an environment variable, set/overwrite it - # here. Otherwise, set/overwrite the internal variable instead. - while : ; do - if [[ $1 = "-h" || $1 = "--help" ]]; then - echo "$help_message" - exit 0 - elif [[ $1 = "-v" || $1 = "--verbose" ]]; then - verbose=true - shift - elif [[ $1 = "-e" || $1 = "--allow-empty" ]]; then - allow_empty=true - shift - elif [[ ( $1 = "-m" || $1 = "--message" ) && -n $2 ]]; then - commit_message=$2 - shift 2 - elif [[ $1 = "-n" || $1 = "--no-hash" ]]; then - GIT_DEPLOY_APPEND_HASH=false - shift - elif [[ $1 = "--source-only" ]]; then - source_only=true - shift - elif [[ $1 = "--push-only" ]]; then - push_only=true - shift - else - break - fi - done - - if [ ${source_only} ] && [ ${push_only} ]; then - >&2 echo "You can only specify one of --source-only or --push-only" - exit 1 - fi - - # Set internal option vars from the environment and arg flags. All internal - # vars should be declared here, with sane defaults if applicable. - - # Source directory & target branch. - deploy_directory=build - deploy_branch=gh-pages - - #if no user identity is already set in the current git environment, use this: - default_username=${GIT_DEPLOY_USERNAME:-deploy.sh} - default_email=${GIT_DEPLOY_EMAIL:-} - - #repository to deploy to. must be readable and writable. - repo=origin - - #append commit hash to the end of message by default - append_hash=${GIT_DEPLOY_APPEND_HASH:-true} -} - -main() { - enable_expanded_output - - if ! git diff --exit-code --quiet --cached; then - echo Aborting due to uncommitted changes in the index >&2 - return 1 - fi - - commit_title=`git log -n 1 --format="%s" HEAD` - commit_hash=` git log -n 1 --format="%H" HEAD` - - #default commit message uses last title if a custom one is not supplied - if [[ -z $commit_message ]]; then - commit_message="publish: $commit_title" - fi - - #append hash to commit message unless no hash flag was found - if [ $append_hash = true ]; then - commit_message="$commit_message"$'\n\n'"generated from commit $commit_hash" - fi - - previous_branch=`git rev-parse --abbrev-ref HEAD` - - if [ ! -d "$deploy_directory" ]; then - echo "Deploy directory '$deploy_directory' does not exist. Aborting." >&2 - return 1 - fi - - # must use short form of flag in ls for compatibility with macOS and BSD - if [[ -z `ls -A "$deploy_directory" 2> /dev/null` && -z $allow_empty ]]; then - echo "Deploy directory '$deploy_directory' is empty. Aborting. If you're sure you want to deploy an empty tree, use the --allow-empty / -e flag." >&2 - return 1 - fi - - if git ls-remote --exit-code $repo "refs/heads/$deploy_branch" ; then - # deploy_branch exists in $repo; make sure we have the latest version - - disable_expanded_output - git fetch --force $repo $deploy_branch:$deploy_branch - enable_expanded_output - fi - - # check if deploy_branch exists locally - if git show-ref --verify --quiet "refs/heads/$deploy_branch" - then incremental_deploy - else initial_deploy - fi - - restore_head -} - -initial_deploy() { - git --work-tree "$deploy_directory" checkout --orphan $deploy_branch - git --work-tree "$deploy_directory" add --all - commit+push -} - -incremental_deploy() { - #make deploy_branch the current branch - git symbolic-ref HEAD refs/heads/$deploy_branch - #put the previously committed contents of deploy_branch into the index - git --work-tree "$deploy_directory" reset --mixed --quiet - git --work-tree "$deploy_directory" add --all - - set +o errexit - diff=$(git --work-tree "$deploy_directory" diff --exit-code --quiet HEAD --)$? - set -o errexit - case $diff in - 0) echo No changes to files in $deploy_directory. Skipping commit.;; - 1) commit+push;; - *) - echo git diff exited with code $diff. Aborting. Staying on branch $deploy_branch so you can debug. To switch back to main, use: git symbolic-ref HEAD refs/heads/main && git reset --mixed >&2 - return $diff - ;; - esac -} - -commit+push() { - set_user_id - git --work-tree "$deploy_directory" commit -m "$commit_message" - - disable_expanded_output - #--quiet is important here to avoid outputting the repo URL, which may contain a secret token - git push --quiet $repo $deploy_branch - enable_expanded_output -} - -#echo expanded commands as they are executed (for debugging) -enable_expanded_output() { - if [ $verbose ]; then - set -o xtrace - set +o verbose - fi -} - -#this is used to avoid outputting the repo URL, which may contain a secret token -disable_expanded_output() { - if [ $verbose ]; then - set +o xtrace - set -o verbose - fi -} - -set_user_id() { - if [[ -z `git config user.name` ]]; then - git config user.name "$default_username" - fi - if [[ -z `git config user.email` ]]; then - git config user.email "$default_email" - fi -} - -restore_head() { - if [[ $previous_branch = "HEAD" ]]; then - #we weren't on any branch before, so just set HEAD back to the commit it was on - git update-ref --no-deref HEAD $commit_hash $deploy_branch - else - git symbolic-ref HEAD refs/heads/$previous_branch - fi - - git reset --mixed -} - -filter() { - sed -e "s|$repo|\$repo|g" -} - -sanitize() { - "$@" 2> >(filter 1>&2) | filter -} - -parse_args "$@" - -if [[ ${source_only} ]]; then - run_build -elif [[ ${push_only} ]]; then - main "$@" -else - run_build - main "$@" -fi diff --git a/samples/rest-notes-slate/slate/font-selection.json b/samples/rest-notes-slate/slate/font-selection.json deleted file mode 100755 index 5e78f5d86..000000000 --- a/samples/rest-notes-slate/slate/font-selection.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "IcoMoonType": "selection", - "icons": [ - { - "icon": { - "paths": [ - "M438.857 73.143q119.429 0 220.286 58.857t159.714 159.714 58.857 220.286-58.857 220.286-159.714 159.714-220.286 58.857-220.286-58.857-159.714-159.714-58.857-220.286 58.857-220.286 159.714-159.714 220.286-58.857zM512 785.714v-108.571q0-8-5.143-13.429t-12.571-5.429h-109.714q-7.429 0-13.143 5.714t-5.714 13.143v108.571q0 7.429 5.714 13.143t13.143 5.714h109.714q7.429 0 12.571-5.429t5.143-13.429zM510.857 589.143l10.286-354.857q0-6.857-5.714-10.286-5.714-4.571-13.714-4.571h-125.714q-8 0-13.714 4.571-5.714 3.429-5.714 10.286l9.714 354.857q0 5.714 5.714 10t13.714 4.286h105.714q8 0 13.429-4.286t6-10z" - ], - "attrs": [], - "isMulticolor": false, - "tags": [ - "exclamation-circle" - ], - "defaultCode": 61546, - "grid": 14 - }, - "attrs": [], - "properties": { - "id": 100, - "order": 4, - "prevSize": 28, - "code": 58880, - "name": "exclamation-sign", - "ligatures": "" - }, - "setIdx": 0, - "iconIdx": 0 - }, - { - "icon": { - "paths": [ - "M585.143 786.286v-91.429q0-8-5.143-13.143t-13.143-5.143h-54.857v-292.571q0-8-5.143-13.143t-13.143-5.143h-182.857q-8 0-13.143 5.143t-5.143 13.143v91.429q0 8 5.143 13.143t13.143 5.143h54.857v182.857h-54.857q-8 0-13.143 5.143t-5.143 13.143v91.429q0 8 5.143 13.143t13.143 5.143h256q8 0 13.143-5.143t5.143-13.143zM512 274.286v-91.429q0-8-5.143-13.143t-13.143-5.143h-109.714q-8 0-13.143 5.143t-5.143 13.143v91.429q0 8 5.143 13.143t13.143 5.143h109.714q8 0 13.143-5.143t5.143-13.143zM877.714 512q0 119.429-58.857 220.286t-159.714 159.714-220.286 58.857-220.286-58.857-159.714-159.714-58.857-220.286 58.857-220.286 159.714-159.714 220.286-58.857 220.286 58.857 159.714 159.714 58.857 220.286z" - ], - "attrs": [], - "isMulticolor": false, - "tags": [ - "info-circle" - ], - "defaultCode": 61530, - "grid": 14 - }, - "attrs": [], - "properties": { - "id": 85, - "order": 3, - "name": "info-sign", - "prevSize": 28, - "code": 58882 - }, - "setIdx": 0, - "iconIdx": 2 - }, - { - "icon": { - "paths": [ - "M733.714 419.429q0-16-10.286-26.286l-52-51.429q-10.857-10.857-25.714-10.857t-25.714 10.857l-233.143 232.571-129.143-129.143q-10.857-10.857-25.714-10.857t-25.714 10.857l-52 51.429q-10.286 10.286-10.286 26.286 0 15.429 10.286 25.714l206.857 206.857q10.857 10.857 25.714 10.857 15.429 0 26.286-10.857l310.286-310.286q10.286-10.286 10.286-25.714zM877.714 512q0 119.429-58.857 220.286t-159.714 159.714-220.286 58.857-220.286-58.857-159.714-159.714-58.857-220.286 58.857-220.286 159.714-159.714 220.286-58.857 220.286 58.857 159.714 159.714 58.857 220.286z" - ], - "attrs": [], - "isMulticolor": false, - "tags": [ - "check-circle" - ], - "defaultCode": 61528, - "grid": 14 - }, - "attrs": [], - "properties": { - "id": 83, - "order": 9, - "prevSize": 28, - "code": 58886, - "name": "ok-sign" - }, - "setIdx": 0, - "iconIdx": 6 - }, - { - "icon": { - "paths": [ - "M658.286 475.429q0-105.714-75.143-180.857t-180.857-75.143-180.857 75.143-75.143 180.857 75.143 180.857 180.857 75.143 180.857-75.143 75.143-180.857zM950.857 950.857q0 29.714-21.714 51.429t-51.429 21.714q-30.857 0-51.429-21.714l-196-195.429q-102.286 70.857-228 70.857-81.714 0-156.286-31.714t-128.571-85.714-85.714-128.571-31.714-156.286 31.714-156.286 85.714-128.571 128.571-85.714 156.286-31.714 156.286 31.714 128.571 85.714 85.714 128.571 31.714 156.286q0 125.714-70.857 228l196 196q21.143 21.143 21.143 51.429z" - ], - "width": 951, - "attrs": [], - "isMulticolor": false, - "tags": [ - "search" - ], - "defaultCode": 61442, - "grid": 14 - }, - "attrs": [], - "properties": { - "id": 2, - "order": 1, - "prevSize": 28, - "code": 58887, - "name": "icon-search" - }, - "setIdx": 0, - "iconIdx": 7 - } - ], - "height": 1024, - "metadata": { - "name": "slate", - "license": "SIL OFL 1.1" - }, - "preferences": { - "showGlyphs": true, - "showQuickUse": true, - "showQuickUse2": true, - "showSVGs": true, - "fontPref": { - "prefix": "icon-", - "metadata": { - "fontFamily": "slate", - "majorVersion": 1, - "minorVersion": 0, - "description": "Based on FontAwesome", - "license": "SIL OFL 1.1" - }, - "metrics": { - "emSize": 1024, - "baseline": 6.25, - "whitespace": 50 - }, - "resetPoint": 58880, - "showSelector": false, - "selector": "class", - "classSelector": ".icon", - "showMetrics": false, - "showMetadata": true, - "showVersion": true, - "ie7": false - }, - "imagePref": { - "prefix": "icon-", - "png": true, - "useClassSelector": true, - "color": 4473924, - "bgColor": 16777215 - }, - "historySize": 100, - "showCodes": true, - "gridSize": 16, - "showLiga": false - } -} diff --git a/samples/rest-notes-slate/slate/lib/monokai_sublime_slate.rb b/samples/rest-notes-slate/slate/lib/monokai_sublime_slate.rb deleted file mode 100644 index cd2de3317..000000000 --- a/samples/rest-notes-slate/slate/lib/monokai_sublime_slate.rb +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- # -# frozen_string_literal: true - -# this is based on https://github.com/rouge-ruby/rouge/blob/master/lib/rouge/themes/monokai_sublime.rb -# but without the added background, and changed styling for JSON keys to be soft_yellow instead of white - -module Rouge - module Themes - class MonokaiSublimeSlate < CSSTheme - name 'monokai.sublime.slate' - - palette :black => '#000000' - palette :bright_green => '#a6e22e' - palette :bright_pink => '#f92672' - palette :carmine => '#960050' - palette :dark => '#49483e' - palette :dark_grey => '#888888' - palette :dark_red => '#aa0000' - palette :dimgrey => '#75715e' - palette :emperor => '#555555' - palette :grey => '#999999' - palette :light_grey => '#aaaaaa' - palette :light_violet => '#ae81ff' - palette :soft_cyan => '#66d9ef' - palette :soft_yellow => '#e6db74' - palette :very_dark => '#1e0010' - palette :whitish => '#f8f8f2' - palette :orange => '#f6aa11' - palette :white => '#ffffff' - - style Generic::Heading, :fg => :grey - style Literal::String::Regex, :fg => :orange - style Generic::Output, :fg => :dark_grey - style Generic::Prompt, :fg => :emperor - style Generic::Strong, :bold => false - style Generic::Subheading, :fg => :light_grey - style Name::Builtin, :fg => :orange - style Comment::Multiline, - Comment::Preproc, - Comment::Single, - Comment::Special, - Comment, :fg => :dimgrey - style Error, - Generic::Error, - Generic::Traceback, :fg => :carmine - style Generic::Deleted, - Generic::Inserted, - Generic::Emph, :fg => :dark - style Keyword::Constant, - Keyword::Declaration, - Keyword::Reserved, - Name::Constant, - Keyword::Type, :fg => :soft_cyan - style Literal::Number::Float, - Literal::Number::Hex, - Literal::Number::Integer::Long, - Literal::Number::Integer, - Literal::Number::Oct, - Literal::Number, - Literal::String::Char, - Literal::String::Escape, - Literal::String::Symbol, :fg => :light_violet - style Literal::String::Doc, - Literal::String::Double, - Literal::String::Backtick, - Literal::String::Heredoc, - Literal::String::Interpol, - Literal::String::Other, - Literal::String::Single, - Literal::String, :fg => :soft_yellow - style Name::Attribute, - Name::Class, - Name::Decorator, - Name::Exception, - Name::Function, :fg => :bright_green - style Name::Variable::Class, - Name::Namespace, - Name::Entity, - Name::Builtin::Pseudo, - Name::Variable::Global, - Name::Variable::Instance, - Name::Variable, - Text::Whitespace, - Text, - Name, :fg => :white - style Name::Label, :fg => :bright_pink - style Operator::Word, - Name::Tag, - Keyword, - Keyword::Namespace, - Keyword::Pseudo, - Operator, :fg => :bright_pink - end - end - end diff --git a/samples/rest-notes-slate/slate/lib/multilang.rb b/samples/rest-notes-slate/slate/lib/multilang.rb deleted file mode 100644 index 36fbe5b1f..000000000 --- a/samples/rest-notes-slate/slate/lib/multilang.rb +++ /dev/null @@ -1,16 +0,0 @@ -module Multilang - def block_code(code, full_lang_name) - if full_lang_name - parts = full_lang_name.split('--') - rouge_lang_name = (parts) ? parts[0] : "" # just parts[0] here causes null ref exception when no language specified - super(code, rouge_lang_name).sub("highlight #{rouge_lang_name}") do |match| - match + " tab-" + full_lang_name - end - else - super(code, full_lang_name) - end - end -end - -require 'middleman-core/renderers/redcarpet' -Middleman::Renderers::MiddlemanRedcarpetHTML.send :include, Multilang diff --git a/samples/rest-notes-slate/slate/lib/nesting_unique_head.rb b/samples/rest-notes-slate/slate/lib/nesting_unique_head.rb deleted file mode 100644 index 01278371c..000000000 --- a/samples/rest-notes-slate/slate/lib/nesting_unique_head.rb +++ /dev/null @@ -1,22 +0,0 @@ -# Nested unique header generation -require 'middleman-core/renderers/redcarpet' - -class NestingUniqueHeadCounter < Middleman::Renderers::MiddlemanRedcarpetHTML - def initialize - super - @@headers_history = {} if !defined?(@@headers_history) - end - - def header(text, header_level) - friendly_text = text.gsub(/<[^>]*>/,"").parameterize - @@headers_history[header_level] = text.parameterize - - if header_level > 1 - for i in (header_level - 1).downto(1) - friendly_text.prepend("#{@@headers_history[i]}-") if @@headers_history.key?(i) - end - end - - return "#{text}" - end -end diff --git a/samples/rest-notes-slate/slate/lib/toc_data.rb b/samples/rest-notes-slate/slate/lib/toc_data.rb deleted file mode 100644 index 4a04efee2..000000000 --- a/samples/rest-notes-slate/slate/lib/toc_data.rb +++ /dev/null @@ -1,31 +0,0 @@ -require 'nokogiri' - -def toc_data(page_content) - html_doc = Nokogiri::HTML::DocumentFragment.parse(page_content) - - # get a flat list of headers - headers = [] - html_doc.css('h1, h2, h3').each do |header| - headers.push({ - id: header.attribute('id').to_s, - content: header.children, - title: header.children.to_s.gsub(/<[^>]*>/, ''), - level: header.name[1].to_i, - children: [] - }) - end - - [3,2].each do |header_level| - header_to_nest = nil - headers = headers.reject do |header| - if header[:level] == header_level - header_to_nest[:children].push header if header_to_nest - true - else - header_to_nest = header if header[:level] < header_level - false - end - end - end - headers -end diff --git a/samples/rest-notes-slate/slate/lib/unique_head.rb b/samples/rest-notes-slate/slate/lib/unique_head.rb deleted file mode 100644 index d42bab2aa..000000000 --- a/samples/rest-notes-slate/slate/lib/unique_head.rb +++ /dev/null @@ -1,24 +0,0 @@ -# Unique header generation -require 'middleman-core/renderers/redcarpet' -require 'digest' -class UniqueHeadCounter < Middleman::Renderers::MiddlemanRedcarpetHTML - def initialize - super - @head_count = {} - end - def header(text, header_level) - friendly_text = text.gsub(/<[^>]*>/,"").parameterize - if friendly_text.strip.length == 0 - # Looks like parameterize removed the whole thing! It removes many unicode - # characters like Chinese and Russian. To get a unique URL, let's just - # URI escape the whole header - friendly_text = Digest::SHA1.hexdigest(text)[0,10] - end - @head_count[friendly_text] ||= 0 - @head_count[friendly_text] += 1 - if @head_count[friendly_text] > 1 - friendly_text += "-#{@head_count[friendly_text]}" - end - return "#{text}" - end -end diff --git a/samples/rest-notes-slate/slate/slate.sh b/samples/rest-notes-slate/slate/slate.sh deleted file mode 100755 index a3cc498e9..000000000 --- a/samples/rest-notes-slate/slate/slate.sh +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env bash -set -o errexit #abort if any command fails - -me=$(basename "$0") - -help_message="\ -Usage: $me [] [] -Run commands related to the slate process. - -Commands: - - serve Run the middleman server process, useful for - development. - build Run the build process. - deploy Will build and deploy files to branch. Use - --no-build to only deploy. - -Global Options: - - -h, --help Show this help information. - -v, --verbose Increase verbosity. Useful for debugging. - -Deploy options: - -e, --allow-empty Allow deployment of an empty directory. - -m, --message MESSAGE Specify the message used when committing on the - deploy branch. - -n, --no-hash Don't append the source commit's hash to the deploy - commit's message. - --no-build Do not build the source files. -" - - -run_serve() { - exec bundle exec middleman serve --watcher-force-polling -} - -run_build() { - bundle exec middleman build --clean -} - -parse_args() { - # Set args from a local environment file. - if [ -e ".env" ]; then - source .env - fi - - command= - - # Parse arg flags - # If something is exposed as an environment variable, set/overwrite it - # here. Otherwise, set/overwrite the internal variable instead. - while : ; do - if [[ $1 = "-h" || $1 = "--help" ]]; then - echo "$help_message" - exit 0 - elif [[ $1 = "-v" || $1 = "--verbose" ]]; then - verbose=true - shift - elif [[ $1 = "-e" || $1 = "--allow-empty" ]]; then - allow_empty=true - shift - elif [[ ( $1 = "-m" || $1 = "--message" ) && -n $2 ]]; then - commit_message=$2 - shift 2 - elif [[ $1 = "-n" || $1 = "--no-hash" ]]; then - GIT_DEPLOY_APPEND_HASH=false - shift - elif [[ $1 = "--no-build" ]]; then - no_build=true - shift - elif [[ $1 = "serve" || $1 = "build" || $1 = "deploy" ]]; then - if [ ! -z "${command}" ]; then - >&2 echo "You can only specify one command." - exit 1 - fi - command=$1 - shift - elif [ -z $1 ]; then - break - fi - done - - if [ -z "${command}" ]; then - >&2 echo "Command not specified." - exit 1 - fi - - # Set internal option vars from the environment and arg flags. All internal - # vars should be declared here, with sane defaults if applicable. - - # Source directory & target branch. - deploy_directory=build - deploy_branch=gh-pages - - #if no user identity is already set in the current git environment, use this: - default_username=${GIT_DEPLOY_USERNAME:-deploy.sh} - default_email=${GIT_DEPLOY_EMAIL:-} - - #repository to deploy to. must be readable and writable. - repo=origin - - #append commit hash to the end of message by default - append_hash=${GIT_DEPLOY_APPEND_HASH:-true} -} - -main() { - enable_expanded_output - - if ! git diff --exit-code --quiet --cached; then - echo Aborting due to uncommitted changes in the index >&2 - return 1 - fi - - commit_title=`git log -n 1 --format="%s" HEAD` - commit_hash=` git log -n 1 --format="%H" HEAD` - - #default commit message uses last title if a custom one is not supplied - if [[ -z $commit_message ]]; then - commit_message="publish: $commit_title" - fi - - #append hash to commit message unless no hash flag was found - if [ $append_hash = true ]; then - commit_message="$commit_message"$'\n\n'"generated from commit $commit_hash" - fi - - previous_branch=`git rev-parse --abbrev-ref HEAD` - - if [ ! -d "$deploy_directory" ]; then - echo "Deploy directory '$deploy_directory' does not exist. Aborting." >&2 - return 1 - fi - - # must use short form of flag in ls for compatibility with macOS and BSD - if [[ -z `ls -A "$deploy_directory" 2> /dev/null` && -z $allow_empty ]]; then - echo "Deploy directory '$deploy_directory' is empty. Aborting. If you're sure you want to deploy an empty tree, use the --allow-empty / -e flag." >&2 - return 1 - fi - - if git ls-remote --exit-code $repo "refs/heads/$deploy_branch" ; then - # deploy_branch exists in $repo; make sure we have the latest version - - disable_expanded_output - git fetch --force $repo $deploy_branch:$deploy_branch - enable_expanded_output - fi - - # check if deploy_branch exists locally - if git show-ref --verify --quiet "refs/heads/$deploy_branch" - then incremental_deploy - else initial_deploy - fi - - restore_head -} - -initial_deploy() { - git --work-tree "$deploy_directory" checkout --orphan $deploy_branch - git --work-tree "$deploy_directory" add --all - commit+push -} - -incremental_deploy() { - #make deploy_branch the current branch - git symbolic-ref HEAD refs/heads/$deploy_branch - #put the previously committed contents of deploy_branch into the index - git --work-tree "$deploy_directory" reset --mixed --quiet - git --work-tree "$deploy_directory" add --all - - set +o errexit - diff=$(git --work-tree "$deploy_directory" diff --exit-code --quiet HEAD --)$? - set -o errexit - case $diff in - 0) echo No changes to files in $deploy_directory. Skipping commit.;; - 1) commit+push;; - *) - echo git diff exited with code $diff. Aborting. Staying on branch $deploy_branch so you can debug. To switch back to main, use: git symbolic-ref HEAD refs/heads/main && git reset --mixed >&2 - return $diff - ;; - esac -} - -commit+push() { - set_user_id - git --work-tree "$deploy_directory" commit -m "$commit_message" - - disable_expanded_output - #--quiet is important here to avoid outputting the repo URL, which may contain a secret token - git push --quiet $repo $deploy_branch - enable_expanded_output -} - -#echo expanded commands as they are executed (for debugging) -enable_expanded_output() { - if [ $verbose ]; then - set -o xtrace - set +o verbose - fi -} - -#this is used to avoid outputting the repo URL, which may contain a secret token -disable_expanded_output() { - if [ $verbose ]; then - set +o xtrace - set -o verbose - fi -} - -set_user_id() { - if [[ -z `git config user.name` ]]; then - git config user.name "$default_username" - fi - if [[ -z `git config user.email` ]]; then - git config user.email "$default_email" - fi -} - -restore_head() { - if [[ $previous_branch = "HEAD" ]]; then - #we weren't on any branch before, so just set HEAD back to the commit it was on - git update-ref --no-deref HEAD $commit_hash $deploy_branch - else - git symbolic-ref HEAD refs/heads/$previous_branch - fi - - git reset --mixed -} - -filter() { - sed -e "s|$repo|\$repo|g" -} - -sanitize() { - "$@" 2> >(filter 1>&2) | filter -} - -parse_args "$@" - -if [ "${command}" = "serve" ]; then - run_serve -elif [[ "${command}" = "build" ]]; then - run_build -elif [[ ${command} = "deploy" ]]; then - if [[ ${no_build} != true ]]; then - run_build - fi - main "$@" -fi diff --git a/samples/rest-notes-slate/slate/source/api-guide.html.md.erb b/samples/rest-notes-slate/slate/source/api-guide.html.md.erb deleted file mode 100644 index 77dab5229..000000000 --- a/samples/rest-notes-slate/slate/source/api-guide.html.md.erb +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: REST Notes API Guide - -language_tabs: - - shell - - http - -search: true ---- - -# Overview - - -## HTTP verbs - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP verbs. - - -Verb | Usage --------- | ----- -`GET` | Used to retrieve a resource -`POST` | Used to create a new resource -`PATCH` | Used to update an existing resource, including partial updates -`DELETE` | Used to delete an existing resource - -## HTTP status codes - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP status codes. - -Status code | Usage ------------------ | ----- -`200 OK` | The request completed successfully -`201 Created` | A new resource has been created successfully. The resource's URI is available from the response's `Location` header -`204 No Content` | An update to an existing resource has been applied successfully -`400 Bad Request` | The request was malformed. The response body will include an error providing further information -`404 Not Found` | The requested resource did not exist - -## Errors - -<%= ERB.new(File.read("../build/generated-snippets/error-example/http-response.md")).result(binding) %> - -Whenever an error response (status code >= 400) is returned, the body will contain a JSON object -that describes the problem. The error object has the following structure: - -<%= ERB.new(File.read("../build/generated-snippets/error-example/response-fields.md")).result(binding) %> - -## Hypermedia - -RESTful Notes uses hypermedia and resources include links to other resources in their -responses. Responses are in [Hypertext Application Language (HAL)](https://github.com/mikekelly/hal_specification) -format. Links can be found beneath the `_links` key. Users of the API should not create -URIs themselves, instead they should use the above-described links to navigate - - - -# Resources - - - -## Index - -<%= ERB.new(File.read("../build/generated-snippets/index-example/curl-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/index-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/index-example/http-response.md")).result(binding) %> - -The index provides the entry point into the service. A `GET` request is used to access the index. - -### Response structure - -<%= ERB.new(File.read("../build/generated-snippets/index-example/response-fields.md")).result(binding) %> - -### Links - -<%= ERB.new(File.read("../build/generated-snippets/index-example/links.md")).result(binding) %> - - - -## Notes - -The Notes resources is used to create and list notes - -### Listing notes - -<%= ERB.new(File.read("../build/generated-snippets/notes-list-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/notes-list-example/http-response.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/notes-list-example/curl-request.md")).result(binding) %> - -A `GET` request will list all of the service's notes. - -#### Response structure - -<%= ERB.new(File.read("../build/generated-snippets/notes-list-example/response-fields.md")).result(binding) %> - -### Creating a note - -<%= ERB.new(File.read("../build/generated-snippets/notes-create-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/notes-create-example/http-response.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/notes-create-example/curl-request.md")).result(binding) %> - -A `POST` request is used to create a note - -#### Request structure - -<%= ERB.new(File.read("../build/generated-snippets/notes-create-example/request-fields.md")).result(binding) %> - - - -## Tags - -The Tags resource is used to create and list tags. - -### Listing tags - -<%= ERB.new(File.read("../build/generated-snippets/tags-list-example/curl-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/tags-list-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/tags-list-example/http-response.md")).result(binding) %> - -A `GET` request will list all of the service's tags. - -#### Response structure - -<%= ERB.new(File.read("../build/generated-snippets/tags-list-example/response-fields.md")).result(binding) %> - - -### Creating a tag - -<%= ERB.new(File.read("../build/generated-snippets/tags-create-example/curl-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/tags-create-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/notes-create-example/http-response.md")).result(binding) %> - -A `POST` request is used to create a tag - -#### Request structure - -<%= ERB.new(File.read("../build/generated-snippets/tags-create-example/request-fields.md")).result(binding) %> - - - -## Note - -The Note resource is used to retrieve, update, and delete individual notes - -### Retrieve a note - -<%= ERB.new(File.read("../build/generated-snippets/note-get-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/note-get-example/curl-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/note-get-example/http-response.md")).result(binding) %> - -A `GET` request will retrieve the details of a note - -<%= ERB.new(File.read("../build/generated-snippets/note-get-example/response-fields.md")).result(binding) %> - -#### Links - -<%= ERB.new(File.read("../build/generated-snippets/note-get-example/links.md")).result(binding) %> - -### Update a note - -<%= ERB.new(File.read("../build/generated-snippets/note-update-example/curl-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/note-update-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/note-update-example/http-response.md")).result(binding) %> - -A `PATCH` request is used to update a note - -#### Request structure - -<%= ERB.new(File.read("../build/generated-snippets/note-update-example/request-fields.md")).result(binding) %> - -To leave an attribute of a note unchanged, any of the above may be omitted from the -request. - - - -## Tag - -The Tag resource is used to retrieve, update, and delete individual tags - -### Retrieve a tag - -<%= ERB.new(File.read("../build/generated-snippets/tag-get-example/curl-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/tag-get-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/tag-get-example/http-response.md")).result(binding) %> - -A `GET` request will retrieve the details of a tag - -#### Response structure - -<%= ERB.new(File.read("../build/generated-snippets/tag-get-example/response-fields.md")).result(binding) %> - -#### Links - -<%= ERB.new(File.read("../build/generated-snippets/tag-get-example/links.md")).result(binding) %> - -### Update a tag - -<%= ERB.new(File.read("../build/generated-snippets/tag-update-example/curl-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/tag-update-example/http-request.md")).result(binding) %> -<%= ERB.new(File.read("../build/generated-snippets/tag-update-example/http-response.md")).result(binding) %> - -A `PATCH` request is used to update a tag - -#### Request structure - -<%= ERB.new(File.read("../build/generated-snippets/tag-update-example/request-fields.md")).result(binding) %> \ No newline at end of file diff --git a/samples/rest-notes-slate/slate/source/fonts/slate.eot b/samples/rest-notes-slate/slate/source/fonts/slate.eot deleted file mode 100644 index 13c4839a1..000000000 Binary files a/samples/rest-notes-slate/slate/source/fonts/slate.eot and /dev/null differ diff --git a/samples/rest-notes-slate/slate/source/fonts/slate.svg b/samples/rest-notes-slate/slate/source/fonts/slate.svg deleted file mode 100644 index 5f3498230..000000000 --- a/samples/rest-notes-slate/slate/source/fonts/slate.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - -Generated by IcoMoon - - - - - - - - - - diff --git a/samples/rest-notes-slate/slate/source/fonts/slate.ttf b/samples/rest-notes-slate/slate/source/fonts/slate.ttf deleted file mode 100644 index ace9a46a7..000000000 Binary files a/samples/rest-notes-slate/slate/source/fonts/slate.ttf and /dev/null differ diff --git a/samples/rest-notes-slate/slate/source/fonts/slate.woff b/samples/rest-notes-slate/slate/source/fonts/slate.woff deleted file mode 100644 index 1e72e0ee0..000000000 Binary files a/samples/rest-notes-slate/slate/source/fonts/slate.woff and /dev/null differ diff --git a/samples/rest-notes-slate/slate/source/fonts/slate.woff2 b/samples/rest-notes-slate/slate/source/fonts/slate.woff2 deleted file mode 100644 index 7c585a727..000000000 Binary files a/samples/rest-notes-slate/slate/source/fonts/slate.woff2 and /dev/null differ diff --git a/samples/rest-notes-slate/slate/source/images/logo.png b/samples/rest-notes-slate/slate/source/images/logo.png deleted file mode 100644 index 68a478fae..000000000 Binary files a/samples/rest-notes-slate/slate/source/images/logo.png and /dev/null differ diff --git a/samples/rest-notes-slate/slate/source/images/navbar.png b/samples/rest-notes-slate/slate/source/images/navbar.png deleted file mode 100644 index df38e90d8..000000000 Binary files a/samples/rest-notes-slate/slate/source/images/navbar.png and /dev/null differ diff --git a/samples/rest-notes-slate/slate/source/includes/_errors.md b/samples/rest-notes-slate/slate/source/includes/_errors.md deleted file mode 100644 index 7b35e92b5..000000000 --- a/samples/rest-notes-slate/slate/source/includes/_errors.md +++ /dev/null @@ -1,22 +0,0 @@ -# Errors - - - -The Kittn API uses the following error codes: - - -Error Code | Meaning ----------- | ------- -400 | Bad Request -- Your request is invalid. -401 | Unauthorized -- Your API key is wrong. -403 | Forbidden -- The kitten requested is hidden for administrators only. -404 | Not Found -- The specified kitten could not be found. -405 | Method Not Allowed -- You tried to access a kitten with an invalid method. -406 | Not Acceptable -- You requested a format that isn't json. -410 | Gone -- The kitten requested has been removed from our servers. -418 | I'm a teapot. -429 | Too Many Requests -- You're requesting too many kittens! Slow down! -500 | Internal Server Error -- We had a problem with our server. Try again later. -503 | Service Unavailable -- We're temporarily offline for maintenance. Please try again later. diff --git a/samples/rest-notes-slate/slate/source/index.html.md b/samples/rest-notes-slate/slate/source/index.html.md deleted file mode 100644 index db246274b..000000000 --- a/samples/rest-notes-slate/slate/source/index.html.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: API Reference - -language_tabs: # must be one of https://git.io/vQNgJ - - shell - - ruby - - python - - javascript - -toc_footers: - - Sign Up for a Developer Key - - Documentation Powered by Slate - -includes: - - errors - -search: true - -code_clipboard: true - -meta: - - name: description - content: Documentation for the Kittn API ---- - -# Introduction - -Welcome to the Kittn API! You can use our API to access Kittn API endpoints, which can get information on various cats, kittens, and breeds in our database. - -We have language bindings in Shell, Ruby, Python, and JavaScript! You can view code examples in the dark area to the right, and you can switch the programming language of the examples with the tabs in the top right. - -This example API documentation page was created with [Slate](https://github.com/slatedocs/slate). Feel free to edit it and use it as a base for your own API's documentation. - -# Authentication - -> To authorize, use this code: - -```ruby -require 'kittn' - -api = Kittn::APIClient.authorize!('meowmeowmeow') -``` - -```python -import kittn - -api = kittn.authorize('meowmeowmeow') -``` - -```shell -# With shell, you can just pass the correct header with each request -curl "api_endpoint_here" \ - -H "Authorization: meowmeowmeow" -``` - -```javascript -const kittn = require('kittn'); - -let api = kittn.authorize('meowmeowmeow'); -``` - -> Make sure to replace `meowmeowmeow` with your API key. - -Kittn uses API keys to allow access to the API. You can register a new Kittn API key at our [developer portal](http://example.com/developers). - -Kittn expects for the API key to be included in all API requests to the server in a header that looks like the following: - -`Authorization: meowmeowmeow` - - - -# Kittens - -## Get All Kittens - -```ruby -require 'kittn' - -api = Kittn::APIClient.authorize!('meowmeowmeow') -api.kittens.get -``` - -```python -import kittn - -api = kittn.authorize('meowmeowmeow') -api.kittens.get() -``` - -```shell -curl "http://example.com/api/kittens" \ - -H "Authorization: meowmeowmeow" -``` - -```javascript -const kittn = require('kittn'); - -let api = kittn.authorize('meowmeowmeow'); -let kittens = api.kittens.get(); -``` - -> The above command returns JSON structured like this: - -```json -[ - { - "id": 1, - "name": "Fluffums", - "breed": "calico", - "fluffiness": 6, - "cuteness": 7 - }, - { - "id": 2, - "name": "Max", - "breed": "unknown", - "fluffiness": 5, - "cuteness": 10 - } -] -``` - -This endpoint retrieves all kittens. - -### HTTP Request - -`GET http://example.com/api/kittens` - -### Query Parameters - -Parameter | Default | Description ---------- | ------- | ----------- -include_cats | false | If set to true, the result will also include cats. -available | true | If set to false, the result will include kittens that have already been adopted. - - - -## Get a Specific Kitten - -```ruby -require 'kittn' - -api = Kittn::APIClient.authorize!('meowmeowmeow') -api.kittens.get(2) -``` - -```python -import kittn - -api = kittn.authorize('meowmeowmeow') -api.kittens.get(2) -``` - -```shell -curl "http://example.com/api/kittens/2" \ - -H "Authorization: meowmeowmeow" -``` - -```javascript -const kittn = require('kittn'); - -let api = kittn.authorize('meowmeowmeow'); -let max = api.kittens.get(2); -``` - -> The above command returns JSON structured like this: - -```json -{ - "id": 2, - "name": "Max", - "breed": "unknown", - "fluffiness": 5, - "cuteness": 10 -} -``` - -This endpoint retrieves a specific kitten. - - - -### HTTP Request - -`GET http://example.com/kittens/` - -### URL Parameters - -Parameter | Description ---------- | ----------- -ID | The ID of the kitten to retrieve - -## Delete a Specific Kitten - -```ruby -require 'kittn' - -api = Kittn::APIClient.authorize!('meowmeowmeow') -api.kittens.delete(2) -``` - -```python -import kittn - -api = kittn.authorize('meowmeowmeow') -api.kittens.delete(2) -``` - -```shell -curl "http://example.com/api/kittens/2" \ - -X DELETE \ - -H "Authorization: meowmeowmeow" -``` - -```javascript -const kittn = require('kittn'); - -let api = kittn.authorize('meowmeowmeow'); -let max = api.kittens.delete(2); -``` - -> The above command returns JSON structured like this: - -```json -{ - "id": 2, - "deleted" : ":(" -} -``` - -This endpoint deletes a specific kitten. - -### HTTP Request - -`DELETE http://example.com/kittens/` - -### URL Parameters - -Parameter | Description ---------- | ----------- -ID | The ID of the kitten to delete - diff --git a/samples/rest-notes-slate/slate/source/javascripts/all.js b/samples/rest-notes-slate/slate/source/javascripts/all.js deleted file mode 100644 index 5f5d4067b..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/all.js +++ /dev/null @@ -1,2 +0,0 @@ -//= require ./all_nosearch -//= require ./app/_search diff --git a/samples/rest-notes-slate/slate/source/javascripts/all_nosearch.js b/samples/rest-notes-slate/slate/source/javascripts/all_nosearch.js deleted file mode 100644 index 026e5a200..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/all_nosearch.js +++ /dev/null @@ -1,27 +0,0 @@ -//= require ./lib/_energize -//= require ./app/_copy -//= require ./app/_toc -//= require ./app/_lang - -function adjustLanguageSelectorWidth() { - const elem = $('.dark-box > .lang-selector'); - elem.width(elem.parent().width()); -} - -$(function() { - loadToc($('#toc'), '.toc-link', '.toc-list-h2', 10); - setupLanguages($('body').data('languages')); - $('.content').imagesLoaded( function() { - window.recacheHeights(); - window.refreshToc(); - }); - - $(window).resize(function() { - adjustLanguageSelectorWidth(); - }); - adjustLanguageSelectorWidth(); -}); - -window.onpopstate = function() { - activateLanguage(getLanguageFromQueryString()); -}; diff --git a/samples/rest-notes-slate/slate/source/javascripts/app/_copy.js b/samples/rest-notes-slate/slate/source/javascripts/app/_copy.js deleted file mode 100644 index 4dfbbb6c0..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/app/_copy.js +++ /dev/null @@ -1,15 +0,0 @@ -function copyToClipboard(container) { - const el = document.createElement('textarea'); - el.value = container.textContent.replace(/\n$/, ''); - document.body.appendChild(el); - el.select(); - document.execCommand('copy'); - document.body.removeChild(el); -} - -function setupCodeCopy() { - $('pre.highlight').prepend('
Copy to Clipboard
'); - $('.copy-clipboard').on('click', function() { - copyToClipboard(this.parentNode.children[1]); - }); -} diff --git a/samples/rest-notes-slate/slate/source/javascripts/app/_lang.js b/samples/rest-notes-slate/slate/source/javascripts/app/_lang.js deleted file mode 100644 index cc5ac8b6b..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/app/_lang.js +++ /dev/null @@ -1,171 +0,0 @@ -//= require ../lib/_jquery - -/* -Copyright 2008-2013 Concur Technologies, Inc. - -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. -*/ -;(function () { - 'use strict'; - - var languages = []; - - window.setupLanguages = setupLanguages; - window.activateLanguage = activateLanguage; - window.getLanguageFromQueryString = getLanguageFromQueryString; - - function activateLanguage(language) { - if (!language) return; - if (language === "") return; - - $(".lang-selector a").removeClass('active'); - $(".lang-selector a[data-language-name='" + language + "']").addClass('active'); - for (var i=0; i < languages.length; i++) { - $(".highlight.tab-" + languages[i]).hide(); - $(".lang-specific." + languages[i]).hide(); - } - $(".highlight.tab-" + language).show(); - $(".lang-specific." + language).show(); - - window.recacheHeights(); - - // scroll to the new location of the position - if ($(window.location.hash).get(0)) { - $(window.location.hash).get(0).scrollIntoView(true); - } - } - - // parseURL and stringifyURL are from https://github.com/sindresorhus/query-string - // MIT licensed - // https://github.com/sindresorhus/query-string/blob/7bee64c16f2da1a326579e96977b9227bf6da9e6/license - function parseURL(str) { - if (typeof str !== 'string') { - return {}; - } - - str = str.trim().replace(/^(\?|#|&)/, ''); - - if (!str) { - return {}; - } - - return str.split('&').reduce(function (ret, param) { - var parts = param.replace(/\+/g, ' ').split('='); - var key = parts[0]; - var val = parts[1]; - - key = decodeURIComponent(key); - // missing `=` should be `null`: - // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters - val = val === undefined ? null : decodeURIComponent(val); - - if (!ret.hasOwnProperty(key)) { - ret[key] = val; - } else if (Array.isArray(ret[key])) { - ret[key].push(val); - } else { - ret[key] = [ret[key], val]; - } - - return ret; - }, {}); - }; - - function stringifyURL(obj) { - return obj ? Object.keys(obj).sort().map(function (key) { - var val = obj[key]; - - if (Array.isArray(val)) { - return val.sort().map(function (val2) { - return encodeURIComponent(key) + '=' + encodeURIComponent(val2); - }).join('&'); - } - - return encodeURIComponent(key) + '=' + encodeURIComponent(val); - }).join('&') : ''; - }; - - // gets the language set in the query string - function getLanguageFromQueryString() { - if (location.search.length >= 1) { - var language = parseURL(location.search).language; - if (language) { - return language; - } else if (jQuery.inArray(location.search.substr(1), languages) != -1) { - return location.search.substr(1); - } - } - - return false; - } - - // returns a new query string with the new language in it - function generateNewQueryString(language) { - var url = parseURL(location.search); - if (url.language) { - url.language = language; - return stringifyURL(url); - } - return language; - } - - // if a button is clicked, add the state to the history - function pushURL(language) { - if (!history) { return; } - var hash = window.location.hash; - if (hash) { - hash = hash.replace(/^#+/, ''); - } - history.pushState({}, '', '?' + generateNewQueryString(language) + '#' + hash); - - // save language as next default - if (localStorage) { - localStorage.setItem("language", language); - } - } - - function setupLanguages(l) { - var defaultLanguage = null; - if (localStorage) { - defaultLanguage = localStorage.getItem("language"); - } - - languages = l; - - var presetLanguage = getLanguageFromQueryString(); - if (presetLanguage) { - // the language is in the URL, so use that language! - activateLanguage(presetLanguage); - - if (localStorage) { - localStorage.setItem("language", presetLanguage); - } - } else if ((defaultLanguage !== null) && (jQuery.inArray(defaultLanguage, languages) != -1)) { - // the language was the last selected one saved in localstorage, so use that language! - activateLanguage(defaultLanguage); - } else { - // no language selected, so use the default - activateLanguage(languages[0]); - } - } - - // if we click on a language tab, activate that language - $(function() { - $(".lang-selector a").on("click", function() { - var language = $(this).data("language-name"); - pushURL(language); - activateLanguage(language); - return false; - }); - }); -})(); diff --git a/samples/rest-notes-slate/slate/source/javascripts/app/_search.js b/samples/rest-notes-slate/slate/source/javascripts/app/_search.js deleted file mode 100644 index 0b0ccd97f..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/app/_search.js +++ /dev/null @@ -1,102 +0,0 @@ -//= require ../lib/_lunr -//= require ../lib/_jquery -//= require ../lib/_jquery.highlight -;(function () { - 'use strict'; - - var content, searchResults; - var highlightOpts = { element: 'span', className: 'search-highlight' }; - var searchDelay = 0; - var timeoutHandle = 0; - var index; - - function populate() { - index = lunr(function(){ - - this.ref('id'); - this.field('title', { boost: 10 }); - this.field('body'); - this.pipeline.add(lunr.trimmer, lunr.stopWordFilter); - var lunrConfig = this; - - $('h1, h2').each(function() { - var title = $(this); - var body = title.nextUntil('h1, h2'); - lunrConfig.add({ - id: title.prop('id'), - title: title.text(), - body: body.text() - }); - }); - - }); - determineSearchDelay(); - } - - $(populate); - $(bind); - - function determineSearchDelay() { - if (index.tokenSet.toArray().length>5000) { - searchDelay = 300; - } - } - - function bind() { - content = $('.content'); - searchResults = $('.search-results'); - - $('#input-search').on('keyup',function(e) { - var wait = function() { - return function(executingFunction, waitTime){ - clearTimeout(timeoutHandle); - timeoutHandle = setTimeout(executingFunction, waitTime); - }; - }(); - wait(function(){ - search(e); - }, searchDelay); - }); - } - - function search(event) { - - var searchInput = $('#input-search')[0]; - - unhighlight(); - searchResults.addClass('visible'); - - // ESC clears the field - if (event.keyCode === 27) searchInput.value = ''; - - if (searchInput.value) { - var results = index.search(searchInput.value).filter(function(r) { - return r.score > 0.0001; - }); - - if (results.length) { - searchResults.empty(); - $.each(results, function (index, result) { - var elem = document.getElementById(result.ref); - searchResults.append("
  • " + $(elem).text() + "
  • "); - }); - highlight.call(searchInput); - } else { - searchResults.html('
  • '); - $('.search-results li').text('No Results Found for "' + searchInput.value + '"'); - } - } else { - unhighlight(); - searchResults.removeClass('visible'); - } - } - - function highlight() { - if (this.value) content.highlight(this.value, highlightOpts); - } - - function unhighlight() { - content.unhighlight(highlightOpts); - } -})(); - diff --git a/samples/rest-notes-slate/slate/source/javascripts/app/_toc.js b/samples/rest-notes-slate/slate/source/javascripts/app/_toc.js deleted file mode 100644 index f70bdc0ff..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/app/_toc.js +++ /dev/null @@ -1,122 +0,0 @@ -//= require ../lib/_jquery -//= require ../lib/_imagesloaded.min -;(function () { - 'use strict'; - - var htmlPattern = /<[^>]*>/g; - var loaded = false; - - var debounce = function(func, waitTime) { - var timeout = false; - return function() { - if (timeout === false) { - setTimeout(function() { - func(); - timeout = false; - }, waitTime); - timeout = true; - } - }; - }; - - var closeToc = function() { - $(".toc-wrapper").removeClass('open'); - $("#nav-button").removeClass('open'); - }; - - function loadToc($toc, tocLinkSelector, tocListSelector, scrollOffset) { - var headerHeights = {}; - var pageHeight = 0; - var windowHeight = 0; - var originalTitle = document.title; - - var recacheHeights = function() { - headerHeights = {}; - pageHeight = $(document).height(); - windowHeight = $(window).height(); - - $toc.find(tocLinkSelector).each(function() { - var targetId = $(this).attr('href'); - if (targetId[0] === "#") { - headerHeights[targetId] = $("#" + $.escapeSelector(targetId.substring(1))).offset().top; - } - }); - }; - - var refreshToc = function() { - var currentTop = $(document).scrollTop() + scrollOffset; - - if (currentTop + windowHeight >= pageHeight) { - // at bottom of page, so just select last header by making currentTop very large - // this fixes the problem where the last header won't ever show as active if its content - // is shorter than the window height - currentTop = pageHeight + 1000; - } - - var best = null; - for (var name in headerHeights) { - if ((headerHeights[name] < currentTop && headerHeights[name] > headerHeights[best]) || best === null) { - best = name; - } - } - - // Catch the initial load case - if (currentTop == scrollOffset && !loaded) { - best = window.location.hash; - loaded = true; - } - - var $best = $toc.find("[href='" + best + "']").first(); - if (!$best.hasClass("active")) { - // .active is applied to the ToC link we're currently on, and its parent
      s selected by tocListSelector - // .active-expanded is applied to the ToC links that are parents of this one - $toc.find(".active").removeClass("active"); - $toc.find(".active-parent").removeClass("active-parent"); - $best.addClass("active"); - $best.parents(tocListSelector).addClass("active").siblings(tocLinkSelector).addClass('active-parent'); - $best.siblings(tocListSelector).addClass("active"); - $toc.find(tocListSelector).filter(":not(.active)").slideUp(150); - $toc.find(tocListSelector).filter(".active").slideDown(150); - if (window.history.replaceState) { - window.history.replaceState(null, "", best); - } - var thisTitle = $best.data("title"); - if (thisTitle !== undefined && thisTitle.length > 0) { - document.title = thisTitle.replace(htmlPattern, "") + " – " + originalTitle; - } else { - document.title = originalTitle; - } - } - }; - - var makeToc = function() { - recacheHeights(); - refreshToc(); - - $("#nav-button").click(function() { - $(".toc-wrapper").toggleClass('open'); - $("#nav-button").toggleClass('open'); - return false; - }); - $(".page-wrapper").click(closeToc); - $(".toc-link").click(closeToc); - - // reload immediately after scrolling on toc click - $toc.find(tocLinkSelector).click(function() { - setTimeout(function() { - refreshToc(); - }, 0); - }); - - $(window).scroll(debounce(refreshToc, 200)); - $(window).resize(debounce(recacheHeights, 200)); - }; - - makeToc(); - - window.recacheHeights = recacheHeights; - window.refreshToc = refreshToc; - } - - window.loadToc = loadToc; -})(); diff --git a/samples/rest-notes-slate/slate/source/javascripts/lib/_energize.js b/samples/rest-notes-slate/slate/source/javascripts/lib/_energize.js deleted file mode 100644 index 6798f3c03..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/lib/_energize.js +++ /dev/null @@ -1,169 +0,0 @@ -/** - * energize.js v0.1.0 - * - * Speeds up click events on mobile devices. - * https://github.com/davidcalhoun/energize.js - */ - -(function() { // Sandbox - /** - * Don't add to non-touch devices, which don't need to be sped up - */ - if(!('ontouchstart' in window)) return; - - var lastClick = {}, - isThresholdReached, touchstart, touchmove, touchend, - click, closest; - - /** - * isThresholdReached - * - * Compare touchstart with touchend xy coordinates, - * and only fire simulated click event if the coordinates - * are nearby. (don't want clicking to be confused with a swipe) - */ - isThresholdReached = function(startXY, xy) { - return Math.abs(startXY[0] - xy[0]) > 5 || Math.abs(startXY[1] - xy[1]) > 5; - }; - - /** - * touchstart - * - * Save xy coordinates when the user starts touching the screen - */ - touchstart = function(e) { - this.startXY = [e.touches[0].clientX, e.touches[0].clientY]; - this.threshold = false; - }; - - /** - * touchmove - * - * Check if the user is scrolling past the threshold. - * Have to check here because touchend will not always fire - * on some tested devices (Kindle Fire?) - */ - touchmove = function(e) { - // NOOP if the threshold has already been reached - if(this.threshold) return false; - - this.threshold = isThresholdReached(this.startXY, [e.touches[0].clientX, e.touches[0].clientY]); - }; - - /** - * touchend - * - * If the user didn't scroll past the threshold between - * touchstart and touchend, fire a simulated click. - * - * (This will fire before a native click) - */ - touchend = function(e) { - // Don't fire a click if the user scrolled past the threshold - if(this.threshold || isThresholdReached(this.startXY, [e.changedTouches[0].clientX, e.changedTouches[0].clientY])) { - return; - } - - /** - * Create and fire a click event on the target element - * https://developer.mozilla.org/en/DOM/event.initMouseEvent - */ - var touch = e.changedTouches[0], - evt = document.createEvent('MouseEvents'); - evt.initMouseEvent('click', true, true, window, 0, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); - evt.simulated = true; // distinguish from a normal (nonsimulated) click - e.target.dispatchEvent(evt); - }; - - /** - * click - * - * Because we've already fired a click event in touchend, - * we need to listed for all native click events here - * and suppress them as necessary. - */ - click = function(e) { - /** - * Prevent ghost clicks by only allowing clicks we created - * in the click event we fired (look for e.simulated) - */ - var time = Date.now(), - timeDiff = time - lastClick.time, - x = e.clientX, - y = e.clientY, - xyDiff = [Math.abs(lastClick.x - x), Math.abs(lastClick.y - y)], - target = closest(e.target, 'A') || e.target, // needed for standalone apps - nodeName = target.nodeName, - isLink = nodeName === 'A', - standAlone = window.navigator.standalone && isLink && e.target.getAttribute("href"); - - lastClick.time = time; - lastClick.x = x; - lastClick.y = y; - - /** - * Unfortunately Android sometimes fires click events without touch events (seen on Kindle Fire), - * so we have to add more logic to determine the time of the last click. Not perfect... - * - * Older, simpler check: if((!e.simulated) || standAlone) - */ - if((!e.simulated && (timeDiff < 500 || (timeDiff < 1500 && xyDiff[0] < 50 && xyDiff[1] < 50))) || standAlone) { - e.preventDefault(); - e.stopPropagation(); - if(!standAlone) return false; - } - - /** - * Special logic for standalone web apps - * See http://stackoverflow.com/questions/2898740/iphone-safari-web-app-opens-links-in-new-window - */ - if(standAlone) { - window.location = target.getAttribute("href"); - } - - /** - * Add an energize-focus class to the targeted link (mimics :focus behavior) - * TODO: test and/or remove? Does this work? - */ - if(!target || !target.classList) return; - target.classList.add("energize-focus"); - window.setTimeout(function(){ - target.classList.remove("energize-focus"); - }, 150); - }; - - /** - * closest - * @param {HTMLElement} node current node to start searching from. - * @param {string} tagName the (uppercase) name of the tag you're looking for. - * - * Find the closest ancestor tag of a given node. - * - * Starts at node and goes up the DOM tree looking for a - * matching nodeName, continuing until hitting document.body - */ - closest = function(node, tagName){ - var curNode = node; - - while(curNode !== document.body) { // go up the dom until we find the tag we're after - if(!curNode || curNode.nodeName === tagName) { return curNode; } // found - curNode = curNode.parentNode; // not found, so keep going up - } - - return null; // not found - }; - - /** - * Add all delegated event listeners - * - * All the events we care about bubble up to document, - * so we can take advantage of event delegation. - * - * Note: no need to wait for DOMContentLoaded here - */ - document.addEventListener('touchstart', touchstart, false); - document.addEventListener('touchmove', touchmove, false); - document.addEventListener('touchend', touchend, false); - document.addEventListener('click', click, true); // TODO: why does this use capture? - -})(); \ No newline at end of file diff --git a/samples/rest-notes-slate/slate/source/javascripts/lib/_imagesloaded.min.js b/samples/rest-notes-slate/slate/source/javascripts/lib/_imagesloaded.min.js deleted file mode 100644 index e443a77d6..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/lib/_imagesloaded.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * imagesLoaded PACKAGED v4.1.4 - * JavaScript is all like "You images are done yet or what?" - * MIT License - */ - -!function(e,t){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",t):"object"==typeof module&&module.exports?module.exports=t():e.EvEmitter=t()}("undefined"!=typeof window?window:this,function(){function e(){}var t=e.prototype;return t.on=function(e,t){if(e&&t){var i=this._events=this._events||{},n=i[e]=i[e]||[];return n.indexOf(t)==-1&&n.push(t),this}},t.once=function(e,t){if(e&&t){this.on(e,t);var i=this._onceEvents=this._onceEvents||{},n=i[e]=i[e]||{};return n[t]=!0,this}},t.off=function(e,t){var i=this._events&&this._events[e];if(i&&i.length){var n=i.indexOf(t);return n!=-1&&i.splice(n,1),this}},t.emitEvent=function(e,t){var i=this._events&&this._events[e];if(i&&i.length){i=i.slice(0),t=t||[];for(var n=this._onceEvents&&this._onceEvents[e],o=0;o (default options) - * $('#content').highlight('lorem'); - * - * // search for and highlight more terms at once - * // so you can save some time on traversing DOM - * $('#content').highlight(['lorem', 'ipsum']); - * $('#content').highlight('lorem ipsum'); - * - * // search only for entire word 'lorem' - * $('#content').highlight('lorem', { wordsOnly: true }); - * - * // don't ignore case during search of term 'lorem' - * $('#content').highlight('lorem', { caseSensitive: true }); - * - * // wrap every occurrance of term 'ipsum' in content - * // with - * $('#content').highlight('ipsum', { element: 'em', className: 'important' }); - * - * // remove default highlight - * $('#content').unhighlight(); - * - * // remove custom highlight - * $('#content').unhighlight({ element: 'em', className: 'important' }); - * - * - * Copyright (c) 2009 Bartek Szopka - * - * Licensed under MIT license. - * - */ - -jQuery.extend({ - highlight: function (node, re, nodeName, className) { - if (node.nodeType === 3) { - var match = node.data.match(re); - if (match) { - var highlight = document.createElement(nodeName || 'span'); - highlight.className = className || 'highlight'; - var wordNode = node.splitText(match.index); - wordNode.splitText(match[0].length); - var wordClone = wordNode.cloneNode(true); - highlight.appendChild(wordClone); - wordNode.parentNode.replaceChild(highlight, wordNode); - return 1; //skip added node in parent - } - } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children - !/(script|style)/i.test(node.tagName) && // ignore script and style nodes - !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted - for (var i = 0; i < node.childNodes.length; i++) { - i += jQuery.highlight(node.childNodes[i], re, nodeName, className); - } - } - return 0; - } -}); - -jQuery.fn.unhighlight = function (options) { - var settings = { className: 'highlight', element: 'span' }; - jQuery.extend(settings, options); - - return this.find(settings.element + "." + settings.className).each(function () { - var parent = this.parentNode; - parent.replaceChild(this.firstChild, this); - parent.normalize(); - }).end(); -}; - -jQuery.fn.highlight = function (words, options) { - var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false }; - jQuery.extend(settings, options); - - if (words.constructor === String) { - words = [words]; - } - words = jQuery.grep(words, function(word, i){ - return word != ''; - }); - words = jQuery.map(words, function(word, i) { - return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); - }); - if (words.length == 0) { return this; }; - - var flag = settings.caseSensitive ? "" : "i"; - var pattern = "(" + words.join("|") + ")"; - if (settings.wordsOnly) { - pattern = "\\b" + pattern + "\\b"; - } - var re = new RegExp(pattern, flag); - - return this.each(function () { - jQuery.highlight(this, re, settings.element, settings.className); - }); -}; - diff --git a/samples/rest-notes-slate/slate/source/javascripts/lib/_jquery.js b/samples/rest-notes-slate/slate/source/javascripts/lib/_jquery.js deleted file mode 100644 index fc6c299b7..000000000 --- a/samples/rest-notes-slate/slate/source/javascripts/lib/_jquery.js +++ /dev/null @@ -1,10881 +0,0 @@ -/*! - * jQuery JavaScript Library v3.6.0 - * https://jquery.com/ - * - * Includes Sizzle.js - * https://sizzlejs.com/ - * - * Copyright OpenJS Foundation and other contributors - * Released under the MIT license - * https://jquery.org/license - * - * Date: 2021-03-02T17:08Z - */ -( function( global, factory ) { - - "use strict"; - - if ( typeof module === "object" && typeof module.exports === "object" ) { - - // For CommonJS and CommonJS-like environments where a proper `window` - // is present, execute the factory and get jQuery. - // For environments that do not have a `window` with a `document` - // (such as Node.js), expose a factory as module.exports. - // This accentuates the need for the creation of a real `window`. - // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info. - module.exports = global.document ? - factory( global, true ) : - function( w ) { - if ( !w.document ) { - throw new Error( "jQuery requires a window with a document" ); - } - return factory( w ); - }; - } else { - factory( global ); - } - -// Pass this if window is not defined yet -} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { - -// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 -// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode -// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common -// enough that all such attempts are guarded in a try block. -"use strict"; - -var arr = []; - -var getProto = Object.getPrototypeOf; - -var slice = arr.slice; - -var flat = arr.flat ? function( array ) { - return arr.flat.call( array ); -} : function( array ) { - return arr.concat.apply( [], array ); -}; - - -var push = arr.push; - -var indexOf = arr.indexOf; - -var class2type = {}; - -var toString = class2type.toString; - -var hasOwn = class2type.hasOwnProperty; - -var fnToString = hasOwn.toString; - -var ObjectFunctionString = fnToString.call( Object ); - -var support = {}; - -var isFunction = function isFunction( obj ) { - - // Support: Chrome <=57, Firefox <=52 - // In some browsers, typeof returns "function" for HTML elements - // (i.e., `typeof document.createElement( "object" ) === "function"`). - // We don't want to classify *any* DOM node as a function. - // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5 - // Plus for old WebKit, typeof returns "function" for HTML collections - // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756) - return typeof obj === "function" && typeof obj.nodeType !== "number" && - typeof obj.item !== "function"; - }; - - -var isWindow = function isWindow( obj ) { - return obj != null && obj === obj.window; - }; - - -var document = window.document; - - - - var preservedScriptAttributes = { - type: true, - src: true, - nonce: true, - noModule: true - }; - - function DOMEval( code, node, doc ) { - doc = doc || document; - - var i, val, - script = doc.createElement( "script" ); - - script.text = code; - if ( node ) { - for ( i in preservedScriptAttributes ) { - - // Support: Firefox 64+, Edge 18+ - // Some browsers don't support the "nonce" property on scripts. - // On the other hand, just using `getAttribute` is not enough as - // the `nonce` attribute is reset to an empty string whenever it - // becomes browsing-context connected. - // See https://github.com/whatwg/html/issues/2369 - // See https://html.spec.whatwg.org/#nonce-attributes - // The `node.getAttribute` check was added for the sake of - // `jQuery.globalEval` so that it can fake a nonce-containing node - // via an object. - val = node[ i ] || node.getAttribute && node.getAttribute( i ); - if ( val ) { - script.setAttribute( i, val ); - } - } - } - doc.head.appendChild( script ).parentNode.removeChild( script ); - } - - -function toType( obj ) { - if ( obj == null ) { - return obj + ""; - } - - // Support: Android <=2.3 only (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call( obj ) ] || "object" : - typeof obj; -} -/* global Symbol */ -// Defining this global in .eslintrc.json would create a danger of using the global -// unguarded in another place, it seems safer to define global only for this module - - - -var - version = "3.6.0", - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }; - -jQuery.fn = jQuery.prototype = { - - // The current version of jQuery being used - jquery: version, - - constructor: jQuery, - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - - // Return all the elements in a clean array - if ( num == null ) { - return slice.call( this ); - } - - // Return just the one element from the set - return num < 0 ? this[ num + this.length ] : this[ num ]; - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - each: function( callback ) { - return jQuery.each( this, callback ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map( this, function( elem, i ) { - return callback.call( elem, i, elem ); - } ) ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - even: function() { - return this.pushStack( jQuery.grep( this, function( _elem, i ) { - return ( i + 1 ) % 2; - } ) ); - }, - - odd: function() { - return this.pushStack( jQuery.grep( this, function( _elem, i ) { - return i % 2; - } ) ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: arr.sort, - splice: arr.splice -}; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[ 0 ] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // Skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !isFunction( target ) ) { - target = {}; - } - - // Extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } - - for ( ; i < length; i++ ) { - - // Only deal with non-null/undefined values - if ( ( options = arguments[ i ] ) != null ) { - - // Extend the base object - for ( name in options ) { - copy = options[ name ]; - - // Prevent Object.prototype pollution - // Prevent never-ending loop - if ( name === "__proto__" || target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = Array.isArray( copy ) ) ) ) { - src = target[ name ]; - - // Ensure proper type for the source value - if ( copyIsArray && !Array.isArray( src ) ) { - clone = []; - } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { - clone = {}; - } else { - clone = src; - } - copyIsArray = false; - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend( { - - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - - // Assume jQuery is ready without the ready module - isReady: true, - - error: function( msg ) { - throw new Error( msg ); - }, - - noop: function() {}, - - isPlainObject: function( obj ) { - var proto, Ctor; - - // Detect obvious negatives - // Use toString instead of jQuery.type to catch host objects - if ( !obj || toString.call( obj ) !== "[object Object]" ) { - return false; - } - - proto = getProto( obj ); - - // Objects with no prototype (e.g., `Object.create( null )`) are plain - if ( !proto ) { - return true; - } - - // Objects with prototype are plain iff they were constructed by a global Object function - Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; - return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; - }, - - isEmptyObject: function( obj ) { - var name; - - for ( name in obj ) { - return false; - } - return true; - }, - - // Evaluates a script in a provided context; falls back to the global one - // if not specified. - globalEval: function( code, options, doc ) { - DOMEval( code, { nonce: options && options.nonce }, doc ); - }, - - each: function( obj, callback ) { - var length, i = 0; - - if ( isArrayLike( obj ) ) { - length = obj.length; - for ( ; i < length; i++ ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } else { - for ( i in obj ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } - - return obj; - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArrayLike( Object( arr ) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : indexOf.call( arr, elem, i ); - }, - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; - - for ( ; j < len; j++ ) { - first[ i++ ] = second[ j ]; - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); - } - } - - return matches; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var length, value, - i = 0, - ret = []; - - // Go through the array, translating each of the items to their new values - if ( isArrayLike( elems ) ) { - length = elems.length; - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - } - - // Flatten any nested arrays - return flat( ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support -} ); - -if ( typeof Symbol === "function" ) { - jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; -} - -// Populate the class2type map -jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), - function( _i, name ) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); - } ); - -function isArrayLike( obj ) { - - // Support: real iOS 8.2 only (not reproducible in simulator) - // `in` check used to prevent JIT error (gh-2145) - // hasOwn isn't used here due to false negatives - // regarding Nodelist length in IE - var length = !!obj && "length" in obj && obj.length, - type = toType( obj ); - - if ( isFunction( obj ) || isWindow( obj ) ) { - return false; - } - - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; -} -var Sizzle = -/*! - * Sizzle CSS Selector Engine v2.3.6 - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://js.foundation/ - * - * Date: 2021-02-16 - */ -( function( window ) { -var i, - support, - Expr, - getText, - isXML, - tokenize, - compile, - select, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + 1 * new Date(), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - nonnativeSelectorCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // Instance methods - hasOwn = ( {} ).hasOwnProperty, - arr = [], - pop = arr.pop, - pushNative = arr.push, - push = arr.push, - slice = arr.slice, - - // Use a stripped-down indexOf as it's faster than native - // https://jsperf.com/thor-indexof-vs-for/5 - indexOf = function( list, elem ) { - var i = 0, - len = list.length; - for ( ; i < len; i++ ) { - if ( list[ i ] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + - "ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - - // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram - identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + - "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", - - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + - - // Operator (capture 2) - "*([*^$|!~]?=)" + whitespace + - - // "Attribute values must be CSS identifiers [capture 5] - // or strings [capture 3 or capture 4]" - "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + - whitespace + "*\\]", - - pseudos = ":(" + identifier + ")(?:\\((" + - - // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: - // 1. quoted (capture 3; capture 4 or capture 5) - "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + - - // 2. simple (capture 6) - "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + - - // 3. anything else (capture 2) - ".*" + - ")\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rwhitespace = new RegExp( whitespace + "+", "g" ), - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + - whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + - "*" ), - rdescend = new RegExp( whitespace + "|>" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + identifier + ")" ), - "CLASS": new RegExp( "^\\.(" + identifier + ")" ), - "TAG": new RegExp( "^(" + identifier + "|[*])" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + - whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + - whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + - "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + - "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rhtml = /HTML$/i, - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - - // CSS escapes - // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), - funescape = function( escape, nonHex ) { - var high = "0x" + escape.slice( 1 ) - 0x10000; - - return nonHex ? - - // Strip the backslash prefix from a non-hex escape sequence - nonHex : - - // Replace a hexadecimal escape sequence with the encoded Unicode code point - // Support: IE <=11+ - // For values outside the Basic Multilingual Plane (BMP), manually construct a - // surrogate pair - high < 0 ? - String.fromCharCode( high + 0x10000 ) : - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }, - - // CSS string/identifier serialization - // https://drafts.csswg.org/cssom/#common-serializing-idioms - rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, - fcssescape = function( ch, asCodePoint ) { - if ( asCodePoint ) { - - // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER - if ( ch === "\0" ) { - return "\uFFFD"; - } - - // Control characters and (dependent upon position) numbers get escaped as code points - return ch.slice( 0, -1 ) + "\\" + - ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; - } - - // Other potentially-special ASCII characters get backslash-escaped - return "\\" + ch; - }, - - // Used for iframes - // See setDocument() - // Removing the function wrapper causes a "Permission Denied" - // error in IE - unloadHandler = function() { - setDocument(); - }, - - inDisabledFieldset = addCombinator( - function( elem ) { - return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; - }, - { dir: "parentNode", next: "legend" } - ); - -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - ( arr = slice.call( preferredDoc.childNodes ) ), - preferredDoc.childNodes - ); - - // Support: Android<4.0 - // Detect silently failing push.apply - // eslint-disable-next-line no-unused-expressions - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - pushNative.apply( target, slice.call( els ) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - - // Can't trust NodeList.length - while ( ( target[ j++ ] = els[ i++ ] ) ) {} - target.length = j - 1; - } - }; -} - -function Sizzle( selector, context, results, seed ) { - var m, i, elem, nid, match, groups, newSelector, - newContext = context && context.ownerDocument, - - // nodeType defaults to 9, since context defaults to document - nodeType = context ? context.nodeType : 9; - - results = results || []; - - // Return early from calls with invalid selector or context - if ( typeof selector !== "string" || !selector || - nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { - - return results; - } - - // Try to shortcut find operations (as opposed to filters) in HTML documents - if ( !seed ) { - setDocument( context ); - context = context || document; - - if ( documentIsHTML ) { - - // If the selector is sufficiently simple, try using a "get*By*" DOM method - // (excepting DocumentFragment context, where the methods don't exist) - if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { - - // ID selector - if ( ( m = match[ 1 ] ) ) { - - // Document context - if ( nodeType === 9 ) { - if ( ( elem = context.getElementById( m ) ) ) { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - - // Element context - } else { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( newContext && ( elem = newContext.getElementById( m ) ) && - contains( context, elem ) && - elem.id === m ) { - - results.push( elem ); - return results; - } - } - - // Type selector - } else if ( match[ 2 ] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Class selector - } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && - context.getElementsByClassName ) { - - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // Take advantage of querySelectorAll - if ( support.qsa && - !nonnativeSelectorCache[ selector + " " ] && - ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && - - // Support: IE 8 only - // Exclude object elements - ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { - - newSelector = selector; - newContext = context; - - // qSA considers elements outside a scoping root when evaluating child or - // descendant combinators, which is not what we want. - // In such cases, we work around the behavior by prefixing every selector in the - // list with an ID selector referencing the scope context. - // The technique has to be used as well when a leading combinator is used - // as such selectors are not recognized by querySelectorAll. - // Thanks to Andrew Dupont for this technique. - if ( nodeType === 1 && - ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { - - // Expand context for sibling selectors - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || - context; - - // We can use :scope instead of the ID hack if the browser - // supports it & if we're not changing the context. - if ( newContext !== context || !support.scope ) { - - // Capture the context ID, setting it first if necessary - if ( ( nid = context.getAttribute( "id" ) ) ) { - nid = nid.replace( rcssescape, fcssescape ); - } else { - context.setAttribute( "id", ( nid = expando ) ); - } - } - - // Prefix every selector in the list - groups = tokenize( selector ); - i = groups.length; - while ( i-- ) { - groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + - toSelector( groups[ i ] ); - } - newSelector = groups.join( "," ); - } - - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - nonnativeSelectorCache( selector, true ); - } finally { - if ( nid === expando ) { - context.removeAttribute( "id" ); - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * Create key-value caches of limited size - * @returns {function(string, object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; - - function cache( key, value ) { - - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return ( cache[ key + " " ] = value ); - } - return cache; -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created element and returns a boolean result - */ -function assert( fn ) { - var el = document.createElement( "fieldset" ); - - try { - return !!fn( el ); - } catch ( e ) { - return false; - } finally { - - // Remove from its parent by default - if ( el.parentNode ) { - el.parentNode.removeChild( el ); - } - - // release memory in IE - el = null; - } -} - -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split( "|" ), - i = arr.length; - - while ( i-- ) { - Expr.attrHandle[ arr[ i ] ] = handler; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - a.sourceIndex - b.sourceIndex; - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( ( cur = cur.nextSibling ) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return ( name === "input" || name === "button" ) && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for :enabled/:disabled - * @param {Boolean} disabled true for :disabled; false for :enabled - */ -function createDisabledPseudo( disabled ) { - - // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable - return function( elem ) { - - // Only certain elements can match :enabled or :disabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled - if ( "form" in elem ) { - - // Check for inherited disabledness on relevant non-disabled elements: - // * listed form-associated elements in a disabled fieldset - // https://html.spec.whatwg.org/multipage/forms.html#category-listed - // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled - // * option elements in a disabled optgroup - // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled - // All such elements have a "form" property. - if ( elem.parentNode && elem.disabled === false ) { - - // Option elements defer to a parent optgroup if present - if ( "label" in elem ) { - if ( "label" in elem.parentNode ) { - return elem.parentNode.disabled === disabled; - } else { - return elem.disabled === disabled; - } - } - - // Support: IE 6 - 11 - // Use the isDisabled shortcut property to check for disabled fieldset ancestors - return elem.isDisabled === disabled || - - // Where there is no isDisabled, check manually - /* jshint -W018 */ - elem.isDisabled !== !disabled && - inDisabledFieldset( elem ) === disabled; - } - - return elem.disabled === disabled; - - // Try to winnow out elements that can't be disabled before trusting the disabled property. - // Some victims get caught in our net (label, legend, menu, track), but it shouldn't - // even exist on them, let alone have a boolean value. - } else if ( "label" in elem ) { - return elem.disabled === disabled; - } - - // Remaining elements are neither :enabled nor :disabled - return false; - }; -} - -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction( function( argument ) { - argument = +argument; - return markFunction( function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ ( j = matchIndexes[ i ] ) ] ) { - seed[ j ] = !( matches[ j ] = seed[ j ] ); - } - } - } ); - } ); -} - -/** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ -function testContext( context ) { - return context && typeof context.getElementsByTagName !== "undefined" && context; -} - -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - var namespace = elem && elem.namespaceURI, - docElem = elem && ( elem.ownerDocument || elem ).documentElement; - - // Support: IE <=8 - // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes - // https://bugs.jquery.com/ticket/4833 - return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, subWindow, - doc = node ? node.ownerDocument || node : preferredDoc; - - // Return early if doc is invalid or already selected - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Update global variables - document = doc; - docElem = document.documentElement; - documentIsHTML = !isXML( document ); - - // Support: IE 9 - 11+, Edge 12 - 18+ - // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( preferredDoc != document && - ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { - - // Support: IE 11, Edge - if ( subWindow.addEventListener ) { - subWindow.addEventListener( "unload", unloadHandler, false ); - - // Support: IE 9 - 10 only - } else if ( subWindow.attachEvent ) { - subWindow.attachEvent( "onunload", unloadHandler ); - } - } - - // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, - // Safari 4 - 5 only, Opera <=11.6 - 12.x only - // IE/Edge & older browsers don't support the :scope pseudo-class. - // Support: Safari 6.0 only - // Safari 6.0 supports :scope but it's an alias of :root there. - support.scope = assert( function( el ) { - docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); - return typeof el.querySelectorAll !== "undefined" && - !el.querySelectorAll( ":scope fieldset div" ).length; - } ); - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties - // (excepting IE8 booleans) - support.attributes = assert( function( el ) { - el.className = "i"; - return !el.getAttribute( "className" ); - } ); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert( function( el ) { - el.appendChild( document.createComment( "" ) ); - return !el.getElementsByTagName( "*" ).length; - } ); - - // Support: IE<9 - support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programmatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert( function( el ) { - docElem.appendChild( el ).id = expando; - return !document.getElementsByName || !document.getElementsByName( expando ).length; - } ); - - // ID filter and find - if ( support.getById ) { - Expr.filter[ "ID" ] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute( "id" ) === attrId; - }; - }; - Expr.find[ "ID" ] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var elem = context.getElementById( id ); - return elem ? [ elem ] : []; - } - }; - } else { - Expr.filter[ "ID" ] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== "undefined" && - elem.getAttributeNode( "id" ); - return node && node.value === attrId; - }; - }; - - // Support: IE 6 - 7 only - // getElementById is not reliable as a find shortcut - Expr.find[ "ID" ] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var node, i, elems, - elem = context.getElementById( id ); - - if ( elem ) { - - // Verify the id attribute - node = elem.getAttributeNode( "id" ); - if ( node && node.value === id ) { - return [ elem ]; - } - - // Fall back on getElementsByName - elems = context.getElementsByName( id ); - i = 0; - while ( ( elem = elems[ i++ ] ) ) { - node = elem.getAttributeNode( "id" ); - if ( node && node.value === id ) { - return [ elem ]; - } - } - } - - return []; - } - }; - } - - // Tag - Expr.find[ "TAG" ] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( tag ); - - // DocumentFragment nodes don't have gEBTN - } else if ( support.qsa ) { - return context.querySelectorAll( tag ); - } - } : - - function( tag, context ) { - var elem, - tmp = [], - i = 0, - - // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( ( elem = results[ i++ ] ) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See https://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { - - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert( function( el ) { - - var input; - - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // https://bugs.jquery.com/ticket/12359 - docElem.appendChild( el ).innerHTML = "" + - ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !el.querySelectorAll( "[selected]" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { - rbuggyQSA.push( "~=" ); - } - - // Support: IE 11+, Edge 15 - 18+ - // IE 11/Edge don't find elements on a `[name='']` query in some cases. - // Adding a temporary attribute to the document before the selection works - // around the issue. - // Interestingly, IE 10 & older don't seem to have the issue. - input = document.createElement( "input" ); - input.setAttribute( "name", "" ); - el.appendChild( input ); - if ( !el.querySelectorAll( "[name='']" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + - whitespace + "*(?:''|\"\")" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !el.querySelectorAll( ":checked" ).length ) { - rbuggyQSA.push( ":checked" ); - } - - // Support: Safari 8+, iOS 8+ - // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibling-combinator selector` fails - if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { - rbuggyQSA.push( ".#.+[+~]" ); - } - - // Support: Firefox <=3.6 - 5 only - // Old Firefox doesn't throw on a badly-escaped identifier. - el.querySelectorAll( "\\\f" ); - rbuggyQSA.push( "[\\r\\n\\f]" ); - } ); - - assert( function( el ) { - el.innerHTML = "" + - ""; - - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = document.createElement( "input" ); - input.setAttribute( "type", "hidden" ); - el.appendChild( input ).setAttribute( "name", "D" ); - - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( el.querySelectorAll( "[name=d]" ).length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: IE9-11+ - // IE's :disabled selector does not pick up the children of disabled fieldsets - docElem.appendChild( el ).disabled = true; - if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: Opera 10 - 11 only - // Opera 10-11 does not throw on post-comma invalid pseudos - el.querySelectorAll( "*,:x" ); - rbuggyQSA.push( ",.*:" ); - } ); - } - - if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector ) ) ) ) { - - assert( function( el ) { - - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( el, "*" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( el, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - } ); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully self-exclusive - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - ) ); - } : - function( a, b ) { - if ( b ) { - while ( ( b = b.parentNode ) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } - - // Calculate position if both inputs belong to the same document - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : - - // Otherwise we know they are disconnected - 1; - - // Disconnected nodes - if ( compare & 1 || - ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { - - // Choose the first element that is related to our preferred document - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( a == document || a.ownerDocument == preferredDoc && - contains( preferredDoc, a ) ) { - return -1; - } - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( b == document || b.ownerDocument == preferredDoc && - contains( preferredDoc, b ) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - return a == document ? -1 : - b == document ? 1 : - /* eslint-enable eqeqeq */ - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( ( cur = cur.parentNode ) ) { - ap.unshift( cur ); - } - cur = b; - while ( ( cur = cur.parentNode ) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[ i ] === bp[ i ] ) { - i++; - } - - return i ? - - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[ i ], bp[ i ] ) : - - // Otherwise nodes in our document sort first - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - ap[ i ] == preferredDoc ? -1 : - bp[ i ] == preferredDoc ? 1 : - /* eslint-enable eqeqeq */ - 0; - }; - - return document; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - setDocument( elem ); - - if ( support.matchesSelector && documentIsHTML && - !nonnativeSelectorCache[ expr + " " ] && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch ( e ) { - nonnativeSelectorCache( expr, true ); - } - } - - return Sizzle( expr, document, null, [ elem ] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - - // Set document vars if needed - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( ( context.ownerDocument || context ) != document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - - // Set document vars if needed - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( ( elem.ownerDocument || elem ) != document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; -}; - -Sizzle.escape = function( sel ) { - return ( sel + "" ).replace( rcssescape, fcssescape ); -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( ( elem = results[ i++ ] ) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - - // If no nodeType, this is expected to be an array - while ( ( node = elem[ i++ ] ) ) { - - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[ 1 ] = match[ 1 ].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[ 3 ] = ( match[ 3 ] || match[ 4 ] || - match[ 5 ] || "" ).replace( runescape, funescape ); - - if ( match[ 2 ] === "~=" ) { - match[ 3 ] = " " + match[ 3 ] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[ 1 ] = match[ 1 ].toLowerCase(); - - if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { - - // nth-* requires argument - if ( !match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[ 4 ] = +( match[ 4 ] ? - match[ 5 ] + ( match[ 6 ] || 1 ) : - 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); - match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); - - // other types prohibit arguments - } else if ( match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[ 6 ] && match[ 2 ]; - - if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[ 3 ] ) { - match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - - // Get excess from tokenize (recursively) - ( excess = tokenize( unquoted, true ) ) && - - // advance to the next closing parenthesis - ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { - - // excess is a negative index - match[ 0 ] = match[ 0 ].slice( 0, excess ); - match[ 2 ] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { - return true; - } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - ( pattern = new RegExp( "(^|" + whitespace + - ")" + className + "(" + whitespace + "|$)" ) ) && classCache( - className, function( elem ) { - return pattern.test( - typeof elem.className === "string" && elem.className || - typeof elem.getAttribute !== "undefined" && - elem.getAttribute( "class" ) || - "" - ); - } ); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - /* eslint-disable max-len */ - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - /* eslint-enable max-len */ - - }; - }, - - "CHILD": function( type, what, _argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, _context, xml ) { - var cache, uniqueCache, outerCache, node, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType, - diff = false; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( ( node = node[ dir ] ) ) { - if ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) { - - return false; - } - } - - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - - // Seek `elem` from a previously-cached index - - // ...in a gzip-friendly way - node = parent; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex && cache[ 2 ]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( ( node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - ( diff = nodeIndex = 0 ) || start.pop() ) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - } else { - - // Use previously-cached element index if available - if ( useCache ) { - - // ...in a gzip-friendly way - node = elem; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex; - } - - // xml :nth-child(...) - // or :nth-last-child(...) or :nth(-last)?-of-type(...) - if ( diff === false ) { - - // Use the same loop as above to seek `elem` from the start - while ( ( node = ++nodeIndex && node && node[ dir ] || - ( diff = nodeIndex = 0 ) || start.pop() ) ) { - - if ( ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) && - ++diff ) { - - // Cache the index of each encountered element - if ( useCache ) { - outerCache = node[ expando ] || - ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - uniqueCache[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction( function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf( seed, matched[ i ] ); - seed[ idx ] = !( matches[ idx ] = matched[ i ] ); - } - } ) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - - // Potentially complex pseudos - "not": markFunction( function( selector ) { - - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction( function( seed, matches, _context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( ( elem = unmatched[ i ] ) ) { - seed[ i ] = !( matches[ i ] = elem ); - } - } - } ) : - function( elem, _context, xml ) { - input[ 0 ] = elem; - matcher( input, null, xml, results ); - - // Don't keep the element (issue #299) - input[ 0 ] = null; - return !results.pop(); - }; - } ), - - "has": markFunction( function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - } ), - - "contains": markFunction( function( text ) { - text = text.replace( runescape, funescape ); - return function( elem ) { - return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; - }; - } ), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - - // lang value must be a valid identifier - if ( !ridentifier.test( lang || "" ) ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( ( elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); - return false; - }; - } ), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && - ( !document.hasFocus || document.hasFocus() ) && - !!( elem.type || elem.href || ~elem.tabIndex ); - }, - - // Boolean properties - "enabled": createDisabledPseudo( false ), - "disabled": createDisabledPseudo( true ), - - "checked": function( elem ) { - - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return ( nodeName === "input" && !!elem.checked ) || - ( nodeName === "option" && !!elem.selected ); - }, - - "selected": function( elem ) { - - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - // eslint-disable-next-line no-unused-expressions - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos[ "empty" ]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( ( attr = elem.getAttribute( "type" ) ) == null || - attr.toLowerCase() === "text" ); - }, - - // Position-in-collection - "first": createPositionalPseudo( function() { - return [ 0 ]; - } ), - - "last": createPositionalPseudo( function( _matchIndexes, length ) { - return [ length - 1 ]; - } ), - - "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - } ), - - "even": createPositionalPseudo( function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "odd": createPositionalPseudo( function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { - var i = argument < 0 ? - argument + length : - argument > length ? - length : - argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ) - } -}; - -Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -tokenize = Sizzle.tokenize = function( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || ( match = rcomma.exec( soFar ) ) ) { - if ( match ) { - - // Don't consume trailing commas as valid - soFar = soFar.slice( match[ 0 ].length ) || soFar; - } - groups.push( ( tokens = [] ) ); - } - - matched = false; - - // Combinators - if ( ( match = rcombinators.exec( soFar ) ) ) { - matched = match.shift(); - tokens.push( { - value: matched, - - // Cast descendant combinators to space - type: match[ 0 ].replace( rtrim, " " ) - } ); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || - ( match = preFilters[ type ]( match ) ) ) ) { - matched = match.shift(); - tokens.push( { - value: matched, - type: type, - matches: match - } ); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -}; - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[ i ].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - skip = combinator.next, - key = skip || dir, - checkNonElements = base && key === "parentNode", - doneName = done++; - - return combinator.first ? - - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - return false; - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, uniqueCache, outerCache, - newCache = [ dirruns, doneName ]; - - // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching - if ( xml ) { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || ( elem[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ elem.uniqueID ] || - ( outerCache[ elem.uniqueID ] = {} ); - - if ( skip && skip === elem.nodeName.toLowerCase() ) { - elem = elem[ dir ] || elem; - } else if ( ( oldCache = uniqueCache[ key ] ) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return ( newCache[ 2 ] = oldCache[ 2 ] ); - } else { - - // Reuse newcache so results back-propagate to previous elements - uniqueCache[ key ] = newCache; - - // A match means we're done; a fail means we have to keep checking - if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { - return true; - } - } - } - } - } - return false; - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[ i ]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[ 0 ]; -} - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[ i ], results ); - } - return results; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( ( elem = unmatched[ i ] ) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction( function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( - selector || "*", - context.nodeType ? [ context ] : context, - [] - ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( ( elem = temp[ i ] ) ) { - matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( ( elem = matcherOut[ i ] ) ) { - - // Restore matcherIn since elem is not yet a final match - temp.push( ( matcherIn[ i ] = elem ) ); - } - } - postFinder( null, ( matcherOut = [] ), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( ( elem = matcherOut[ i ] ) && - ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { - - seed[ temp ] = !( results[ temp ] = elem ); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - } ); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[ 0 ].type ], - implicitRelative = leadingRelative || Expr.relative[ " " ], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - ( checkContext = context ).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - - // Avoid hanging onto element (issue #299) - checkContext = null; - return ret; - } ]; - - for ( ; i < len; i++ ) { - if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { - matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; - } else { - matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[ j ].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens - .slice( 0, i - 1 ) - .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), - - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), - len = elems.length; - - if ( outermost ) { - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - outermostContext = context == document || context || outermost; - } - - // Add elements passing elementMatchers directly to results - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( !context && elem.ownerDocument != document ) { - setDocument( elem ); - xml = !documentIsHTML; - } - while ( ( matcher = elementMatchers[ j++ ] ) ) { - if ( matcher( elem, context || document, xml ) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - - // They will have gone through all possible matchers - if ( ( elem = !matcher && elem ) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // `i` is now the count of elements visited above, and adding it to `matchedCount` - // makes the latter nonnegative. - matchedCount += i; - - // Apply set filters to unmatched elements - // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` - // equals `i`), unless we didn't visit _any_ elements in the above loop because we have - // no element matchers and no seed. - // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that - // case, which will result in a "00" `matchedCount` that differs from `i` but is also - // numerically zero. - if ( bySet && i !== matchedCount ) { - j = 0; - while ( ( matcher = setMatchers[ j++ ] ) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !( unmatched[ i ] || setMatched[ i ] ) ) { - setMatched[ i ] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - - // Generate a function of recursive functions that can be used to check each element - if ( !match ) { - match = tokenize( selector ); - } - i = match.length; - while ( i-- ) { - cached = matcherFromTokens( match[ i ] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( - selector, - matcherFromGroupMatchers( elementMatchers, setMatchers ) - ); - - // Save selector and tokenization - cached.selector = selector; - } - return cached; -}; - -/** - * A low-level selection function that works with Sizzle's compiled - * selector functions - * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile - * @param {Element} context - * @param {Array} [results] - * @param {Array} [seed] A set of elements to match against - */ -select = Sizzle.select = function( selector, context, results, seed ) { - var i, tokens, token, type, find, - compiled = typeof selector === "function" && selector, - match = !seed && tokenize( ( selector = compiled.selector || selector ) ); - - results = results || []; - - // Try to minimize operations if there is only one selector in the list and no seed - // (the latter of which guarantees us context) - if ( match.length === 1 ) { - - // Reduce context if the leading compound selector is an ID - tokens = match[ 0 ] = match[ 0 ].slice( 0 ); - if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && - context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { - - context = ( Expr.find[ "ID" ]( token.matches[ 0 ] - .replace( runescape, funescape ), context ) || [] )[ 0 ]; - if ( !context ) { - return results; - - // Precompiled matchers will still verify ancestry, so step up a level - } else if ( compiled ) { - context = context.parentNode; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[ i ]; - - // Abort if we hit a combinator - if ( Expr.relative[ ( type = token.type ) ] ) { - break; - } - if ( ( find = Expr.find[ type ] ) ) { - - // Search, expanding context for leading sibling combinators - if ( ( seed = find( - token.matches[ 0 ].replace( runescape, funescape ), - rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || - context - ) ) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - - // Compile and execute a filtering function if one is not provided - // Provide `match` to avoid retokenization if we modified the selector above - ( compiled || compile( selector, match ) )( - seed, - context, - !documentIsHTML, - results, - !context || rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; -}; - -// One-time assignments - -// Sort stability -support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; - -// Support: Chrome 14-35+ -// Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; - -// Initialize against the default document -setDocument(); - -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) -// Detached nodes confoundingly follow *each other* -support.sortDetached = assert( function( el ) { - - // Should return 1, but returns 4 (following) - return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; -} ); - -// Support: IE<8 -// Prevent attribute/property "interpolation" -// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert( function( el ) { - el.innerHTML = ""; - return el.firstChild.getAttribute( "href" ) === "#"; -} ) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - } ); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert( function( el ) { - el.innerHTML = ""; - el.firstChild.setAttribute( "value", "" ); - return el.firstChild.getAttribute( "value" ) === ""; -} ) ) { - addHandle( "value", function( elem, _name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - } ); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert( function( el ) { - return el.getAttribute( "disabled" ) == null; -} ) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; - } - } ); -} - -return Sizzle; - -} )( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; - -// Deprecated -jQuery.expr[ ":" ] = jQuery.expr.pseudos; -jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; -jQuery.escapeSelector = Sizzle.escape; - - - - -var dir = function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; -}; - - -var siblings = function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; -}; - - -var rneedsContext = jQuery.expr.match.needsContext; - - - -function nodeName( elem, name ) { - - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - -} -var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); - - - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - return !!qualifier.call( elem, i, elem ) !== not; - } ); - } - - // Single element - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - } ); - } - - // Arraylike of elements (jQuery, arguments, Array) - if ( typeof qualifier !== "string" ) { - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not; - } ); - } - - // Filtered directly for both simple and complex selectors - return jQuery.filter( qualifier, elements, not ); -} - -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - if ( elems.length === 1 && elem.nodeType === 1 ) { - return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; - } - - return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - } ) ); -}; - -jQuery.fn.extend( { - find: function( selector ) { - var i, ret, - len = this.length, - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter( function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - } ) ); - } - - ret = this.pushStack( [] ); - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - return len > 1 ? jQuery.uniqueSort( ret ) : ret; - }, - filter: function( selector ) { - return this.pushStack( winnow( this, selector || [], false ) ); - }, - not: function( selector ) { - return this.pushStack( winnow( this, selector || [], true ) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } -} ); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) -var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - // Shortcut simple #id case for speed - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, - - init = jQuery.fn.init = function( selector, context, root ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Method init() accepts an alternate rootjQuery - // so migrate can support jQuery.sub (gh-2101) - root = root || rootjQuery; - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[ 0 ] === "<" && - selector[ selector.length - 1 ] === ">" && - selector.length >= 3 ) { - - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && ( match[ 1 ] || !context ) ) { - - // HANDLE: $(html) -> $(array) - if ( match[ 1 ] ) { - context = context instanceof jQuery ? context[ 0 ] : context; - - // Option to run scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[ 1 ], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - - // Properties of context are called as methods if possible - if ( isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[ 2 ] ); - - if ( elem ) { - - // Inject the element directly into the jQuery object - this[ 0 ] = elem; - this.length = 1; - } - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || root ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this[ 0 ] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( isFunction( selector ) ) { - return root.ready !== undefined ? - root.ready( selector ) : - - // Execute immediately if ready is not present - selector( jQuery ); - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; - -// Initialize central reference -rootjQuery = jQuery( document ); - - -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - - // Methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend( { - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter( function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[ i ] ) ) { - return true; - } - } - } ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - targets = typeof selectors !== "string" && jQuery( selectors ); - - // Positional selectors never match, since there's no _selection_ context - if ( !rneedsContext.test( selectors ) ) { - for ( ; i < l; i++ ) { - for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - - // Always skip document fragments - if ( cur.nodeType < 11 && ( targets ? - targets.index( cur ) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector( cur, selectors ) ) ) { - - matched.push( cur ); - break; - } - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); - }, - - // Determine the position of an element within the set - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // Index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.uniqueSort( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - } -} ); - -function sibling( cur, dir ) { - while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} - return cur; -} - -jQuery.each( { - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, _i, until ) { - return dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, _i, until ) { - return dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, _i, until ) { - return dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return siblings( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return siblings( elem.firstChild ); - }, - contents: function( elem ) { - if ( elem.contentDocument != null && - - // Support: IE 11+ - // elements with no `data` attribute has an object - // `contentDocument` with a `null` prototype. - getProto( elem.contentDocument ) ) { - - return elem.contentDocument; - } - - // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only - // Treat the template element as a regular one in browsers that - // don't support it. - if ( nodeName( elem, "template" ) ) { - elem = elem.content || elem; - } - - return jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.uniqueSort( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -} ); -var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); - - - -// Convert String-formatted options into Object-formatted ones -function createOptions( options ) { - var object = {}; - jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { - object[ flag ] = true; - } ); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - createOptions( options ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - - // Last fire value for non-forgettable lists - memory, - - // Flag to know if list was already fired - fired, - - // Flag to prevent firing - locked, - - // Actual callback list - list = [], - - // Queue of execution data for repeatable lists - queue = [], - - // Index of currently firing callback (modified by add/remove as needed) - firingIndex = -1, - - // Fire callbacks - fire = function() { - - // Enforce single-firing - locked = locked || options.once; - - // Execute callbacks for all pending executions, - // respecting firingIndex overrides and runtime changes - fired = firing = true; - for ( ; queue.length; firingIndex = -1 ) { - memory = queue.shift(); - while ( ++firingIndex < list.length ) { - - // Run callback and check for early termination - if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && - options.stopOnFalse ) { - - // Jump to end and forget the data so .add doesn't re-fire - firingIndex = list.length; - memory = false; - } - } - } - - // Forget the data if we're done with it - if ( !options.memory ) { - memory = false; - } - - firing = false; - - // Clean up if we're done firing for good - if ( locked ) { - - // Keep an empty list if we have data for future add calls - if ( memory ) { - list = []; - - // Otherwise, this object is spent - } else { - list = ""; - } - } - }, - - // Actual Callbacks object - self = { - - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - - // If we have memory from a past run, we should fire after adding - if ( memory && !firing ) { - firingIndex = list.length - 1; - queue.push( memory ); - } - - ( function add( args ) { - jQuery.each( args, function( _, arg ) { - if ( isFunction( arg ) ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && toType( arg ) !== "string" ) { - - // Inspect recursively - add( arg ); - } - } ); - } )( arguments ); - - if ( memory && !firing ) { - fire(); - } - } - return this; - }, - - // Remove a callback from the list - remove: function() { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - - // Handle firing indexes - if ( index <= firingIndex ) { - firingIndex--; - } - } - } ); - return this; - }, - - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? - jQuery.inArray( fn, list ) > -1 : - list.length > 0; - }, - - // Remove all callbacks from the list - empty: function() { - if ( list ) { - list = []; - } - return this; - }, - - // Disable .fire and .add - // Abort any current/pending executions - // Clear all callbacks and values - disable: function() { - locked = queue = []; - list = memory = ""; - return this; - }, - disabled: function() { - return !list; - }, - - // Disable .fire - // Also disable .add unless we have memory (since it would have no effect) - // Abort any pending executions - lock: function() { - locked = queue = []; - if ( !memory && !firing ) { - list = memory = ""; - } - return this; - }, - locked: function() { - return !!locked; - }, - - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( !locked ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - queue.push( args ); - if ( !firing ) { - fire(); - } - } - return this; - }, - - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - -function Identity( v ) { - return v; -} -function Thrower( ex ) { - throw ex; -} - -function adoptValue( value, resolve, reject, noValue ) { - var method; - - try { - - // Check for promise aspect first to privilege synchronous behavior - if ( value && isFunction( ( method = value.promise ) ) ) { - method.call( value ).done( resolve ).fail( reject ); - - // Other thenables - } else if ( value && isFunction( ( method = value.then ) ) ) { - method.call( value, resolve, reject ); - - // Other non-thenables - } else { - - // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: - // * false: [ value ].slice( 0 ) => resolve( value ) - // * true: [ value ].slice( 1 ) => resolve() - resolve.apply( undefined, [ value ].slice( noValue ) ); - } - - // For Promises/A+, convert exceptions into rejections - // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in - // Deferred#then to conditionally suppress rejection. - } catch ( value ) { - - // Support: Android 4.0 only - // Strict mode functions invoked without .call/.apply get global-object context - reject.apply( undefined, [ value ] ); - } -} - -jQuery.extend( { - - Deferred: function( func ) { - var tuples = [ - - // action, add listener, callbacks, - // ... .then handlers, argument index, [final state] - [ "notify", "progress", jQuery.Callbacks( "memory" ), - jQuery.Callbacks( "memory" ), 2 ], - [ "resolve", "done", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 0, "resolved" ], - [ "reject", "fail", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 1, "rejected" ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - "catch": function( fn ) { - return promise.then( null, fn ); - }, - - // Keep pipe for back-compat - pipe: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - - return jQuery.Deferred( function( newDefer ) { - jQuery.each( tuples, function( _i, tuple ) { - - // Map tuples (progress, done, fail) to arguments (done, fail, progress) - var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; - - // deferred.progress(function() { bind to newDefer or newDefer.notify }) - // deferred.done(function() { bind to newDefer or newDefer.resolve }) - // deferred.fail(function() { bind to newDefer or newDefer.reject }) - deferred[ tuple[ 1 ] ]( function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && isFunction( returned.promise ) ) { - returned.promise() - .progress( newDefer.notify ) - .done( newDefer.resolve ) - .fail( newDefer.reject ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( - this, - fn ? [ returned ] : arguments - ); - } - } ); - } ); - fns = null; - } ).promise(); - }, - then: function( onFulfilled, onRejected, onProgress ) { - var maxDepth = 0; - function resolve( depth, deferred, handler, special ) { - return function() { - var that = this, - args = arguments, - mightThrow = function() { - var returned, then; - - // Support: Promises/A+ section 2.3.3.3.3 - // https://promisesaplus.com/#point-59 - // Ignore double-resolution attempts - if ( depth < maxDepth ) { - return; - } - - returned = handler.apply( that, args ); - - // Support: Promises/A+ section 2.3.1 - // https://promisesaplus.com/#point-48 - if ( returned === deferred.promise() ) { - throw new TypeError( "Thenable self-resolution" ); - } - - // Support: Promises/A+ sections 2.3.3.1, 3.5 - // https://promisesaplus.com/#point-54 - // https://promisesaplus.com/#point-75 - // Retrieve `then` only once - then = returned && - - // Support: Promises/A+ section 2.3.4 - // https://promisesaplus.com/#point-64 - // Only check objects and functions for thenability - ( typeof returned === "object" || - typeof returned === "function" ) && - returned.then; - - // Handle a returned thenable - if ( isFunction( then ) ) { - - // Special processors (notify) just wait for resolution - if ( special ) { - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ) - ); - - // Normal processors (resolve) also hook into progress - } else { - - // ...and disregard older resolution values - maxDepth++; - - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ), - resolve( maxDepth, deferred, Identity, - deferred.notifyWith ) - ); - } - - // Handle all other returned values - } else { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Identity ) { - that = undefined; - args = [ returned ]; - } - - // Process the value(s) - // Default process is resolve - ( special || deferred.resolveWith )( that, args ); - } - }, - - // Only normal processors (resolve) catch and reject exceptions - process = special ? - mightThrow : - function() { - try { - mightThrow(); - } catch ( e ) { - - if ( jQuery.Deferred.exceptionHook ) { - jQuery.Deferred.exceptionHook( e, - process.stackTrace ); - } - - // Support: Promises/A+ section 2.3.3.3.4.1 - // https://promisesaplus.com/#point-61 - // Ignore post-resolution exceptions - if ( depth + 1 >= maxDepth ) { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Thrower ) { - that = undefined; - args = [ e ]; - } - - deferred.rejectWith( that, args ); - } - } - }; - - // Support: Promises/A+ section 2.3.3.3.1 - // https://promisesaplus.com/#point-57 - // Re-resolve promises immediately to dodge false rejection from - // subsequent errors - if ( depth ) { - process(); - } else { - - // Call an optional hook to record the stack, in case of exception - // since it's otherwise lost when execution goes async - if ( jQuery.Deferred.getStackHook ) { - process.stackTrace = jQuery.Deferred.getStackHook(); - } - window.setTimeout( process ); - } - }; - } - - return jQuery.Deferred( function( newDefer ) { - - // progress_handlers.add( ... ) - tuples[ 0 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onProgress ) ? - onProgress : - Identity, - newDefer.notifyWith - ) - ); - - // fulfilled_handlers.add( ... ) - tuples[ 1 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onFulfilled ) ? - onFulfilled : - Identity - ) - ); - - // rejected_handlers.add( ... ) - tuples[ 2 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onRejected ) ? - onRejected : - Thrower - ) - ); - } ).promise(); - }, - - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 5 ]; - - // promise.progress = list.add - // promise.done = list.add - // promise.fail = list.add - promise[ tuple[ 1 ] ] = list.add; - - // Handle state - if ( stateString ) { - list.add( - function() { - - // state = "resolved" (i.e., fulfilled) - // state = "rejected" - state = stateString; - }, - - // rejected_callbacks.disable - // fulfilled_callbacks.disable - tuples[ 3 - i ][ 2 ].disable, - - // rejected_handlers.disable - // fulfilled_handlers.disable - tuples[ 3 - i ][ 3 ].disable, - - // progress_callbacks.lock - tuples[ 0 ][ 2 ].lock, - - // progress_handlers.lock - tuples[ 0 ][ 3 ].lock - ); - } - - // progress_handlers.fire - // fulfilled_handlers.fire - // rejected_handlers.fire - list.add( tuple[ 3 ].fire ); - - // deferred.notify = function() { deferred.notifyWith(...) } - // deferred.resolve = function() { deferred.resolveWith(...) } - // deferred.reject = function() { deferred.rejectWith(...) } - deferred[ tuple[ 0 ] ] = function() { - deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); - return this; - }; - - // deferred.notifyWith = list.fireWith - // deferred.resolveWith = list.fireWith - // deferred.rejectWith = list.fireWith - deferred[ tuple[ 0 ] + "With" ] = list.fireWith; - } ); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( singleValue ) { - var - - // count of uncompleted subordinates - remaining = arguments.length, - - // count of unprocessed arguments - i = remaining, - - // subordinate fulfillment data - resolveContexts = Array( i ), - resolveValues = slice.call( arguments ), - - // the primary Deferred - primary = jQuery.Deferred(), - - // subordinate callback factory - updateFunc = function( i ) { - return function( value ) { - resolveContexts[ i ] = this; - resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( !( --remaining ) ) { - primary.resolveWith( resolveContexts, resolveValues ); - } - }; - }; - - // Single- and empty arguments are adopted like Promise.resolve - if ( remaining <= 1 ) { - adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject, - !remaining ); - - // Use .then() to unwrap secondary thenables (cf. gh-3000) - if ( primary.state() === "pending" || - isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { - - return primary.then(); - } - } - - // Multiple arguments are aggregated like Promise.all array elements - while ( i-- ) { - adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject ); - } - - return primary.promise(); - } -} ); - - -// These usually indicate a programmer mistake during development, -// warn about them ASAP rather than swallowing them by default. -var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; - -jQuery.Deferred.exceptionHook = function( error, stack ) { - - // Support: IE 8 - 9 only - // Console exists when dev tools are open, which can happen at any time - if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { - window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); - } -}; - - - - -jQuery.readyException = function( error ) { - window.setTimeout( function() { - throw error; - } ); -}; - - - - -// The deferred used on DOM ready -var readyList = jQuery.Deferred(); - -jQuery.fn.ready = function( fn ) { - - readyList - .then( fn ) - - // Wrap jQuery.readyException in a function so that the lookup - // happens at the time of error handling instead of callback - // registration. - .catch( function( error ) { - jQuery.readyException( error ); - } ); - - return this; -}; - -jQuery.extend( { - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - } -} ); - -jQuery.ready.then = readyList.then; - -// The ready event handler and self cleanup method -function completed() { - document.removeEventListener( "DOMContentLoaded", completed ); - window.removeEventListener( "load", completed ); - jQuery.ready(); -} - -// Catch cases where $(document).ready() is called -// after the browser event has already occurred. -// Support: IE <=9 - 10 only -// Older IE sometimes signals "interactive" too soon -if ( document.readyState === "complete" || - ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - - // Handle it asynchronously to allow scripts the opportunity to delay ready - window.setTimeout( jQuery.ready ); - -} else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed ); -} - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( toType( key ) === "object" ) { - chainable = true; - for ( i in key ) { - access( elems, fn, i, key[ i ], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, _key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( - elems[ i ], key, raw ? - value : - value.call( elems[ i ], i, fn( elems[ i ], key ) ) - ); - } - } - } - - if ( chainable ) { - return elems; - } - - // Gets - if ( bulk ) { - return fn.call( elems ); - } - - return len ? fn( elems[ 0 ], key ) : emptyGet; -}; - - -// Matches dashed string for camelizing -var rmsPrefix = /^-ms-/, - rdashAlpha = /-([a-z])/g; - -// Used by camelCase as callback to replace() -function fcamelCase( _all, letter ) { - return letter.toUpperCase(); -} - -// Convert dashed to camelCase; used by the css and data modules -// Support: IE <=9 - 11, Edge 12 - 15 -// Microsoft forgot to hump their vendor prefix (#9572) -function camelCase( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); -} -var acceptData = function( owner ) { - - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); -}; - - - - -function Data() { - this.expando = jQuery.expando + Data.uid++; -} - -Data.uid = 1; - -Data.prototype = { - - cache: function( owner ) { - - // Check if the owner object already has a cache - var value = owner[ this.expando ]; - - // If not, create one - if ( !value ) { - value = {}; - - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( acceptData( owner ) ) { - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable property - // configurable must be true to allow the property to be - // deleted when data is removed - } else { - Object.defineProperty( owner, this.expando, { - value: value, - configurable: true - } ); - } - } - } - - return value; - }, - set: function( owner, data, value ) { - var prop, - cache = this.cache( owner ); - - // Handle: [ owner, key, value ] args - // Always use camelCase key (gh-2257) - if ( typeof data === "string" ) { - cache[ camelCase( data ) ] = value; - - // Handle: [ owner, { properties } ] args - } else { - - // Copy the properties one-by-one to the cache object - for ( prop in data ) { - cache[ camelCase( prop ) ] = data[ prop ]; - } - } - return cache; - }, - get: function( owner, key ) { - return key === undefined ? - this.cache( owner ) : - - // Always use camelCase key (gh-2257) - owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; - }, - access: function( owner, key, value ) { - - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ( ( key && typeof key === "string" ) && value === undefined ) ) { - - return this.get( owner, key ); - } - - // When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, - cache = owner[ this.expando ]; - - if ( cache === undefined ) { - return; - } - - if ( key !== undefined ) { - - // Support array or space separated string of keys - if ( Array.isArray( key ) ) { - - // If key is an array of keys... - // We always set camelCase keys, so remove that. - key = key.map( camelCase ); - } else { - key = camelCase( key ); - - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - key = key in cache ? - [ key ] : - ( key.match( rnothtmlwhite ) || [] ); - } - - i = key.length; - - while ( i-- ) { - delete cache[ key[ i ] ]; - } - } - - // Remove the expando if there's no more data - if ( key === undefined || jQuery.isEmptyObject( cache ) ) { - - // Support: Chrome <=35 - 45 - // Webkit & Blink performance suffers when deleting properties - // from DOM nodes, so set to undefined instead - // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) - if ( owner.nodeType ) { - owner[ this.expando ] = undefined; - } else { - delete owner[ this.expando ]; - } - } - }, - hasData: function( owner ) { - var cache = owner[ this.expando ]; - return cache !== undefined && !jQuery.isEmptyObject( cache ); - } -}; -var dataPriv = new Data(); - -var dataUser = new Data(); - - - -// Implementation Summary -// -// 1. Enforce API surface and semantic compatibility with 1.9.x branch -// 2. Improve the module's maintainability by reducing the storage -// paths to a single mechanism. -// 3. Use the same single mechanism to support "private" and "user" data. -// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) -// 5. Avoid exposing implementation details on user objects (eg. expando properties) -// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /[A-Z]/g; - -function getData( data ) { - if ( data === "true" ) { - return true; - } - - if ( data === "false" ) { - return false; - } - - if ( data === "null" ) { - return null; - } - - // Only convert to a number if it doesn't change the string - if ( data === +data + "" ) { - return +data; - } - - if ( rbrace.test( data ) ) { - return JSON.parse( data ); - } - - return data; -} - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = getData( data ); - } catch ( e ) {} - - // Make sure we set the data so it isn't changed later - dataUser.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} - -jQuery.extend( { - hasData: function( elem ) { - return dataUser.hasData( elem ) || dataPriv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return dataUser.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - dataUser.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to dataPriv methods, these can be deprecated. - _data: function( elem, name, data ) { - return dataPriv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - dataPriv.remove( elem, name ); - } -} ); - -jQuery.fn.extend( { - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = dataUser.get( elem ); - - if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE 11 only - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = camelCase( name.slice( 5 ) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - dataPriv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each( function() { - dataUser.set( this, key ); - } ); - } - - return access( this, function( value ) { - var data; - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - - // Attempt to get data from the cache - // The key will always be camelCased in Data - data = dataUser.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, key ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each( function() { - - // We always store the camelCased key - dataUser.set( this, key, value ); - } ); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each( function() { - dataUser.remove( this, key ); - } ); - } -} ); - - -jQuery.extend( { - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = dataPriv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || Array.isArray( data ) ) { - queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // Clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // Not public - generate a queueHooks object, or return the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { - empty: jQuery.Callbacks( "once memory" ).add( function() { - dataPriv.remove( elem, [ type + "queue", key ] ); - } ) - } ); - } -} ); - -jQuery.fn.extend( { - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[ 0 ], type ); - } - - return data === undefined ? - this : - this.each( function() { - var queue = jQuery.queue( this, type, data ); - - // Ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - } ); - }, - dequeue: function( type ) { - return this.each( function() { - jQuery.dequeue( this, type ); - } ); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -} ); -var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; - -var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); - - -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - -var documentElement = document.documentElement; - - - - var isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ); - }, - composed = { composed: true }; - - // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only - // Check attachment across shadow DOM boundaries when possible (gh-3504) - // Support: iOS 10.0-10.2 only - // Early iOS 10 versions support `attachShadow` but not `getRootNode`, - // leading to errors. We need to check for `getRootNode`. - if ( documentElement.getRootNode ) { - isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ) || - elem.getRootNode( composed ) === elem.ownerDocument; - }; - } -var isHiddenWithinTree = function( elem, el ) { - - // isHiddenWithinTree might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - - // Inline style trumps all - return elem.style.display === "none" || - elem.style.display === "" && - - // Otherwise, check computed style - // Support: Firefox <=43 - 45 - // Disconnected elements can have computed display: none, so first confirm that elem is - // in the document. - isAttached( elem ) && - - jQuery.css( elem, "display" ) === "none"; - }; - - - -function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, scale, - maxIterations = 20, - currentValue = tween ? - function() { - return tween.cur(); - } : - function() { - return jQuery.css( elem, prop, "" ); - }, - initial = currentValue(), - unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), - - // Starting value computation is required for potential unit mismatches - initialInUnit = elem.nodeType && - ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && - rcssNum.exec( jQuery.css( elem, prop ) ); - - if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { - - // Support: Firefox <=54 - // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) - initial = initial / 2; - - // Trust units reported by jQuery.css - unit = unit || initialInUnit[ 3 ]; - - // Iteratively approximate from a nonzero starting point - initialInUnit = +initial || 1; - - while ( maxIterations-- ) { - - // Evaluate and update our best guess (doubling guesses that zero out). - // Finish if the scale equals or crosses 1 (making the old*new product non-positive). - jQuery.style( elem, prop, initialInUnit + unit ); - if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { - maxIterations = 0; - } - initialInUnit = initialInUnit / scale; - - } - - initialInUnit = initialInUnit * 2; - jQuery.style( elem, prop, initialInUnit + unit ); - - // Make sure we update the tween properties later on - valueParts = valueParts || []; - } - - if ( valueParts ) { - initialInUnit = +initialInUnit || +initial || 0; - - // Apply relative offset (+=/-=) if specified - adjusted = valueParts[ 1 ] ? - initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : - +valueParts[ 2 ]; - if ( tween ) { - tween.unit = unit; - tween.start = initialInUnit; - tween.end = adjusted; - } - } - return adjusted; -} - - -var defaultDisplayMap = {}; - -function getDefaultDisplay( elem ) { - var temp, - doc = elem.ownerDocument, - nodeName = elem.nodeName, - display = defaultDisplayMap[ nodeName ]; - - if ( display ) { - return display; - } - - temp = doc.body.appendChild( doc.createElement( nodeName ) ); - display = jQuery.css( temp, "display" ); - - temp.parentNode.removeChild( temp ); - - if ( display === "none" ) { - display = "block"; - } - defaultDisplayMap[ nodeName ] = display; - - return display; -} - -function showHide( elements, show ) { - var display, elem, - values = [], - index = 0, - length = elements.length; - - // Determine new display value for elements that need to change - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - display = elem.style.display; - if ( show ) { - - // Since we force visibility upon cascade-hidden elements, an immediate (and slow) - // check is required in this first loop unless we have a nonempty display value (either - // inline or about-to-be-restored) - if ( display === "none" ) { - values[ index ] = dataPriv.get( elem, "display" ) || null; - if ( !values[ index ] ) { - elem.style.display = ""; - } - } - if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { - values[ index ] = getDefaultDisplay( elem ); - } - } else { - if ( display !== "none" ) { - values[ index ] = "none"; - - // Remember what we're overwriting - dataPriv.set( elem, "display", display ); - } - } - } - - // Set the display of the elements in a second loop to avoid constant reflow - for ( index = 0; index < length; index++ ) { - if ( values[ index ] != null ) { - elements[ index ].style.display = values[ index ]; - } - } - - return elements; -} - -jQuery.fn.extend( { - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - if ( typeof state === "boolean" ) { - return state ? this.show() : this.hide(); - } - - return this.each( function() { - if ( isHiddenWithinTree( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - } ); - } -} ); -var rcheckableType = ( /^(?:checkbox|radio)$/i ); - -var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); - -var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); - - - -( function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // Support: Android 4.0 - 4.3 only - // Check state lost if the name is set (#11217) - // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Android <=4.1 only - // Older WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE <=11 only - // Make sure textarea (and checkbox) defaultValue is properly cloned - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; - - // Support: IE <=9 only - // IE <=9 replaces "; - support.option = !!div.lastChild; -} )(); - - -// We have to close these tags to support XHTML (#13200) -var wrapMap = { - - // XHTML parsers do not magically insert elements in the - // same way that tag soup parsers do. So we cannot shorten - // this by omitting or other required elements. - thead: [ 1, "", "
      " ], - col: [ 2, "", "
      " ], - tr: [ 2, "", "
      " ], - td: [ 3, "", "
      " ], - - _default: [ 0, "", "" ] -}; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// Support: IE <=9 only -if ( !support.option ) { - wrapMap.optgroup = wrapMap.option = [ 1, "" ]; -} - - -function getAll( context, tag ) { - - // Support: IE <=9 - 11 only - // Use typeof to avoid zero-argument method invocation on host objects (#15151) - var ret; - - if ( typeof context.getElementsByTagName !== "undefined" ) { - ret = context.getElementsByTagName( tag || "*" ); - - } else if ( typeof context.querySelectorAll !== "undefined" ) { - ret = context.querySelectorAll( tag || "*" ); - - } else { - ret = []; - } - - if ( tag === undefined || tag && nodeName( context, tag ) ) { - return jQuery.merge( [ context ], ret ); - } - - return ret; -} - - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - dataPriv.set( - elems[ i ], - "globalEval", - !refElements || dataPriv.get( refElements[ i ], "globalEval" ) - ); - } -} - - -var rhtml = /<|&#?\w+;/; - -function buildFragment( elems, context, scripts, selection, ignored ) { - var elem, tmp, tag, wrap, attached, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( toType( elem ) === "object" ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Ensure the created nodes are orphaned (#12392) - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( ( elem = nodes[ i++ ] ) ) { - - // Skip elements already in the context collection (trac-4087) - if ( selection && jQuery.inArray( elem, selection ) > -1 ) { - if ( ignored ) { - ignored.push( elem ); - } - continue; - } - - attached = isAttached( elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( attached ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( ( elem = tmp[ j++ ] ) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; -} - - -var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -// Support: IE <=9 - 11+ -// focus() and blur() are asynchronous, except when they are no-op. -// So expect focus to be synchronous when the element is already active, -// and blur to be synchronous when the element is not already active. -// (focus and blur are always synchronous in other supported browsers, -// this just defines when we can count on it). -function expectSync( elem, type ) { - return ( elem === safeActiveElement() ) === ( type === "focus" ); -} - -// Support: IE <=9 only -// Accessing document.activeElement can throw unexpectedly -// https://bugs.jquery.com/ticket/13393 -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -function on( elem, types, selector, data, fn, one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - on( elem, type, selector, data, types[ type ], one ); - } - return elem; - } - - if ( data == null && fn == null ) { - - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return elem; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return elem.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - } ); -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.get( elem ); - - // Only attach events to objects that accept data - if ( !acceptData( elem ) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Ensure that invalid selectors throw exceptions at attach time - // Evaluate against documentElement in case elem is a non-element node (e.g., document) - if ( selector ) { - jQuery.find.matchesSelector( documentElement, selector ); - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !( events = elemData.events ) ) { - events = elemData.events = Object.create( null ); - } - if ( !( eventHandle = elemData.handle ) ) { - eventHandle = elemData.handle = function( e ) { - - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend( { - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join( "." ) - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !( handlers = events[ type ] ) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || - special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); - - if ( !elemData || !( events = elemData.events ) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[ 2 ] && - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || - selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || - special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove data and the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - dataPriv.remove( elem, "handle events" ); - } - }, - - dispatch: function( nativeEvent ) { - - var i, j, ret, matched, handleObj, handlerQueue, - args = new Array( arguments.length ), - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( nativeEvent ), - - handlers = ( - dataPriv.get( this, "events" ) || Object.create( null ) - )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[ 0 ] = event; - - for ( i = 1; i < arguments.length; i++ ) { - args[ i ] = arguments[ i ]; - } - - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( ( handleObj = matched.handlers[ j++ ] ) && - !event.isImmediatePropagationStopped() ) { - - // If the event is namespaced, then each handler is only invoked if it is - // specially universal or its namespaces are a superset of the event's. - if ( !event.rnamespace || handleObj.namespace === false || - event.rnamespace.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || - handleObj.handler ).apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( ( event.result = ret ) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, handleObj, sel, matchedHandlers, matchedSelectors, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - if ( delegateCount && - - // Support: IE <=9 - // Black-hole SVG instance trees (trac-13180) - cur.nodeType && - - // Support: Firefox <=42 - // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) - // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click - // Support: IE 11 only - // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) - !( event.type === "click" && event.button >= 1 ) ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { - matchedHandlers = []; - matchedSelectors = {}; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matchedSelectors[ sel ] === undefined ) { - matchedSelectors[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) > -1 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matchedSelectors[ sel ] ) { - matchedHandlers.push( handleObj ); - } - } - if ( matchedHandlers.length ) { - handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); - } - } - } - } - - // Add the remaining (directly-bound) handlers - cur = this; - if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); - } - - return handlerQueue; - }, - - addProp: function( name, hook ) { - Object.defineProperty( jQuery.Event.prototype, name, { - enumerable: true, - configurable: true, - - get: isFunction( hook ) ? - function() { - if ( this.originalEvent ) { - return hook( this.originalEvent ); - } - } : - function() { - if ( this.originalEvent ) { - return this.originalEvent[ name ]; - } - }, - - set: function( value ) { - Object.defineProperty( this, name, { - enumerable: true, - configurable: true, - writable: true, - value: value - } ); - } - } ); - }, - - fix: function( originalEvent ) { - return originalEvent[ jQuery.expando ] ? - originalEvent : - new jQuery.Event( originalEvent ); - }, - - special: { - load: { - - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - click: { - - // Utilize native event to ensure correct state for checkable inputs - setup: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Claim the first handler - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - // dataPriv.set( el, "click", ... ) - leverageNative( el, "click", returnTrue ); - } - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Force setup before triggering a click - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - leverageNative( el, "click" ); - } - - // Return non-false to allow normal event-path propagation - return true; - }, - - // For cross-browser consistency, suppress native .click() on links - // Also prevent it if we're currently inside a leveraged native-event stack - _default: function( event ) { - var target = event.target; - return rcheckableType.test( target.type ) && - target.click && nodeName( target, "input" ) && - dataPriv.get( target, "click" ) || - nodeName( target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - } -}; - -// Ensure the presence of an event listener that handles manually-triggered -// synthetic events by interrupting progress until reinvoked in response to -// *native* events that it fires directly, ensuring that state changes have -// already occurred before other listeners are invoked. -function leverageNative( el, type, expectSync ) { - - // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add - if ( !expectSync ) { - if ( dataPriv.get( el, type ) === undefined ) { - jQuery.event.add( el, type, returnTrue ); - } - return; - } - - // Register the controller as a special universal handler for all event namespaces - dataPriv.set( el, type, false ); - jQuery.event.add( el, type, { - namespace: false, - handler: function( event ) { - var notAsync, result, - saved = dataPriv.get( this, type ); - - if ( ( event.isTrigger & 1 ) && this[ type ] ) { - - // Interrupt processing of the outer synthetic .trigger()ed event - // Saved data should be false in such cases, but might be a leftover capture object - // from an async native handler (gh-4350) - if ( !saved.length ) { - - // Store arguments for use when handling the inner native event - // There will always be at least one argument (an event object), so this array - // will not be confused with a leftover capture object. - saved = slice.call( arguments ); - dataPriv.set( this, type, saved ); - - // Trigger the native event and capture its result - // Support: IE <=9 - 11+ - // focus() and blur() are asynchronous - notAsync = expectSync( this, type ); - this[ type ](); - result = dataPriv.get( this, type ); - if ( saved !== result || notAsync ) { - dataPriv.set( this, type, false ); - } else { - result = {}; - } - if ( saved !== result ) { - - // Cancel the outer synthetic event - event.stopImmediatePropagation(); - event.preventDefault(); - - // Support: Chrome 86+ - // In Chrome, if an element having a focusout handler is blurred by - // clicking outside of it, it invokes the handler synchronously. If - // that handler calls `.remove()` on the element, the data is cleared, - // leaving `result` undefined. We need to guard against this. - return result && result.value; - } - - // If this is an inner synthetic event for an event with a bubbling surrogate - // (focus or blur), assume that the surrogate already propagated from triggering the - // native event and prevent that from happening again here. - // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the - // bubbling surrogate propagates *after* the non-bubbling base), but that seems - // less bad than duplication. - } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { - event.stopPropagation(); - } - - // If this is a native event triggered above, everything is now in order - // Fire an inner synthetic event with the original arguments - } else if ( saved.length ) { - - // ...and capture the result - dataPriv.set( this, type, { - value: jQuery.event.trigger( - - // Support: IE <=9 - 11+ - // Extend with the prototype to reset the above stopImmediatePropagation() - jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), - saved.slice( 1 ), - this - ) - } ); - - // Abort handling of the native event - event.stopImmediatePropagation(); - } - } - } ); -} - -jQuery.removeEvent = function( elem, type, handle ) { - - // This "if" is needed for plain objects - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle ); - } -}; - -jQuery.Event = function( src, props ) { - - // Allow instantiation without the 'new' keyword - if ( !( this instanceof jQuery.Event ) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - - // Support: Android <=2.3 only - src.returnValue === false ? - returnTrue : - returnFalse; - - // Create target properties - // Support: Safari <=6 - 7 only - // Target should not be a text node (#504, #13143) - this.target = ( src.target && src.target.nodeType === 3 ) ? - src.target.parentNode : - src.target; - - this.currentTarget = src.currentTarget; - this.relatedTarget = src.relatedTarget; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || Date.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - constructor: jQuery.Event, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - isSimulated: false, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && !this.isSimulated ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Includes all common event props including KeyEvent and MouseEvent specific props -jQuery.each( { - altKey: true, - bubbles: true, - cancelable: true, - changedTouches: true, - ctrlKey: true, - detail: true, - eventPhase: true, - metaKey: true, - pageX: true, - pageY: true, - shiftKey: true, - view: true, - "char": true, - code: true, - charCode: true, - key: true, - keyCode: true, - button: true, - buttons: true, - clientX: true, - clientY: true, - offsetX: true, - offsetY: true, - pointerId: true, - pointerType: true, - screenX: true, - screenY: true, - targetTouches: true, - toElement: true, - touches: true, - which: true -}, jQuery.event.addProp ); - -jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { - jQuery.event.special[ type ] = { - - // Utilize native event if possible so blur/focus sequence is correct - setup: function() { - - // Claim the first handler - // dataPriv.set( this, "focus", ... ) - // dataPriv.set( this, "blur", ... ) - leverageNative( this, type, expectSync ); - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function() { - - // Force setup before trigger - leverageNative( this, type ); - - // Return non-false to allow normal event-path propagation - return true; - }, - - // Suppress native focus or blur as it's already being fired - // in leverageNative. - _default: function() { - return true; - }, - - delegateType: delegateType - }; -} ); - -// Create mouseenter/leave events using mouseover/out and event-time checks -// so that event delegation works in jQuery. -// Do the same for pointerenter/pointerleave and pointerover/pointerout -// -// Support: Safari 7 only -// Safari sends mouseenter too often; see: -// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 -// for the description of the bug (it existed in older Chrome versions as well). -jQuery.each( { - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mouseenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -} ); - -jQuery.fn.extend( { - - on: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn ); - }, - one: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? - handleObj.origType + "." + handleObj.namespace : - handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each( function() { - jQuery.event.remove( this, types, fn, selector ); - } ); - } -} ); - - -var - - // Support: IE <=10 - 11, Edge 12 - 13 only - // In IE/Edge using regex groups here causes severe slowdowns. - // See https://connect.microsoft.com/IE/feedback/details/1736512/ - rnoInnerhtml = /\s*$/g; - -// Prefer a tbody over its parent table for containing new rows -function manipulationTarget( elem, content ) { - if ( nodeName( elem, "table" ) && - nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - - return jQuery( elem ).children( "tbody" )[ 0 ] || elem; - } - - return elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { - elem.type = elem.type.slice( 5 ); - } else { - elem.removeAttribute( "type" ); - } - - return elem; -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( dataPriv.hasData( src ) ) { - pdataOld = dataPriv.get( src ); - events = pdataOld.events; - - if ( events ) { - dataPriv.remove( dest, "handle events" ); - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( dataUser.hasData( src ) ) { - udataOld = dataUser.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - dataUser.set( dest, udataCur ); - } -} - -// Fix IE bugs, see support tests -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -function domManip( collection, args, callback, ignored ) { - - // Flatten any nested arrays - args = flat( args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = collection.length, - iNoClone = l - 1, - value = args[ 0 ], - valueIsFunction = isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( valueIsFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return collection.each( function( index ) { - var self = collection.eq( index ); - if ( valueIsFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - domManip( self, args, callback, ignored ); - } ); - } - - if ( l ) { - fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - // Require either new content or an interest in ignored elements to invoke the callback - if ( first || ignored ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item - // instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( collection[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !dataPriv.access( node, "globalEval" ) && - jQuery.contains( doc, node ) ) { - - if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { - - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl && !node.noModule ) { - jQuery._evalUrl( node.src, { - nonce: node.nonce || node.getAttribute( "nonce" ) - }, doc ); - } - } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); - } - } - } - } - } - } - - return collection; -} - -function remove( elem, selector, keepData ) { - var node, - nodes = selector ? jQuery.filter( selector, elem ) : elem, - i = 0; - - for ( ; ( node = nodes[ i ] ) != null; i++ ) { - if ( !keepData && node.nodeType === 1 ) { - jQuery.cleanData( getAll( node ) ); - } - - if ( node.parentNode ) { - if ( keepData && isAttached( node ) ) { - setGlobalEval( getAll( node, "script" ) ); - } - node.parentNode.removeChild( node ); - } - } - - return elem; -} - -jQuery.extend( { - htmlPrefilter: function( html ) { - return html; - }, - - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = isAttached( elem ); - - // Fix IE cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - cleanData: function( elems ) { - var data, elem, type, - special = jQuery.event.special, - i = 0; - - for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { - if ( acceptData( elem ) ) { - if ( ( data = elem[ dataPriv.expando ] ) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataPriv.expando ] = undefined; - } - if ( elem[ dataUser.expando ] ) { - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataUser.expando ] = undefined; - } - } - } - } -} ); - -jQuery.fn.extend( { - detach: function( selector ) { - return remove( this, selector, true ); - }, - - remove: function( selector ) { - return remove( this, selector ); - }, - - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each( function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - } ); - }, null, value, arguments.length ); - }, - - append: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - } ); - }, - - prepend: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - } ); - }, - - before: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - } ); - }, - - after: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - } ); - }, - - empty: function() { - var elem, - i = 0; - - for ( ; ( elem = this[ i ] ) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - } ); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = jQuery.htmlPrefilter( value ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch ( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var ignored = []; - - // Make the changes, replacing each non-ignored context element with the new content - return domManip( this, arguments, function( elem ) { - var parent = this.parentNode; - - if ( jQuery.inArray( this, ignored ) < 0 ) { - jQuery.cleanData( getAll( this ) ); - if ( parent ) { - parent.replaceChild( elem, this ); - } - } - - // Force callback invocation - }, ignored ); - } -} ); - -jQuery.each( { - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: Android <=4.0 only, PhantomJS 1 only - // .get() because push.apply(_, arraylike) throws on ancient WebKit - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -} ); -var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); - -var getStyles = function( elem ) { - - // Support: IE <=11 only, Firefox <=30 (#15098, #14150) - // IE throws on elements created in popups - // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" - var view = elem.ownerDocument.defaultView; - - if ( !view || !view.opener ) { - view = window; - } - - return view.getComputedStyle( elem ); - }; - -var swap = function( elem, options, callback ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.call( elem ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; -}; - - -var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); - - - -( function() { - - // Executing both pixelPosition & boxSizingReliable tests require only one layout - // so they're executed at the same time to save the second computation. - function computeStyleTests() { - - // This is a singleton, we need to execute it only once - if ( !div ) { - return; - } - - container.style.cssText = "position:absolute;left:-11111px;width:60px;" + - "margin-top:1px;padding:0;border:0"; - div.style.cssText = - "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + - "margin:auto;border:1px;padding:1px;" + - "width:60%;top:1%"; - documentElement.appendChild( container ).appendChild( div ); - - var divStyle = window.getComputedStyle( div ); - pixelPositionVal = divStyle.top !== "1%"; - - // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 - reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; - - // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 - // Some styles come back with percentage values, even though they shouldn't - div.style.right = "60%"; - pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; - - // Support: IE 9 - 11 only - // Detect misreporting of content dimensions for box-sizing:border-box elements - boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; - - // Support: IE 9 only - // Detect overflow:scroll screwiness (gh-3699) - // Support: Chrome <=64 - // Don't get tricked when zoom affects offsetWidth (gh-4029) - div.style.position = "absolute"; - scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; - - documentElement.removeChild( container ); - - // Nullify the div so it wouldn't be stored in the memory and - // it will also be a sign that checks already performed - div = null; - } - - function roundPixelMeasures( measure ) { - return Math.round( parseFloat( measure ) ); - } - - var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, - reliableTrDimensionsVal, reliableMarginLeftVal, - container = document.createElement( "div" ), - div = document.createElement( "div" ); - - // Finish early in limited (non-browser) environments - if ( !div.style ) { - return; - } - - // Support: IE <=9 - 11 only - // Style of cloned element affects source element cloned (#8908) - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - jQuery.extend( support, { - boxSizingReliable: function() { - computeStyleTests(); - return boxSizingReliableVal; - }, - pixelBoxStyles: function() { - computeStyleTests(); - return pixelBoxStylesVal; - }, - pixelPosition: function() { - computeStyleTests(); - return pixelPositionVal; - }, - reliableMarginLeft: function() { - computeStyleTests(); - return reliableMarginLeftVal; - }, - scrollboxSize: function() { - computeStyleTests(); - return scrollboxSizeVal; - }, - - // Support: IE 9 - 11+, Edge 15 - 18+ - // IE/Edge misreport `getComputedStyle` of table rows with width/height - // set in CSS while `offset*` properties report correct values. - // Behavior in IE 9 is more subtle than in newer versions & it passes - // some versions of this test; make sure not to make it pass there! - // - // Support: Firefox 70+ - // Only Firefox includes border widths - // in computed dimensions. (gh-4529) - reliableTrDimensions: function() { - var table, tr, trChild, trStyle; - if ( reliableTrDimensionsVal == null ) { - table = document.createElement( "table" ); - tr = document.createElement( "tr" ); - trChild = document.createElement( "div" ); - - table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; - tr.style.cssText = "border:1px solid"; - - // Support: Chrome 86+ - // Height set through cssText does not get applied. - // Computed height then comes back as 0. - tr.style.height = "1px"; - trChild.style.height = "9px"; - - // Support: Android 8 Chrome 86+ - // In our bodyBackground.html iframe, - // display for all div elements is set to "inline", - // which causes a problem only in Android 8 Chrome 86. - // Ensuring the div is display: block - // gets around this issue. - trChild.style.display = "block"; - - documentElement - .appendChild( table ) - .appendChild( tr ) - .appendChild( trChild ); - - trStyle = window.getComputedStyle( tr ); - reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) + - parseInt( trStyle.borderTopWidth, 10 ) + - parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight; - - documentElement.removeChild( table ); - } - return reliableTrDimensionsVal; - } - } ); -} )(); - - -function curCSS( elem, name, computed ) { - var width, minWidth, maxWidth, ret, - - // Support: Firefox 51+ - // Retrieving style before computed somehow - // fixes an issue with getting wrong values - // on detached elements - style = elem.style; - - computed = computed || getStyles( elem ); - - // getPropertyValue is needed for: - // .css('filter') (IE 9 only, #12537) - // .css('--customProperty) (#3144) - if ( computed ) { - ret = computed.getPropertyValue( name ) || computed[ name ]; - - if ( ret === "" && !isAttached( elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Android Browser returns percentage for some values, - // but width seems to be reliably pixels. - // This is against the CSSOM draft spec: - // https://drafts.csswg.org/cssom/#resolved-values - if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret !== undefined ? - - // Support: IE <=9 - 11 only - // IE returns zIndex value as an integer. - ret + "" : - ret; -} - - -function addGetHookIf( conditionFn, hookFn ) { - - // Define the hook, we'll check on the first run if it's really needed. - return { - get: function() { - if ( conditionFn() ) { - - // Hook not needed (or it's not possible to use it due - // to missing dependency), remove it. - delete this.get; - return; - } - - // Hook needed; redefine it so that the support test is not executed again. - return ( this.get = hookFn ).apply( this, arguments ); - } - }; -} - - -var cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style, - vendorProps = {}; - -// Return a vendor-prefixed property or undefined -function vendorPropName( name ) { - - // Check for vendor prefixed names - var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in emptyStyle ) { - return name; - } - } -} - -// Return a potentially-mapped jQuery.cssProps or vendor prefixed property -function finalPropName( name ) { - var final = jQuery.cssProps[ name ] || vendorProps[ name ]; - - if ( final ) { - return final; - } - if ( name in emptyStyle ) { - return name; - } - return vendorProps[ name ] = vendorPropName( name ) || name; -} - - -var - - // Swappable if display is none or starts with table - // except "table", "table-cell", or "table-caption" - // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rcustomProp = /^--/, - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: "0", - fontWeight: "400" - }; - -function setPositiveNumber( _elem, value, subtract ) { - - // Any relative (+/-) values have already been - // normalized at this point - var matches = rcssNum.exec( value ); - return matches ? - - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : - value; -} - -function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { - var i = dimension === "width" ? 1 : 0, - extra = 0, - delta = 0; - - // Adjustment may not be necessary - if ( box === ( isBorderBox ? "border" : "content" ) ) { - return 0; - } - - for ( ; i < 4; i += 2 ) { - - // Both box models exclude margin - if ( box === "margin" ) { - delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); - } - - // If we get here with a content-box, we're seeking "padding" or "border" or "margin" - if ( !isBorderBox ) { - - // Add padding - delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // For "border" or "margin", add border - if ( box !== "padding" ) { - delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - - // But still keep track of it otherwise - } else { - extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - - // If we get here with a border-box (content + padding + border), we're seeking "content" or - // "padding" or "margin" - } else { - - // For "content", subtract padding - if ( box === "content" ) { - delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // For "content" or "padding", subtract border - if ( box !== "margin" ) { - delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - // Account for positive content-box scroll gutter when requested by providing computedVal - if ( !isBorderBox && computedVal >= 0 ) { - - // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border - // Assuming integer scroll gutter, subtract the rest and round down - delta += Math.max( 0, Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - computedVal - - delta - - extra - - 0.5 - - // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter - // Use an explicit zero to avoid NaN (gh-3964) - ) ) || 0; - } - - return delta; -} - -function getWidthOrHeight( elem, dimension, extra ) { - - // Start with computed style - var styles = getStyles( elem ), - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). - // Fake content-box until we know it's needed to know the true value. - boxSizingNeeded = !support.boxSizingReliable() || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - valueIsBorderBox = isBorderBox, - - val = curCSS( elem, dimension, styles ), - offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); - - // Support: Firefox <=54 - // Return a confounding non-pixel value or feign ignorance, as appropriate. - if ( rnumnonpx.test( val ) ) { - if ( !extra ) { - return val; - } - val = "auto"; - } - - - // Support: IE 9 - 11 only - // Use offsetWidth/offsetHeight for when box sizing is unreliable. - // In those cases, the computed value can be trusted to be border-box. - if ( ( !support.boxSizingReliable() && isBorderBox || - - // Support: IE 10 - 11+, Edge 15 - 18+ - // IE/Edge misreport `getComputedStyle` of table rows with width/height - // set in CSS while `offset*` properties report correct values. - // Interestingly, in some cases IE 9 doesn't suffer from this issue. - !support.reliableTrDimensions() && nodeName( elem, "tr" ) || - - // Fall back to offsetWidth/offsetHeight when value is "auto" - // This happens for inline elements with no explicit setting (gh-3571) - val === "auto" || - - // Support: Android <=4.1 - 4.3 only - // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) - !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && - - // Make sure the element is visible & connected - elem.getClientRects().length ) { - - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // Where available, offsetWidth/offsetHeight approximate border box dimensions. - // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the - // retrieved value as a content box dimension. - valueIsBorderBox = offsetProp in elem; - if ( valueIsBorderBox ) { - val = elem[ offsetProp ]; - } - } - - // Normalize "" and auto - val = parseFloat( val ) || 0; - - // Adjust for the element's box model - return ( val + - boxModelAdjustment( - elem, - dimension, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles, - - // Provide the current computed size to request scroll gutter calculation (gh-3589) - val - ) - ) + "px"; -} - -jQuery.extend( { - - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Don't automatically add "px" to these possibly-unitless properties - cssNumber: { - "animationIterationCount": true, - "columnCount": true, - "fillOpacity": true, - "flexGrow": true, - "flexShrink": true, - "fontWeight": true, - "gridArea": true, - "gridColumn": true, - "gridColumnEnd": true, - "gridColumnStart": true, - "gridRow": true, - "gridRowEnd": true, - "gridRowStart": true, - "lineHeight": true, - "opacity": true, - "order": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: {}, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ), - style = elem.style; - - // Make sure that we're working with the right name. We don't - // want to query the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Gets hook for the prefixed version, then unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // Convert "+=" or "-=" to relative numbers (#7345) - if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { - value = adjustCSS( elem, name, ret ); - - // Fixes bug #9237 - type = "number"; - } - - // Make sure that null and NaN values aren't set (#7116) - if ( value == null || value !== value ) { - return; - } - - // If a number was passed in, add the unit (except for certain CSS properties) - // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append - // "px" to a few hardcoded values. - if ( type === "number" && !isCustomProp ) { - value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); - } - - // background-* props affect original clone's values - if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !( "set" in hooks ) || - ( value = hooks.set( elem, value, extra ) ) !== undefined ) { - - if ( isCustomProp ) { - style.setProperty( name, value ); - } else { - style[ name ] = value; - } - } - - } else { - - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && - ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { - - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var val, num, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ); - - // Make sure that we're working with the right name. We don't - // want to modify the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Try prefixed name followed by the unprefixed name - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - // Convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Make numeric if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || isFinite( num ) ? num || 0 : val; - } - - return val; - } -} ); - -jQuery.each( [ "height", "width" ], function( _i, dimension ) { - jQuery.cssHooks[ dimension ] = { - get: function( elem, computed, extra ) { - if ( computed ) { - - // Certain elements can have dimension info if we invisibly show them - // but it must have a current display style that would benefit - return rdisplayswap.test( jQuery.css( elem, "display" ) ) && - - // Support: Safari 8+ - // Table columns in Safari have non-zero offsetWidth & zero - // getBoundingClientRect().width unless display is changed. - // Support: IE <=11 only - // Running getBoundingClientRect on a disconnected node - // in IE throws an error. - ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? - swap( elem, cssShow, function() { - return getWidthOrHeight( elem, dimension, extra ); - } ) : - getWidthOrHeight( elem, dimension, extra ); - } - }, - - set: function( elem, value, extra ) { - var matches, - styles = getStyles( elem ), - - // Only read styles.position if the test has a chance to fail - // to avoid forcing a reflow. - scrollboxSizeBuggy = !support.scrollboxSize() && - styles.position === "absolute", - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) - boxSizingNeeded = scrollboxSizeBuggy || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - subtract = extra ? - boxModelAdjustment( - elem, - dimension, - extra, - isBorderBox, - styles - ) : - 0; - - // Account for unreliable border-box dimensions by comparing offset* to computed and - // faking a content-box to get border and padding (gh-3699) - if ( isBorderBox && scrollboxSizeBuggy ) { - subtract -= Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - parseFloat( styles[ dimension ] ) - - boxModelAdjustment( elem, dimension, "border", false, styles ) - - 0.5 - ); - } - - // Convert to pixels if value adjustment is needed - if ( subtract && ( matches = rcssNum.exec( value ) ) && - ( matches[ 3 ] || "px" ) !== "px" ) { - - elem.style[ dimension ] = value; - value = jQuery.css( elem, dimension ); - } - - return setPositiveNumber( elem, value, subtract ); - } - }; -} ); - -jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, - function( elem, computed ) { - if ( computed ) { - return ( parseFloat( curCSS( elem, "marginLeft" ) ) || - elem.getBoundingClientRect().left - - swap( elem, { marginLeft: 0 }, function() { - return elem.getBoundingClientRect().left; - } ) - ) + "px"; - } - } -); - -// These hooks are used by animate to expand properties -jQuery.each( { - margin: "", - padding: "", - border: "Width" -}, function( prefix, suffix ) { - jQuery.cssHooks[ prefix + suffix ] = { - expand: function( value ) { - var i = 0, - expanded = {}, - - // Assumes a single number if not a string - parts = typeof value === "string" ? value.split( " " ) : [ value ]; - - for ( ; i < 4; i++ ) { - expanded[ prefix + cssExpand[ i ] + suffix ] = - parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; - } - - return expanded; - } - }; - - if ( prefix !== "margin" ) { - jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; - } -} ); - -jQuery.fn.extend( { - css: function( name, value ) { - return access( this, function( elem, name, value ) { - var styles, len, - map = {}, - i = 0; - - if ( Array.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - } -} ); - - -function Tween( elem, options, prop, end, easing ) { - return new Tween.prototype.init( elem, options, prop, end, easing ); -} -jQuery.Tween = Tween; - -Tween.prototype = { - constructor: Tween, - init: function( elem, options, prop, end, easing, unit ) { - this.elem = elem; - this.prop = prop; - this.easing = easing || jQuery.easing._default; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - }, - cur: function() { - var hooks = Tween.propHooks[ this.prop ]; - - return hooks && hooks.get ? - hooks.get( this ) : - Tween.propHooks._default.get( this ); - }, - run: function( percent ) { - var eased, - hooks = Tween.propHooks[ this.prop ]; - - if ( this.options.duration ) { - this.pos = eased = jQuery.easing[ this.easing ]( - percent, this.options.duration * percent, 0, 1, this.options.duration - ); - } else { - this.pos = eased = percent; - } - this.now = ( this.end - this.start ) * eased + this.start; - - if ( this.options.step ) { - this.options.step.call( this.elem, this.now, this ); - } - - if ( hooks && hooks.set ) { - hooks.set( this ); - } else { - Tween.propHooks._default.set( this ); - } - return this; - } -}; - -Tween.prototype.init.prototype = Tween.prototype; - -Tween.propHooks = { - _default: { - get: function( tween ) { - var result; - - // Use a property on the element directly when it is not a DOM element, - // or when there is no matching style property that exists. - if ( tween.elem.nodeType !== 1 || - tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { - return tween.elem[ tween.prop ]; - } - - // Passing an empty string as a 3rd parameter to .css will automatically - // attempt a parseFloat and fallback to a string if the parse fails. - // Simple values such as "10px" are parsed to Float; - // complex values such as "rotate(1rad)" are returned as-is. - result = jQuery.css( tween.elem, tween.prop, "" ); - - // Empty strings, null, undefined and "auto" are converted to 0. - return !result || result === "auto" ? 0 : result; - }, - set: function( tween ) { - - // Use step hook for back compat. - // Use cssHook if its there. - // Use .style if available and use plain properties where available. - if ( jQuery.fx.step[ tween.prop ] ) { - jQuery.fx.step[ tween.prop ]( tween ); - } else if ( tween.elem.nodeType === 1 && ( - jQuery.cssHooks[ tween.prop ] || - tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { - jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); - } else { - tween.elem[ tween.prop ] = tween.now; - } - } - } -}; - -// Support: IE <=9 only -// Panic based approach to setting things on disconnected nodes -Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { - set: function( tween ) { - if ( tween.elem.nodeType && tween.elem.parentNode ) { - tween.elem[ tween.prop ] = tween.now; - } - } -}; - -jQuery.easing = { - linear: function( p ) { - return p; - }, - swing: function( p ) { - return 0.5 - Math.cos( p * Math.PI ) / 2; - }, - _default: "swing" -}; - -jQuery.fx = Tween.prototype.init; - -// Back compat <1.8 extension point -jQuery.fx.step = {}; - - - - -var - fxNow, inProgress, - rfxtypes = /^(?:toggle|show|hide)$/, - rrun = /queueHooks$/; - -function schedule() { - if ( inProgress ) { - if ( document.hidden === false && window.requestAnimationFrame ) { - window.requestAnimationFrame( schedule ); - } else { - window.setTimeout( schedule, jQuery.fx.interval ); - } - - jQuery.fx.tick(); - } -} - -// Animations created synchronously will run synchronously -function createFxNow() { - window.setTimeout( function() { - fxNow = undefined; - } ); - return ( fxNow = Date.now() ); -} - -// Generate parameters to create a standard animation -function genFx( type, includeWidth ) { - var which, - i = 0, - attrs = { height: type }; - - // If we include width, step value is 1 to do all cssExpand values, - // otherwise step value is 2 to skip over Left and Right - includeWidth = includeWidth ? 1 : 0; - for ( ; i < 4; i += 2 - includeWidth ) { - which = cssExpand[ i ]; - attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; - } - - if ( includeWidth ) { - attrs.opacity = attrs.width = type; - } - - return attrs; -} - -function createTween( value, prop, animation ) { - var tween, - collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), - index = 0, - length = collection.length; - for ( ; index < length; index++ ) { - if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { - - // We're done with this property - return tween; - } - } -} - -function defaultPrefilter( elem, props, opts ) { - var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, - isBox = "width" in props || "height" in props, - anim = this, - orig = {}, - style = elem.style, - hidden = elem.nodeType && isHiddenWithinTree( elem ), - dataShow = dataPriv.get( elem, "fxshow" ); - - // Queue-skipping animations hijack the fx hooks - if ( !opts.queue ) { - hooks = jQuery._queueHooks( elem, "fx" ); - if ( hooks.unqueued == null ) { - hooks.unqueued = 0; - oldfire = hooks.empty.fire; - hooks.empty.fire = function() { - if ( !hooks.unqueued ) { - oldfire(); - } - }; - } - hooks.unqueued++; - - anim.always( function() { - - // Ensure the complete handler is called before this completes - anim.always( function() { - hooks.unqueued--; - if ( !jQuery.queue( elem, "fx" ).length ) { - hooks.empty.fire(); - } - } ); - } ); - } - - // Detect show/hide animations - for ( prop in props ) { - value = props[ prop ]; - if ( rfxtypes.test( value ) ) { - delete props[ prop ]; - toggle = toggle || value === "toggle"; - if ( value === ( hidden ? "hide" : "show" ) ) { - - // Pretend to be hidden if this is a "show" and - // there is still data from a stopped show/hide - if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { - hidden = true; - - // Ignore all other no-op show/hide data - } else { - continue; - } - } - orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); - } - } - - // Bail out if this is a no-op like .hide().hide() - propTween = !jQuery.isEmptyObject( props ); - if ( !propTween && jQuery.isEmptyObject( orig ) ) { - return; - } - - // Restrict "overflow" and "display" styles during box animations - if ( isBox && elem.nodeType === 1 ) { - - // Support: IE <=9 - 11, Edge 12 - 15 - // Record all 3 overflow attributes because IE does not infer the shorthand - // from identically-valued overflowX and overflowY and Edge just mirrors - // the overflowX value there. - opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; - - // Identify a display type, preferring old show/hide data over the CSS cascade - restoreDisplay = dataShow && dataShow.display; - if ( restoreDisplay == null ) { - restoreDisplay = dataPriv.get( elem, "display" ); - } - display = jQuery.css( elem, "display" ); - if ( display === "none" ) { - if ( restoreDisplay ) { - display = restoreDisplay; - } else { - - // Get nonempty value(s) by temporarily forcing visibility - showHide( [ elem ], true ); - restoreDisplay = elem.style.display || restoreDisplay; - display = jQuery.css( elem, "display" ); - showHide( [ elem ] ); - } - } - - // Animate inline elements as inline-block - if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { - if ( jQuery.css( elem, "float" ) === "none" ) { - - // Restore the original display value at the end of pure show/hide animations - if ( !propTween ) { - anim.done( function() { - style.display = restoreDisplay; - } ); - if ( restoreDisplay == null ) { - display = style.display; - restoreDisplay = display === "none" ? "" : display; - } - } - style.display = "inline-block"; - } - } - } - - if ( opts.overflow ) { - style.overflow = "hidden"; - anim.always( function() { - style.overflow = opts.overflow[ 0 ]; - style.overflowX = opts.overflow[ 1 ]; - style.overflowY = opts.overflow[ 2 ]; - } ); - } - - // Implement show/hide animations - propTween = false; - for ( prop in orig ) { - - // General show/hide setup for this element animation - if ( !propTween ) { - if ( dataShow ) { - if ( "hidden" in dataShow ) { - hidden = dataShow.hidden; - } - } else { - dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); - } - - // Store hidden/visible for toggle so `.stop().toggle()` "reverses" - if ( toggle ) { - dataShow.hidden = !hidden; - } - - // Show elements before animating them - if ( hidden ) { - showHide( [ elem ], true ); - } - - /* eslint-disable no-loop-func */ - - anim.done( function() { - - /* eslint-enable no-loop-func */ - - // The final step of a "hide" animation is actually hiding the element - if ( !hidden ) { - showHide( [ elem ] ); - } - dataPriv.remove( elem, "fxshow" ); - for ( prop in orig ) { - jQuery.style( elem, prop, orig[ prop ] ); - } - } ); - } - - // Per-property setup - propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); - if ( !( prop in dataShow ) ) { - dataShow[ prop ] = propTween.start; - if ( hidden ) { - propTween.end = propTween.start; - propTween.start = 0; - } - } - } -} - -function propFilter( props, specialEasing ) { - var index, name, easing, value, hooks; - - // camelCase, specialEasing and expand cssHook pass - for ( index in props ) { - name = camelCase( index ); - easing = specialEasing[ name ]; - value = props[ index ]; - if ( Array.isArray( value ) ) { - easing = value[ 1 ]; - value = props[ index ] = value[ 0 ]; - } - - if ( index !== name ) { - props[ name ] = value; - delete props[ index ]; - } - - hooks = jQuery.cssHooks[ name ]; - if ( hooks && "expand" in hooks ) { - value = hooks.expand( value ); - delete props[ name ]; - - // Not quite $.extend, this won't overwrite existing keys. - // Reusing 'index' because we have the correct "name" - for ( index in value ) { - if ( !( index in props ) ) { - props[ index ] = value[ index ]; - specialEasing[ index ] = easing; - } - } - } else { - specialEasing[ name ] = easing; - } - } -} - -function Animation( elem, properties, options ) { - var result, - stopped, - index = 0, - length = Animation.prefilters.length, - deferred = jQuery.Deferred().always( function() { - - // Don't match elem in the :animated selector - delete tick.elem; - } ), - tick = function() { - if ( stopped ) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - - // Support: Android 2.3 only - // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( percent ); - } - - deferred.notifyWith( elem, [ animation, percent, remaining ] ); - - // If there's more to do, yield - if ( percent < 1 && length ) { - return remaining; - } - - // If this was an empty animation, synthesize a final progress notification - if ( !length ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - } - - // Resolve the animation and report its conclusion - deferred.resolveWith( elem, [ animation ] ); - return false; - }, - animation = deferred.promise( { - elem: elem, - props: jQuery.extend( {}, properties ), - opts: jQuery.extend( true, { - specialEasing: {}, - easing: jQuery.easing._default - }, options ), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function( prop, end ) { - var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); - animation.tweens.push( tween ); - return tween; - }, - stop: function( gotoEnd ) { - var index = 0, - - // If we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if ( stopped ) { - return this; - } - stopped = true; - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( 1 ); - } - - // Resolve when we played the last frame; otherwise, reject - if ( gotoEnd ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - deferred.resolveWith( elem, [ animation, gotoEnd ] ); - } else { - deferred.rejectWith( elem, [ animation, gotoEnd ] ); - } - return this; - } - } ), - props = animation.props; - - propFilter( props, animation.opts.specialEasing ); - - for ( ; index < length; index++ ) { - result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); - if ( result ) { - if ( isFunction( result.stop ) ) { - jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = - result.stop.bind( result ); - } - return result; - } - } - - jQuery.map( props, createTween, animation ); - - if ( isFunction( animation.opts.start ) ) { - animation.opts.start.call( elem, animation ); - } - - // Attach callbacks from options - animation - .progress( animation.opts.progress ) - .done( animation.opts.done, animation.opts.complete ) - .fail( animation.opts.fail ) - .always( animation.opts.always ); - - jQuery.fx.timer( - jQuery.extend( tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - } ) - ); - - return animation; -} - -jQuery.Animation = jQuery.extend( Animation, { - - tweeners: { - "*": [ function( prop, value ) { - var tween = this.createTween( prop, value ); - adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); - return tween; - } ] - }, - - tweener: function( props, callback ) { - if ( isFunction( props ) ) { - callback = props; - props = [ "*" ]; - } else { - props = props.match( rnothtmlwhite ); - } - - var prop, - index = 0, - length = props.length; - - for ( ; index < length; index++ ) { - prop = props[ index ]; - Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; - Animation.tweeners[ prop ].unshift( callback ); - } - }, - - prefilters: [ defaultPrefilter ], - - prefilter: function( callback, prepend ) { - if ( prepend ) { - Animation.prefilters.unshift( callback ); - } else { - Animation.prefilters.push( callback ); - } - } -} ); - -jQuery.speed = function( speed, easing, fn ) { - var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { - complete: fn || !fn && easing || - isFunction( speed ) && speed, - duration: speed, - easing: fn && easing || easing && !isFunction( easing ) && easing - }; - - // Go to the end state if fx are off - if ( jQuery.fx.off ) { - opt.duration = 0; - - } else { - if ( typeof opt.duration !== "number" ) { - if ( opt.duration in jQuery.fx.speeds ) { - opt.duration = jQuery.fx.speeds[ opt.duration ]; - - } else { - opt.duration = jQuery.fx.speeds._default; - } - } - } - - // Normalize opt.queue - true/undefined/null -> "fx" - if ( opt.queue == null || opt.queue === true ) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function() { - if ( isFunction( opt.old ) ) { - opt.old.call( this ); - } - - if ( opt.queue ) { - jQuery.dequeue( this, opt.queue ); - } - }; - - return opt; -}; - -jQuery.fn.extend( { - fadeTo: function( speed, to, easing, callback ) { - - // Show any hidden elements after setting opacity to 0 - return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() - - // Animate to the value specified - .end().animate( { opacity: to }, speed, easing, callback ); - }, - animate: function( prop, speed, easing, callback ) { - var empty = jQuery.isEmptyObject( prop ), - optall = jQuery.speed( speed, easing, callback ), - doAnimation = function() { - - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation( this, jQuery.extend( {}, prop ), optall ); - - // Empty animations, or finishing resolves immediately - if ( empty || dataPriv.get( this, "finish" ) ) { - anim.stop( true ); - } - }; - - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each( doAnimation ) : - this.queue( optall.queue, doAnimation ); - }, - stop: function( type, clearQueue, gotoEnd ) { - var stopQueue = function( hooks ) { - var stop = hooks.stop; - delete hooks.stop; - stop( gotoEnd ); - }; - - if ( typeof type !== "string" ) { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if ( clearQueue ) { - this.queue( type || "fx", [] ); - } - - return this.each( function() { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = dataPriv.get( this ); - - if ( index ) { - if ( data[ index ] && data[ index ].stop ) { - stopQueue( data[ index ] ); - } - } else { - for ( index in data ) { - if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { - stopQueue( data[ index ] ); - } - } - } - - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && - ( type == null || timers[ index ].queue === type ) ) { - - timers[ index ].anim.stop( gotoEnd ); - dequeue = false; - timers.splice( index, 1 ); - } - } - - // Start the next in the queue if the last step wasn't forced. - // Timers currently will call their complete callbacks, which - // will dequeue but only if they were gotoEnd. - if ( dequeue || !gotoEnd ) { - jQuery.dequeue( this, type ); - } - } ); - }, - finish: function( type ) { - if ( type !== false ) { - type = type || "fx"; - } - return this.each( function() { - var index, - data = dataPriv.get( this ), - queue = data[ type + "queue" ], - hooks = data[ type + "queueHooks" ], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // Enable finishing flag on private data - data.finish = true; - - // Empty the queue first - jQuery.queue( this, type, [] ); - - if ( hooks && hooks.stop ) { - hooks.stop.call( this, true ); - } - - // Look for any active animations, and finish them - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && timers[ index ].queue === type ) { - timers[ index ].anim.stop( true ); - timers.splice( index, 1 ); - } - } - - // Look for any animations in the old queue and finish them - for ( index = 0; index < length; index++ ) { - if ( queue[ index ] && queue[ index ].finish ) { - queue[ index ].finish.call( this ); - } - } - - // Turn off finishing flag - delete data.finish; - } ); - } -} ); - -jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { - var cssFn = jQuery.fn[ name ]; - jQuery.fn[ name ] = function( speed, easing, callback ) { - return speed == null || typeof speed === "boolean" ? - cssFn.apply( this, arguments ) : - this.animate( genFx( name, true ), speed, easing, callback ); - }; -} ); - -// Generate shortcuts for custom animations -jQuery.each( { - slideDown: genFx( "show" ), - slideUp: genFx( "hide" ), - slideToggle: genFx( "toggle" ), - fadeIn: { opacity: "show" }, - fadeOut: { opacity: "hide" }, - fadeToggle: { opacity: "toggle" } -}, function( name, props ) { - jQuery.fn[ name ] = function( speed, easing, callback ) { - return this.animate( props, speed, easing, callback ); - }; -} ); - -jQuery.timers = []; -jQuery.fx.tick = function() { - var timer, - i = 0, - timers = jQuery.timers; - - fxNow = Date.now(); - - for ( ; i < timers.length; i++ ) { - timer = timers[ i ]; - - // Run the timer and safely remove it when done (allowing for external removal) - if ( !timer() && timers[ i ] === timer ) { - timers.splice( i--, 1 ); - } - } - - if ( !timers.length ) { - jQuery.fx.stop(); - } - fxNow = undefined; -}; - -jQuery.fx.timer = function( timer ) { - jQuery.timers.push( timer ); - jQuery.fx.start(); -}; - -jQuery.fx.interval = 13; -jQuery.fx.start = function() { - if ( inProgress ) { - return; - } - - inProgress = true; - schedule(); -}; - -jQuery.fx.stop = function() { - inProgress = null; -}; - -jQuery.fx.speeds = { - slow: 600, - fast: 200, - - // Default speed - _default: 400 -}; - - -// Based off of the plugin by Clint Helfers, with permission. -// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ -jQuery.fn.delay = function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = window.setTimeout( next, time ); - hooks.stop = function() { - window.clearTimeout( timeout ); - }; - } ); -}; - - -( function() { - var input = document.createElement( "input" ), - select = document.createElement( "select" ), - opt = select.appendChild( document.createElement( "option" ) ); - - input.type = "checkbox"; - - // Support: Android <=4.3 only - // Default value for a checkbox should be "on" - support.checkOn = input.value !== ""; - - // Support: IE <=11 only - // Must access selectedIndex to make default options select - support.optSelected = opt.selected; - - // Support: IE <=11 only - // An input loses its value after becoming a radio - input = document.createElement( "input" ); - input.value = "t"; - input.type = "radio"; - support.radioValue = input.value === "t"; -} )(); - - -var boolHook, - attrHandle = jQuery.expr.attrHandle; - -jQuery.fn.extend( { - attr: function( name, value ) { - return access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each( function() { - jQuery.removeAttr( this, name ); - } ); - } -} ); - -jQuery.extend( { - attr: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set attributes on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - // Attribute hooks are determined by the lowercase version - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - hooks = jQuery.attrHooks[ name.toLowerCase() ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); - } - - if ( value !== undefined ) { - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - } - - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - elem.setAttribute( name, value + "" ); - return value; - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? undefined : ret; - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !support.radioValue && value === "radio" && - nodeName( elem, "input" ) ) { - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - removeAttr: function( elem, value ) { - var name, - i = 0, - - // Attribute names can contain non-HTML whitespace characters - // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 - attrNames = value && value.match( rnothtmlwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( ( name = attrNames[ i++ ] ) ) { - elem.removeAttribute( name ); - } - } - } -} ); - -// Hooks for boolean attributes -boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - elem.setAttribute( name, name ); - } - return name; - } -}; - -jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { - var getter = attrHandle[ name ] || jQuery.find.attr; - - attrHandle[ name ] = function( elem, name, isXML ) { - var ret, handle, - lowercaseName = name.toLowerCase(); - - if ( !isXML ) { - - // Avoid an infinite loop by temporarily removing this function from the getter - handle = attrHandle[ lowercaseName ]; - attrHandle[ lowercaseName ] = ret; - ret = getter( elem, name, isXML ) != null ? - lowercaseName : - null; - attrHandle[ lowercaseName ] = handle; - } - return ret; - }; -} ); - - - - -var rfocusable = /^(?:input|select|textarea|button)$/i, - rclickable = /^(?:a|area)$/i; - -jQuery.fn.extend( { - prop: function( name, value ) { - return access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - return this.each( function() { - delete this[ jQuery.propFix[ name ] || name ]; - } ); - } -} ); - -jQuery.extend( { - prop: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set properties on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - return ( elem[ name ] = value ); - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - return elem[ name ]; - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - - // Support: IE <=9 - 11 only - // elem.tabIndex doesn't always return the - // correct value when it hasn't been explicitly set - // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) - var tabindex = jQuery.find.attr( elem, "tabindex" ); - - if ( tabindex ) { - return parseInt( tabindex, 10 ); - } - - if ( - rfocusable.test( elem.nodeName ) || - rclickable.test( elem.nodeName ) && - elem.href - ) { - return 0; - } - - return -1; - } - } - }, - - propFix: { - "for": "htmlFor", - "class": "className" - } -} ); - -// Support: IE <=11 only -// Accessing the selectedIndex property -// forces the browser to respect setting selected -// on the option -// The getter ensures a default option is selected -// when in an optgroup -// eslint rule "no-unused-expressions" is disabled for this code -// since it considers such accessions noop -if ( !support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent && parent.parentNode ) { - parent.parentNode.selectedIndex; - } - return null; - }, - set: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }; -} - -jQuery.each( [ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" -], function() { - jQuery.propFix[ this.toLowerCase() ] = this; -} ); - - - - - // Strip and collapse whitespace according to HTML spec - // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace - function stripAndCollapse( value ) { - var tokens = value.match( rnothtmlwhite ) || []; - return tokens.join( " " ); - } - - -function getClass( elem ) { - return elem.getAttribute && elem.getAttribute( "class" ) || ""; -} - -function classesToArray( value ) { - if ( Array.isArray( value ) ) { - return value; - } - if ( typeof value === "string" ) { - return value.match( rnothtmlwhite ) || []; - } - return []; -} - -jQuery.fn.extend( { - addClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - if ( !arguments.length ) { - return this.attr( "class", "" ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) > -1 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isValidValue = type === "string" || Array.isArray( value ); - - if ( typeof stateVal === "boolean" && isValidValue ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); - } - - if ( isFunction( value ) ) { - return this.each( function( i ) { - jQuery( this ).toggleClass( - value.call( this, i, getClass( this ), stateVal ), - stateVal - ); - } ); - } - - return this.each( function() { - var className, i, self, classNames; - - if ( isValidValue ) { - - // Toggle individual class names - i = 0; - self = jQuery( this ); - classNames = classesToArray( value ); - - while ( ( className = classNames[ i++ ] ) ) { - - // Check each className given, space separated list - if ( self.hasClass( className ) ) { - self.removeClass( className ); - } else { - self.addClass( className ); - } - } - - // Toggle whole class name - } else if ( value === undefined || type === "boolean" ) { - className = getClass( this ); - if ( className ) { - - // Store className if set - dataPriv.set( this, "__className__", className ); - } - - // If the element has a class name or if we're passed `false`, - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - if ( this.setAttribute ) { - this.setAttribute( "class", - className || value === false ? - "" : - dataPriv.get( this, "__className__" ) || "" - ); - } - } - } ); - }, - - hasClass: function( selector ) { - var className, elem, - i = 0; - - className = " " + selector + " "; - while ( ( elem = this[ i++ ] ) ) { - if ( elem.nodeType === 1 && - ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { - return true; - } - } - - return false; - } -} ); - - - - -var rreturn = /\r/g; - -jQuery.fn.extend( { - val: function( value ) { - var hooks, ret, valueIsFunction, - elem = this[ 0 ]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || - jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && - "get" in hooks && - ( ret = hooks.get( elem, "value" ) ) !== undefined - ) { - return ret; - } - - ret = elem.value; - - // Handle most common string cases - if ( typeof ret === "string" ) { - return ret.replace( rreturn, "" ); - } - - // Handle cases where value is null/undef or number - return ret == null ? "" : ret; - } - - return; - } - - valueIsFunction = isFunction( value ); - - return this.each( function( i ) { - var val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( valueIsFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - - } else if ( typeof val === "number" ) { - val += ""; - - } else if ( Array.isArray( val ) ) { - val = jQuery.map( val, function( value ) { - return value == null ? "" : value + ""; - } ); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - } ); - } -} ); - -jQuery.extend( { - valHooks: { - option: { - get: function( elem ) { - - var val = jQuery.find.attr( elem, "value" ); - return val != null ? - val : - - // Support: IE <=10 - 11 only - // option.text throws exceptions (#14686, #14858) - // Strip and collapse whitespace - // https://html.spec.whatwg.org/#strip-and-collapse-whitespace - stripAndCollapse( jQuery.text( elem ) ); - } - }, - select: { - get: function( elem ) { - var value, option, i, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one", - values = one ? null : [], - max = one ? index + 1 : options.length; - - if ( index < 0 ) { - i = max; - - } else { - i = one ? index : 0; - } - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Support: IE <=9 only - // IE8-9 doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - - // Don't return options that are disabled or in a disabled optgroup - !option.disabled && - ( !option.parentNode.disabled || - !nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; - - while ( i-- ) { - option = options[ i ]; - - /* eslint-disable no-cond-assign */ - - if ( option.selected = - jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 - ) { - optionSet = true; - } - - /* eslint-enable no-cond-assign */ - } - - // Force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; - } - } - } -} ); - -// Radios and checkboxes getter/setter -jQuery.each( [ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( Array.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); - } - } - }; - if ( !support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - return elem.getAttribute( "value" ) === null ? "on" : elem.value; - }; - } -} ); - - - - -// Return jQuery for attributes-only inclusion - - -support.focusin = "onfocusin" in window; - - -var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - stopPropagationCallback = function( e ) { - e.stopPropagation(); - }; - -jQuery.extend( jQuery.event, { - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; - - cur = lastElement = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "." ) > -1 ) { - - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split( "." ); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf( ":" ) < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join( "." ); - event.rnamespace = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === ( elem.ownerDocument || document ) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { - lastElement = cur; - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && - dataPriv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( ( !special._default || - special._default.apply( eventPath.pop(), data ) === false ) && - acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - - if ( event.isPropagationStopped() ) { - lastElement.addEventListener( type, stopPropagationCallback ); - } - - elem[ type ](); - - if ( event.isPropagationStopped() ) { - lastElement.removeEventListener( type, stopPropagationCallback ); - } - - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - // Piggyback on a donor event to simulate a different one - // Used only for `focus(in | out)` events - simulate: function( type, elem, event ) { - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true - } - ); - - jQuery.event.trigger( e, null, elem ); - } - -} ); - -jQuery.fn.extend( { - - trigger: function( type, data ) { - return this.each( function() { - jQuery.event.trigger( type, data, this ); - } ); - }, - triggerHandler: function( type, data ) { - var elem = this[ 0 ]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -} ); - - -// Support: Firefox <=44 -// Firefox doesn't have focus(in | out) events -// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 -// -// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 -// focus(in | out) events fire after focus & blur events, -// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order -// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 -if ( !support.focusin ) { - jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - - // Handle: regular nodes (via `this.ownerDocument`), window - // (via `this.document`) & document (via `this`). - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - dataPriv.remove( doc, fix ); - - } else { - dataPriv.access( doc, fix, attaches ); - } - } - }; - } ); -} -var location = window.location; - -var nonce = { guid: Date.now() }; - -var rquery = ( /\?/ ); - - - -// Cross-browser xml parsing -jQuery.parseXML = function( data ) { - var xml, parserErrorElem; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE 9 - 11 only - // IE throws on parseFromString with invalid input. - try { - xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) {} - - parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; - if ( !xml || parserErrorElem ) { - jQuery.error( "Invalid XML: " + ( - parserErrorElem ? - jQuery.map( parserErrorElem.childNodes, function( el ) { - return el.textContent; - } ).join( "\n" ) : - data - ) ); - } - return xml; -}; - - -var - rbracket = /\[\]$/, - rCRLF = /\r?\n/g, - rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, - rsubmittable = /^(?:input|select|textarea|keygen)/i; - -function buildParams( prefix, obj, traditional, add ) { - var name; - - if ( Array.isArray( obj ) ) { - - // Serialize array item. - jQuery.each( obj, function( i, v ) { - if ( traditional || rbracket.test( prefix ) ) { - - // Treat each array item as a scalar. - add( prefix, v ); - - } else { - - // Item is non-scalar (array or object), encode its numeric index. - buildParams( - prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", - v, - traditional, - add - ); - } - } ); - - } else if ( !traditional && toType( obj ) === "object" ) { - - // Serialize object item. - for ( name in obj ) { - buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); - } - - } else { - - // Serialize scalar item. - add( prefix, obj ); - } -} - -// Serialize an array of form elements or a set of -// key/values into a query string -jQuery.param = function( a, traditional ) { - var prefix, - s = [], - add = function( key, valueOrFunction ) { - - // If value is a function, invoke it and use its return value - var value = isFunction( valueOrFunction ) ? - valueOrFunction() : - valueOrFunction; - - s[ s.length ] = encodeURIComponent( key ) + "=" + - encodeURIComponent( value == null ? "" : value ); - }; - - if ( a == null ) { - return ""; - } - - // If an array was passed in, assume that it is an array of form elements. - if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { - - // Serialize the form elements - jQuery.each( a, function() { - add( this.name, this.value ); - } ); - - } else { - - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for ( prefix in a ) { - buildParams( prefix, a[ prefix ], traditional, add ); - } - } - - // Return the resulting serialization - return s.join( "&" ); -}; - -jQuery.fn.extend( { - serialize: function() { - return jQuery.param( this.serializeArray() ); - }, - serializeArray: function() { - return this.map( function() { - - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop( this, "elements" ); - return elements ? jQuery.makeArray( elements ) : this; - } ).filter( function() { - var type = this.type; - - // Use .is( ":disabled" ) so that fieldset[disabled] works - return this.name && !jQuery( this ).is( ":disabled" ) && - rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && - ( this.checked || !rcheckableType.test( type ) ); - } ).map( function( _i, elem ) { - var val = jQuery( this ).val(); - - if ( val == null ) { - return null; - } - - if ( Array.isArray( val ) ) { - return jQuery.map( val, function( val ) { - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ); - } - - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ).get(); - } -} ); - - -var - r20 = /%20/g, - rhash = /#.*$/, - rantiCache = /([?&])_=[^&]*/, - rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, - - // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, - rnoContent = /^(?:GET|HEAD)$/, - rprotocol = /^\/\//, - - /* Prefilters - * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) - * 2) These are called: - * - BEFORE asking for a transport - * - AFTER param serialization (s.data is a string if s.processData is true) - * 3) key is the dataType - * 4) the catchall symbol "*" can be used - * 5) execution will start with transport dataType and THEN continue down to "*" if needed - */ - prefilters = {}, - - /* Transports bindings - * 1) key is the dataType - * 2) the catchall symbol "*" can be used - * 3) selection will start with transport dataType and THEN go to "*" if needed - */ - transports = {}, - - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression - allTypes = "*/".concat( "*" ), - - // Anchor tag for parsing the document origin - originAnchor = document.createElement( "a" ); - -originAnchor.href = location.href; - -// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport -function addToPrefiltersOrTransports( structure ) { - - // dataTypeExpression is optional and defaults to "*" - return function( dataTypeExpression, func ) { - - if ( typeof dataTypeExpression !== "string" ) { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; - - if ( isFunction( func ) ) { - - // For each dataType in the dataTypeExpression - while ( ( dataType = dataTypes[ i++ ] ) ) { - - // Prepend if requested - if ( dataType[ 0 ] === "+" ) { - dataType = dataType.slice( 1 ) || "*"; - ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); - - // Otherwise append - } else { - ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); - } - } - } - }; -} - -// Base inspection function for prefilters and transports -function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { - - var inspected = {}, - seekingTransport = ( structure === transports ); - - function inspect( dataType ) { - var selected; - inspected[ dataType ] = true; - jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { - var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); - if ( typeof dataTypeOrTransport === "string" && - !seekingTransport && !inspected[ dataTypeOrTransport ] ) { - - options.dataTypes.unshift( dataTypeOrTransport ); - inspect( dataTypeOrTransport ); - return false; - } else if ( seekingTransport ) { - return !( selected = dataTypeOrTransport ); - } - } ); - return selected; - } - - return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); -} - -// A special extend for ajax options -// that takes "flat" options (not to be deep extended) -// Fixes #9887 -function ajaxExtend( target, src ) { - var key, deep, - flatOptions = jQuery.ajaxSettings.flatOptions || {}; - - for ( key in src ) { - if ( src[ key ] !== undefined ) { - ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; - } - } - if ( deep ) { - jQuery.extend( true, target, deep ); - } - - return target; -} - -/* Handles responses to an ajax request: - * - finds the right dataType (mediates between content-type and expected dataType) - * - returns the corresponding response - */ -function ajaxHandleResponses( s, jqXHR, responses ) { - - var ct, type, finalDataType, firstDataType, - contents = s.contents, - dataTypes = s.dataTypes; - - // Remove auto dataType and get content-type in the process - while ( dataTypes[ 0 ] === "*" ) { - dataTypes.shift(); - if ( ct === undefined ) { - ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); - } - } - - // Check if we're dealing with a known content-type - if ( ct ) { - for ( type in contents ) { - if ( contents[ type ] && contents[ type ].test( ct ) ) { - dataTypes.unshift( type ); - break; - } - } - } - - // Check to see if we have a response for the expected dataType - if ( dataTypes[ 0 ] in responses ) { - finalDataType = dataTypes[ 0 ]; - } else { - - // Try convertible dataTypes - for ( type in responses ) { - if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { - finalDataType = type; - break; - } - if ( !firstDataType ) { - firstDataType = type; - } - } - - // Or just use first one - finalDataType = finalDataType || firstDataType; - } - - // If we found a dataType - // We add the dataType to the list if needed - // and return the corresponding response - if ( finalDataType ) { - if ( finalDataType !== dataTypes[ 0 ] ) { - dataTypes.unshift( finalDataType ); - } - return responses[ finalDataType ]; - } -} - -/* Chain conversions given the request and the original response - * Also sets the responseXXX fields on the jqXHR instance - */ -function ajaxConvert( s, response, jqXHR, isSuccess ) { - var conv2, current, conv, tmp, prev, - converters = {}, - - // Work with a copy of dataTypes in case we need to modify it for conversion - dataTypes = s.dataTypes.slice(); - - // Create converters map with lowercased keys - if ( dataTypes[ 1 ] ) { - for ( conv in s.converters ) { - converters[ conv.toLowerCase() ] = s.converters[ conv ]; - } - } - - current = dataTypes.shift(); - - // Convert to each sequential dataType - while ( current ) { - - if ( s.responseFields[ current ] ) { - jqXHR[ s.responseFields[ current ] ] = response; - } - - // Apply the dataFilter if provided - if ( !prev && isSuccess && s.dataFilter ) { - response = s.dataFilter( response, s.dataType ); - } - - prev = current; - current = dataTypes.shift(); - - if ( current ) { - - // There's only work to do if current dataType is non-auto - if ( current === "*" ) { - - current = prev; - - // Convert response if prev dataType is non-auto and differs from current - } else if ( prev !== "*" && prev !== current ) { - - // Seek a direct converter - conv = converters[ prev + " " + current ] || converters[ "* " + current ]; - - // If none found, seek a pair - if ( !conv ) { - for ( conv2 in converters ) { - - // If conv2 outputs current - tmp = conv2.split( " " ); - if ( tmp[ 1 ] === current ) { - - // If prev can be converted to accepted input - conv = converters[ prev + " " + tmp[ 0 ] ] || - converters[ "* " + tmp[ 0 ] ]; - if ( conv ) { - - // Condense equivalence converters - if ( conv === true ) { - conv = converters[ conv2 ]; - - // Otherwise, insert the intermediate dataType - } else if ( converters[ conv2 ] !== true ) { - current = tmp[ 0 ]; - dataTypes.unshift( tmp[ 1 ] ); - } - break; - } - } - } - } - - // Apply converter (if not an equivalence) - if ( conv !== true ) { - - // Unless errors are allowed to bubble, catch and return them - if ( conv && s.throws ) { - response = conv( response ); - } else { - try { - response = conv( response ); - } catch ( e ) { - return { - state: "parsererror", - error: conv ? e : "No conversion from " + prev + " to " + current - }; - } - } - } - } - } - } - - return { state: "success", data: response }; -} - -jQuery.extend( { - - // Counter for holding the number of active queries - active: 0, - - // Last-Modified header cache for next request - lastModified: {}, - etag: {}, - - ajaxSettings: { - url: location.href, - type: "GET", - isLocal: rlocalProtocol.test( location.protocol ), - global: true, - processData: true, - async: true, - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - - /* - timeout: 0, - data: null, - dataType: null, - username: null, - password: null, - cache: null, - throws: false, - traditional: false, - headers: {}, - */ - - accepts: { - "*": allTypes, - text: "text/plain", - html: "text/html", - xml: "application/xml, text/xml", - json: "application/json, text/javascript" - }, - - contents: { - xml: /\bxml\b/, - html: /\bhtml/, - json: /\bjson\b/ - }, - - responseFields: { - xml: "responseXML", - text: "responseText", - json: "responseJSON" - }, - - // Data converters - // Keys separate source (or catchall "*") and destination types with a single space - converters: { - - // Convert anything to text - "* text": String, - - // Text to html (true = no transformation) - "text html": true, - - // Evaluate text as a json expression - "text json": JSON.parse, - - // Parse text as xml - "text xml": jQuery.parseXML - }, - - // For options that shouldn't be deep extended: - // you can add your own custom options here if - // and when you create one that shouldn't be - // deep extended (see ajaxExtend) - flatOptions: { - url: true, - context: true - } - }, - - // Creates a full fledged settings object into target - // with both ajaxSettings and settings fields. - // If target is omitted, writes into ajaxSettings. - ajaxSetup: function( target, settings ) { - return settings ? - - // Building a settings object - ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : - - // Extending ajaxSettings - ajaxExtend( jQuery.ajaxSettings, target ); - }, - - ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), - ajaxTransport: addToPrefiltersOrTransports( transports ), - - // Main method - ajax: function( url, options ) { - - // If url is an object, simulate pre-1.5 signature - if ( typeof url === "object" ) { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var transport, - - // URL without anti-cache param - cacheURL, - - // Response headers - responseHeadersString, - responseHeaders, - - // timeout handle - timeoutTimer, - - // Url cleanup var - urlAnchor, - - // Request state (becomes false upon send and true upon completion) - completed, - - // To know if global events are to be dispatched - fireGlobals, - - // Loop variable - i, - - // uncached part of the url - uncached, - - // Create the final options object - s = jQuery.ajaxSetup( {}, options ), - - // Callbacks context - callbackContext = s.context || s, - - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && - ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, - - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks( "once memory" ), - - // Status-dependent callbacks - statusCode = s.statusCode || {}, - - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - - // Default abort message - strAbort = "canceled", - - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function( key ) { - var match; - if ( completed ) { - if ( !responseHeaders ) { - responseHeaders = {}; - while ( ( match = rheaders.exec( responseHeadersString ) ) ) { - responseHeaders[ match[ 1 ].toLowerCase() + " " ] = - ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) - .concat( match[ 2 ] ); - } - } - match = responseHeaders[ key.toLowerCase() + " " ]; - } - return match == null ? null : match.join( ", " ); - }, - - // Raw string - getAllResponseHeaders: function() { - return completed ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function( name, value ) { - if ( completed == null ) { - name = requestHeadersNames[ name.toLowerCase() ] = - requestHeadersNames[ name.toLowerCase() ] || name; - requestHeaders[ name ] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function( type ) { - if ( completed == null ) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function( map ) { - var code; - if ( map ) { - if ( completed ) { - - // Execute the appropriate callbacks - jqXHR.always( map[ jqXHR.status ] ); - } else { - - // Lazy-add the new callbacks in a way that preserves old ones - for ( code in map ) { - statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; - } - } - } - return this; - }, - - // Cancel the request - abort: function( statusText ) { - var finalText = statusText || strAbort; - if ( transport ) { - transport.abort( finalText ); - } - done( 0, finalText ); - return this; - } - }; - - // Attach deferreds - deferred.promise( jqXHR ); - - // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ( ( url || s.url || location.href ) + "" ) - .replace( rprotocol, location.protocol + "//" ); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; - - // A cross-domain request is in order when the origin doesn't match the current origin. - if ( s.crossDomain == null ) { - urlAnchor = document.createElement( "a" ); - - // Support: IE <=8 - 11, Edge 12 - 15 - // IE throws exception on accessing the href property if url is malformed, - // e.g. http://example.com:80x/ - try { - urlAnchor.href = s.url; - - // Support: IE <=8 - 11 only - // Anchor's host property isn't correctly set when s.url is relative - urlAnchor.href = urlAnchor.href; - s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== - urlAnchor.protocol + "//" + urlAnchor.host; - } catch ( e ) { - - // If there is an error parsing the URL, assume it is crossDomain, - // it can be rejected by the transport if it is invalid - s.crossDomain = true; - } - } - - // Convert data if not already a string - if ( s.data && s.processData && typeof s.data !== "string" ) { - s.data = jQuery.param( s.data, s.traditional ); - } - - // Apply prefilters - inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); - - // If request was aborted inside a prefilter, stop there - if ( completed ) { - return jqXHR; - } - - // We can fire global events as of now if asked to - // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) - fireGlobals = jQuery.event && s.global; - - // Watch for a new set of requests - if ( fireGlobals && jQuery.active++ === 0 ) { - jQuery.event.trigger( "ajaxStart" ); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test( s.type ); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - // Remove hash to simplify url manipulation - cacheURL = s.url.replace( rhash, "" ); - - // More options handling for requests with no content - if ( !s.hasContent ) { - - // Remember the hash so we can put it back - uncached = s.url.slice( cacheURL.length ); - - // If data is available and should be processed, append data to url - if ( s.data && ( s.processData || typeof s.data === "string" ) ) { - cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; - - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add or update anti-cache param if needed - if ( s.cache === false ) { - cacheURL = cacheURL.replace( rantiCache, "$1" ); - uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + - uncached; - } - - // Put hash and anti-cache on the URL that will be requested (gh-1732) - s.url = cacheURL + uncached; - - // Change '%20' to '+' if this is encoded form body content (gh-2658) - } else if ( s.data && s.processData && - ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { - s.data = s.data.replace( r20, "+" ); - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - if ( jQuery.lastModified[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); - } - if ( jQuery.etag[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); - } - } - - // Set the correct header, if data is being sent - if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { - jqXHR.setRequestHeader( "Content-Type", s.contentType ); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? - s.accepts[ s.dataTypes[ 0 ] ] + - ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : - s.accepts[ "*" ] - ); - - // Check for headers option - for ( i in s.headers ) { - jqXHR.setRequestHeader( i, s.headers[ i ] ); - } - - // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && - ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { - - // Abort if not done already and return - return jqXHR.abort(); - } - - // Aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - completeDeferred.add( s.complete ); - jqXHR.done( s.success ); - jqXHR.fail( s.error ); - - // Get transport - transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); - - // If no transport, we auto-abort - if ( !transport ) { - done( -1, "No Transport" ); - } else { - jqXHR.readyState = 1; - - // Send global event - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); - } - - // If request was aborted inside ajaxSend, stop there - if ( completed ) { - return jqXHR; - } - - // Timeout - if ( s.async && s.timeout > 0 ) { - timeoutTimer = window.setTimeout( function() { - jqXHR.abort( "timeout" ); - }, s.timeout ); - } - - try { - completed = false; - transport.send( requestHeaders, done ); - } catch ( e ) { - - // Rethrow post-completion exceptions - if ( completed ) { - throw e; - } - - // Propagate others as results - done( -1, e ); - } - } - - // Callback for when everything is done - function done( status, nativeStatusText, responses, headers ) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Ignore repeat invocations - if ( completed ) { - return; - } - - completed = true; - - // Clear timeout if it exists - if ( timeoutTimer ) { - window.clearTimeout( timeoutTimer ); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Determine if successful - isSuccess = status >= 200 && status < 300 || status === 304; - - // Get response data - if ( responses ) { - response = ajaxHandleResponses( s, jqXHR, responses ); - } - - // Use a noop converter for missing script but not if jsonp - if ( !isSuccess && - jQuery.inArray( "script", s.dataTypes ) > -1 && - jQuery.inArray( "json", s.dataTypes ) < 0 ) { - s.converters[ "text script" ] = function() {}; - } - - // Convert no matter what (that way responseXXX fields are always set) - response = ajaxConvert( s, response, jqXHR, isSuccess ); - - // If successful, handle type chaining - if ( isSuccess ) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - modified = jqXHR.getResponseHeader( "Last-Modified" ); - if ( modified ) { - jQuery.lastModified[ cacheURL ] = modified; - } - modified = jqXHR.getResponseHeader( "etag" ); - if ( modified ) { - jQuery.etag[ cacheURL ] = modified; - } - } - - // if no content - if ( status === 204 || s.type === "HEAD" ) { - statusText = "nocontent"; - - // if not modified - } else if ( status === 304 ) { - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - statusText = response.state; - success = response.data; - error = response.error; - isSuccess = !error; - } - } else { - - // Extract error from statusText and normalize for non-aborts - error = statusText; - if ( status || !statusText ) { - statusText = "error"; - if ( status < 0 ) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = ( nativeStatusText || statusText ) + ""; - - // Success/Error - if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); - } else { - deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); - } - - // Status-dependent callbacks - jqXHR.statusCode( statusCode ); - statusCode = undefined; - - if ( fireGlobals ) { - globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", - [ jqXHR, s, isSuccess ? success : error ] ); - } - - // Complete - completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); - - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); - - // Handle the global AJAX counter - if ( !( --jQuery.active ) ) { - jQuery.event.trigger( "ajaxStop" ); - } - } - } - - return jqXHR; - }, - - getJSON: function( url, data, callback ) { - return jQuery.get( url, data, callback, "json" ); - }, - - getScript: function( url, callback ) { - return jQuery.get( url, undefined, callback, "script" ); - } -} ); - -jQuery.each( [ "get", "post" ], function( _i, method ) { - jQuery[ method ] = function( url, data, callback, type ) { - - // Shift arguments if data argument was omitted - if ( isFunction( data ) ) { - type = type || callback; - callback = data; - data = undefined; - } - - // The url can be an options object (which then must have .url) - return jQuery.ajax( jQuery.extend( { - url: url, - type: method, - dataType: type, - data: data, - success: callback - }, jQuery.isPlainObject( url ) && url ) ); - }; -} ); - -jQuery.ajaxPrefilter( function( s ) { - var i; - for ( i in s.headers ) { - if ( i.toLowerCase() === "content-type" ) { - s.contentType = s.headers[ i ] || ""; - } - } -} ); - - -jQuery._evalUrl = function( url, options, doc ) { - return jQuery.ajax( { - url: url, - - // Make this explicit, since user can override this through ajaxSetup (#11264) - type: "GET", - dataType: "script", - cache: true, - async: false, - global: false, - - // Only evaluate the response if it is successful (gh-4126) - // dataFilter is not invoked for failure responses, so using it instead - // of the default converter is kludgy but it works. - converters: { - "text script": function() {} - }, - dataFilter: function( response ) { - jQuery.globalEval( response, options, doc ); - } - } ); -}; - - -jQuery.fn.extend( { - wrapAll: function( html ) { - var wrap; - - if ( this[ 0 ] ) { - if ( isFunction( html ) ) { - html = html.call( this[ 0 ] ); - } - - // The elements to wrap the target around - wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); - - if ( this[ 0 ].parentNode ) { - wrap.insertBefore( this[ 0 ] ); - } - - wrap.map( function() { - var elem = this; - - while ( elem.firstElementChild ) { - elem = elem.firstElementChild; - } - - return elem; - } ).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( isFunction( html ) ) { - return this.each( function( i ) { - jQuery( this ).wrapInner( html.call( this, i ) ); - } ); - } - - return this.each( function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - } ); - }, - - wrap: function( html ) { - var htmlIsFunction = isFunction( html ); - - return this.each( function( i ) { - jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); - } ); - }, - - unwrap: function( selector ) { - this.parent( selector ).not( "body" ).each( function() { - jQuery( this ).replaceWith( this.childNodes ); - } ); - return this; - } -} ); - - -jQuery.expr.pseudos.hidden = function( elem ) { - return !jQuery.expr.pseudos.visible( elem ); -}; -jQuery.expr.pseudos.visible = function( elem ) { - return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); -}; - - - - -jQuery.ajaxSettings.xhr = function() { - try { - return new window.XMLHttpRequest(); - } catch ( e ) {} -}; - -var xhrSuccessStatus = { - - // File protocol always yields status code 0, assume 200 - 0: 200, - - // Support: IE <=9 only - // #1450: sometimes IE returns 1223 when it should be 204 - 1223: 204 - }, - xhrSupported = jQuery.ajaxSettings.xhr(); - -support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); -support.ajax = xhrSupported = !!xhrSupported; - -jQuery.ajaxTransport( function( options ) { - var callback, errorCallback; - - // Cross domain only allowed if supported through XMLHttpRequest - if ( support.cors || xhrSupported && !options.crossDomain ) { - return { - send: function( headers, complete ) { - var i, - xhr = options.xhr(); - - xhr.open( - options.type, - options.url, - options.async, - options.username, - options.password - ); - - // Apply custom fields if provided - if ( options.xhrFields ) { - for ( i in options.xhrFields ) { - xhr[ i ] = options.xhrFields[ i ]; - } - } - - // Override mime type if needed - if ( options.mimeType && xhr.overrideMimeType ) { - xhr.overrideMimeType( options.mimeType ); - } - - // X-Requested-With header - // For cross-domain requests, seeing as conditions for a preflight are - // akin to a jigsaw puzzle, we simply never set it to be sure. - // (it can always be set on a per-request basis or even using ajaxSetup) - // For same-domain requests, won't change header if already provided. - if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { - headers[ "X-Requested-With" ] = "XMLHttpRequest"; - } - - // Set headers - for ( i in headers ) { - xhr.setRequestHeader( i, headers[ i ] ); - } - - // Callback - callback = function( type ) { - return function() { - if ( callback ) { - callback = errorCallback = xhr.onload = - xhr.onerror = xhr.onabort = xhr.ontimeout = - xhr.onreadystatechange = null; - - if ( type === "abort" ) { - xhr.abort(); - } else if ( type === "error" ) { - - // Support: IE <=9 only - // On a manual native abort, IE9 throws - // errors on any property access that is not readyState - if ( typeof xhr.status !== "number" ) { - complete( 0, "error" ); - } else { - complete( - - // File: protocol always yields status 0; see #8605, #14207 - xhr.status, - xhr.statusText - ); - } - } else { - complete( - xhrSuccessStatus[ xhr.status ] || xhr.status, - xhr.statusText, - - // Support: IE <=9 only - // IE9 has no XHR2 but throws on binary (trac-11426) - // For XHR2 non-text, let the caller handle it (gh-2498) - ( xhr.responseType || "text" ) !== "text" || - typeof xhr.responseText !== "string" ? - { binary: xhr.response } : - { text: xhr.responseText }, - xhr.getAllResponseHeaders() - ); - } - } - }; - }; - - // Listen to events - xhr.onload = callback(); - errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); - - // Support: IE 9 only - // Use onreadystatechange to replace onabort - // to handle uncaught aborts - if ( xhr.onabort !== undefined ) { - xhr.onabort = errorCallback; - } else { - xhr.onreadystatechange = function() { - - // Check readyState before timeout as it changes - if ( xhr.readyState === 4 ) { - - // Allow onerror to be called first, - // but that will not handle a native abort - // Also, save errorCallback to a variable - // as xhr.onerror cannot be accessed - window.setTimeout( function() { - if ( callback ) { - errorCallback(); - } - } ); - } - }; - } - - // Create the abort callback - callback = callback( "abort" ); - - try { - - // Do send the request (this may raise an exception) - xhr.send( options.hasContent && options.data || null ); - } catch ( e ) { - - // #14683: Only rethrow if this hasn't been notified as an error yet - if ( callback ) { - throw e; - } - } - }, - - abort: function() { - if ( callback ) { - callback(); - } - } - }; - } -} ); - - - - -// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) -jQuery.ajaxPrefilter( function( s ) { - if ( s.crossDomain ) { - s.contents.script = false; - } -} ); - -// Install script dataType -jQuery.ajaxSetup( { - accepts: { - script: "text/javascript, application/javascript, " + - "application/ecmascript, application/x-ecmascript" - }, - contents: { - script: /\b(?:java|ecma)script\b/ - }, - converters: { - "text script": function( text ) { - jQuery.globalEval( text ); - return text; - } - } -} ); - -// Handle cache's special case and crossDomain -jQuery.ajaxPrefilter( "script", function( s ) { - if ( s.cache === undefined ) { - s.cache = false; - } - if ( s.crossDomain ) { - s.type = "GET"; - } -} ); - -// Bind script tag hack transport -jQuery.ajaxTransport( "script", function( s ) { - - // This transport only deals with cross domain or forced-by-attrs requests - if ( s.crossDomain || s.scriptAttrs ) { - var script, callback; - return { - send: function( _, complete ) { - script = jQuery( " - <% end %> - - - - - - NAV - <%= image_tag('navbar.png') %> - - -
      - <%= image_tag "logo.png", class: 'logo' %> - <% if language_tabs.any? %> -
      - <% language_tabs.each do |lang| %> - <% if lang.is_a? Hash %> - <%= lang.values.first %> - <% else %> - <%= lang %> - <% end %> - <% end %> -
      - <% end %> - <% if current_page.data.search %> - -
        - <% end %> -
          - <% toc_data(page_content).each do |h1| %> -
        • - <%= h1[:content] %> - <% if h1[:children].length > 0 %> - - <% end %> -
        • - <% end %> -
        - <% if current_page.data.toc_footers %> - - <% end %> -
        -
        -
        -
        - <%= page_content %> -
        -
        - <% if language_tabs.any? %> -
        - <% language_tabs.each do |lang| %> - <% if lang.is_a? Hash %> - <%= lang.values.first %> - <% else %> - <%= lang %> - <% end %> - <% end %> -
        - <% end %> -
        -
        - - diff --git a/samples/rest-notes-slate/slate/source/stylesheets/_icon-font.scss b/samples/rest-notes-slate/slate/source/stylesheets/_icon-font.scss deleted file mode 100644 index b59948398..000000000 --- a/samples/rest-notes-slate/slate/source/stylesheets/_icon-font.scss +++ /dev/null @@ -1,38 +0,0 @@ -@font-face { - font-family: 'slate'; - src:font-url('slate.eot?-syv14m'); - src:font-url('slate.eot?#iefix-syv14m') format('embedded-opentype'), - font-url('slate.woff2?-syv14m') format('woff2'), - font-url('slate.woff?-syv14m') format('woff'), - font-url('slate.ttf?-syv14m') format('truetype'), - font-url('slate.svg?-syv14m#slate') format('svg'); - font-weight: normal; - font-style: normal; -} - -%icon { - font-family: 'slate'; - speak: none; - font-style: normal; - font-weight: normal; - font-variant: normal; - text-transform: none; - line-height: 1; -} - -%icon-exclamation-sign { - @extend %icon; - content: "\e600"; -} -%icon-info-sign { - @extend %icon; - content: "\e602"; -} -%icon-ok-sign { - @extend %icon; - content: "\e606"; -} -%icon-search { - @extend %icon; - content: "\e607"; -} diff --git a/samples/rest-notes-slate/slate/source/stylesheets/_normalize.scss b/samples/rest-notes-slate/slate/source/stylesheets/_normalize.scss deleted file mode 100644 index 46f646a5c..000000000 --- a/samples/rest-notes-slate/slate/source/stylesheets/_normalize.scss +++ /dev/null @@ -1,427 +0,0 @@ -/*! normalize.css v3.0.2 | MIT License | git.io/normalize */ - -/** - * 1. Set default font family to sans-serif. - * 2. Prevent iOS text size adjust after orientation change, without disabling - * user zoom. - */ - -html { - font-family: sans-serif; /* 1 */ - -ms-text-size-adjust: 100%; /* 2 */ - -webkit-text-size-adjust: 100%; /* 2 */ -} - -/** - * Remove default margin. - */ - -body { - margin: 0; -} - -/* HTML5 display definitions - ========================================================================== */ - -/** - * Correct `block` display not defined for any HTML5 element in IE 8/9. - * Correct `block` display not defined for `details` or `summary` in IE 10/11 - * and Firefox. - * Correct `block` display not defined for `main` in IE 11. - */ - -article, -aside, -details, -figcaption, -figure, -footer, -header, -hgroup, -main, -menu, -nav, -section, -summary { - display: block; -} - -/** - * 1. Correct `inline-block` display not defined in IE 8/9. - * 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera. - */ - -audio, -canvas, -progress, -video { - display: inline-block; /* 1 */ - vertical-align: baseline; /* 2 */ -} - -/** - * Prevent modern browsers from displaying `audio` without controls. - * Remove excess height in iOS 5 devices. - */ - -audio:not([controls]) { - display: none; - height: 0; -} - -/** - * Address `[hidden]` styling not present in IE 8/9/10. - * Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22. - */ - -[hidden], -template { - display: none; -} - -/* Links - ========================================================================== */ - -/** - * Remove the gray background color from active links in IE 10. - */ - -a { - background-color: transparent; -} - -/** - * Improve readability when focused and also mouse hovered in all browsers. - */ - -a:active, -a:hover { - outline: 0; -} - -/* Text-level semantics - ========================================================================== */ - -/** - * Address styling not present in IE 8/9/10/11, Safari, and Chrome. - */ - -abbr[title] { - border-bottom: 1px dotted; -} - -/** - * Address style set to `bolder` in Firefox 4+, Safari, and Chrome. - */ - -b, -strong { - font-weight: bold; -} - -/** - * Address styling not present in Safari and Chrome. - */ - -dfn { - font-style: italic; -} - -/** - * Address variable `h1` font-size and margin within `section` and `article` - * contexts in Firefox 4+, Safari, and Chrome. - */ - -h1 { - font-size: 2em; - margin: 0.67em 0; -} - -/** - * Address styling not present in IE 8/9. - */ - -mark { - background: #ff0; - color: #000; -} - -/** - * Address inconsistent and variable font size in all browsers. - */ - -small { - font-size: 80%; -} - -/** - * Prevent `sub` and `sup` affecting `line-height` in all browsers. - */ - -sub, -sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; -} - -sup { - top: -0.5em; -} - -sub { - bottom: -0.25em; -} - -/* Embedded content - ========================================================================== */ - -/** - * Remove border when inside `a` element in IE 8/9/10. - */ - -img { - border: 0; -} - -/** - * Correct overflow not hidden in IE 9/10/11. - */ - -svg:not(:root) { - overflow: hidden; -} - -/* Grouping content - ========================================================================== */ - -/** - * Address margin not present in IE 8/9 and Safari. - */ - -figure { - margin: 1em 40px; -} - -/** - * Address differences between Firefox and other browsers. - */ - -hr { - -moz-box-sizing: content-box; - box-sizing: content-box; - height: 0; -} - -/** - * Contain overflow in all browsers. - */ - -pre { - overflow: auto; -} - -/** - * Address odd `em`-unit font size rendering in all browsers. - */ - -code, -kbd, -pre, -samp { - font-family: monospace, monospace; - font-size: 1em; -} - -/* Forms - ========================================================================== */ - -/** - * Known limitation: by default, Chrome and Safari on OS X allow very limited - * styling of `select`, unless a `border` property is set. - */ - -/** - * 1. Correct color not being inherited. - * Known issue: affects color of disabled elements. - * 2. Correct font properties not being inherited. - * 3. Address margins set differently in Firefox 4+, Safari, and Chrome. - */ - -button, -input, -optgroup, -select, -textarea { - color: inherit; /* 1 */ - font: inherit; /* 2 */ - margin: 0; /* 3 */ -} - -/** - * Address `overflow` set to `hidden` in IE 8/9/10/11. - */ - -button { - overflow: visible; -} - -/** - * Address inconsistent `text-transform` inheritance for `button` and `select`. - * All other form control elements do not inherit `text-transform` values. - * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera. - * Correct `select` style inheritance in Firefox. - */ - -button, -select { - text-transform: none; -} - -/** - * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` - * and `video` controls. - * 2. Correct inability to style clickable `input` types in iOS. - * 3. Improve usability and consistency of cursor style between image-type - * `input` and others. - */ - -button, -html input[type="button"], /* 1 */ -input[type="reset"], -input[type="submit"] { - -webkit-appearance: button; /* 2 */ - cursor: pointer; /* 3 */ -} - -/** - * Re-set default cursor for disabled elements. - */ - -button[disabled], -html input[disabled] { - cursor: default; -} - -/** - * Remove inner padding and border in Firefox 4+. - */ - -button::-moz-focus-inner, -input::-moz-focus-inner { - border: 0; - padding: 0; -} - -/** - * Address Firefox 4+ setting `line-height` on `input` using `!important` in - * the UA stylesheet. - */ - -input { - line-height: normal; -} - -/** - * It's recommended that you don't attempt to style these elements. - * Firefox's implementation doesn't respect box-sizing, padding, or width. - * - * 1. Address box sizing set to `content-box` in IE 8/9/10. - * 2. Remove excess padding in IE 8/9/10. - */ - -input[type="checkbox"], -input[type="radio"] { - box-sizing: border-box; /* 1 */ - padding: 0; /* 2 */ -} - -/** - * Fix the cursor style for Chrome's increment/decrement buttons. For certain - * `font-size` values of the `input`, it causes the cursor style of the - * decrement button to change from `default` to `text`. - */ - -input[type="number"]::-webkit-inner-spin-button, -input[type="number"]::-webkit-outer-spin-button { - height: auto; -} - -/** - * 1. Address `appearance` set to `searchfield` in Safari and Chrome. - * 2. Address `box-sizing` set to `border-box` in Safari and Chrome - * (include `-moz` to future-proof). - */ - -input[type="search"] { - -webkit-appearance: textfield; /* 1 */ - -moz-box-sizing: content-box; - -webkit-box-sizing: content-box; /* 2 */ - box-sizing: content-box; -} - -/** - * Remove inner padding and search cancel button in Safari and Chrome on OS X. - * Safari (but not Chrome) clips the cancel button when the search input has - * padding (and `textfield` appearance). - */ - -input[type="search"]::-webkit-search-cancel-button, -input[type="search"]::-webkit-search-decoration { - -webkit-appearance: none; -} - -/** - * Define consistent border, margin, and padding. - */ - -fieldset { - border: 1px solid #c0c0c0; - margin: 0 2px; - padding: 0.35em 0.625em 0.75em; -} - -/** - * 1. Correct `color` not being inherited in IE 8/9/10/11. - * 2. Remove padding so people aren't caught out if they zero out fieldsets. - */ - -legend { - border: 0; /* 1 */ - padding: 0; /* 2 */ -} - -/** - * Remove default vertical scrollbar in IE 8/9/10/11. - */ - -textarea { - overflow: auto; -} - -/** - * Don't inherit the `font-weight` (applied by a rule above). - * NOTE: the default cannot safely be changed in Chrome and Safari on OS X. - */ - -optgroup { - font-weight: bold; -} - -/* Tables - ========================================================================== */ - -/** - * Remove most spacing between table cells. - */ - -table { - border-collapse: collapse; - border-spacing: 0; -} - -td, -th { - padding: 0; -} diff --git a/samples/rest-notes-slate/slate/source/stylesheets/_rtl.scss b/samples/rest-notes-slate/slate/source/stylesheets/_rtl.scss deleted file mode 100644 index 720719a02..000000000 --- a/samples/rest-notes-slate/slate/source/stylesheets/_rtl.scss +++ /dev/null @@ -1,140 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// RTL Styles Variables -//////////////////////////////////////////////////////////////////////////////// - -$default: auto; - -//////////////////////////////////////////////////////////////////////////////// -// TABLE OF CONTENTS -//////////////////////////////////////////////////////////////////////////////// - -#toc>ul>li>a>span { - float: left; -} - -.toc-wrapper { - transition: right 0.3s ease-in-out !important; - left: $default !important; - #{right}: 0; -} - -.toc-h2 { - padding-#{right}: $nav-padding + $nav-indent; -} - -#nav-button { - #{right}: 0; - transition: right 0.3s ease-in-out; - &.open { - right: $nav-width - } -} - -//////////////////////////////////////////////////////////////////////////////// -// PAGE LAYOUT AND CODE SAMPLE BACKGROUND -//////////////////////////////////////////////////////////////////////////////// -.page-wrapper { - margin-#{left}: $default !important; - margin-#{right}: $nav-width; - .dark-box { - #{right}: $default; - #{left}: 0; - } -} - -.lang-selector { - width: $default !important; - a { - float: right; - } -} - -//////////////////////////////////////////////////////////////////////////////// -// CODE SAMPLE STYLES -//////////////////////////////////////////////////////////////////////////////// -.content { - &>h1, - &>h2, - &>h3, - &>h4, - &>h5, - &>h6, - &>p, - &>table, - &>ul, - &>ol, - &>aside, - &>dl { - margin-#{left}: $examples-width; - margin-#{right}: $default !important; - } - &>ul, - &>ol { - padding-#{right}: $main-padding + 15px; - } - table { - th, - td { - text-align: right; - } - } - dd { - margin-#{right}: 15px; - } - aside { - aside:before { - padding-#{left}: 0.5em; - } - .search-highlight { - background: linear-gradient(to top right, #F7E633 0%, #F1D32F 100%); - } - } - pre, - blockquote { - float: left !important; - clear: left !important; - } -} - -//////////////////////////////////////////////////////////////////////////////// -// TYPOGRAPHY -//////////////////////////////////////////////////////////////////////////////// -h1, -h2, -h3, -h4, -h5, -h6, -p, -aside { - text-align: right; - direction: rtl; -} - -.toc-wrapper { - text-align: right; - direction: rtl; - font-weight: 100 !important; -} - - -//////////////////////////////////////////////////////////////////////////////// -// RESPONSIVE DESIGN -//////////////////////////////////////////////////////////////////////////////// -@media (max-width: $tablet-width) { - .toc-wrapper { - #{right}: -$nav-width; - &.open { - #{right}: 0; - } - } - .page-wrapper { - margin-#{right}: 0; - } -} - -@media (max-width: $phone-width) { - %left-col { - margin-#{left}: 0; - } -} diff --git a/samples/rest-notes-slate/slate/source/stylesheets/_variables.scss b/samples/rest-notes-slate/slate/source/stylesheets/_variables.scss deleted file mode 100644 index 769326182..000000000 --- a/samples/rest-notes-slate/slate/source/stylesheets/_variables.scss +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright 2008-2013 Concur Technologies, Inc. - -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. -*/ - - -//////////////////////////////////////////////////////////////////////////////// -// CUSTOMIZE SLATE -//////////////////////////////////////////////////////////////////////////////// -// Use these settings to help adjust the appearance of Slate - - -// BACKGROUND COLORS -//////////////////// -$nav-bg: #2E3336 !default; -$examples-bg: #2E3336 !default; -$code-bg: #1E2224 !default; -$code-annotation-bg: #191D1F !default; -$nav-subitem-bg: #1E2224 !default; -$nav-active-bg: #0F75D4 !default; -$nav-active-parent-bg: #1E2224 !default; // parent links of the current section -$lang-select-border: #000 !default; -$lang-select-bg: #1E2224 !default; -$lang-select-active-bg: $examples-bg !default; // feel free to change this to blue or something -$lang-select-pressed-bg: #111 !default; // color of language tab bg when mouse is pressed -$main-bg: #F3F7F9 !default; -$aside-notice-bg: #8fbcd4 !default; -$aside-warning-bg: #c97a7e !default; -$aside-success-bg: #6ac174 !default; -$search-notice-bg: #c97a7e !default; - - -// TEXT COLORS -//////////////////// -$main-text: #333 !default; // main content text color -$nav-text: #fff !default; -$nav-active-text: #fff !default; -$nav-active-parent-text: #fff !default; // parent links of the current section -$lang-select-text: #fff !default; // color of unselected language tab text -$lang-select-active-text: #fff !default; // color of selected language tab text -$lang-select-pressed-text: #fff !default; // color of language tab text when mouse is pressed - - -// SIZES -//////////////////// -$nav-width: 230px !default; // width of the navbar -$examples-width: 50% !default; // portion of the screen taken up by code examples -$logo-margin: 0px !default; // margin below logo -$main-padding: 28px !default; // padding to left and right of content & examples -$nav-padding: 15px !default; // padding to left and right of navbar -$nav-v-padding: 10px !default; // padding used vertically around search boxes and results -$nav-indent: 10px !default; // extra padding for ToC subitems -$code-annotation-padding: 13px !default; // padding inside code annotations -$h1-margin-bottom: 21px !default; // padding under the largest header tags -$tablet-width: 930px !default; // min width before reverting to tablet size -$phone-width: $tablet-width - $nav-width !default; // min width before reverting to mobile size - - -// FONTS -//////////////////// -%default-font { - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; - font-size: 14px; -} - -%header-font { - @extend %default-font; - font-weight: bold; -} - -%code-font { - font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, serif; - font-size: 12px; - line-height: 1.5; -} - - -// OTHER -//////////////////// -$nav-footer-border-color: #666 !default; -$search-box-border-color: #666 !default; - - -//////////////////////////////////////////////////////////////////////////////// -// INTERNAL -//////////////////////////////////////////////////////////////////////////////// -// These settings are probably best left alone. - -%break-words { - word-break: break-all; - hyphens: auto; -} diff --git a/samples/rest-notes-slate/slate/source/stylesheets/print.css.scss b/samples/rest-notes-slate/slate/source/stylesheets/print.css.scss deleted file mode 100644 index aea88c306..000000000 --- a/samples/rest-notes-slate/slate/source/stylesheets/print.css.scss +++ /dev/null @@ -1,153 +0,0 @@ -@charset "utf-8"; -@import 'normalize'; -@import 'variables'; -@import 'icon-font'; - -/* -Copyright 2008-2013 Concur Technologies, Inc. - -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. -*/ - -$print-color: #999; -$print-color-light: #ccc; -$print-font-size: 12px; - -body { - @extend %default-font; -} - -.tocify, .toc-footer, .lang-selector, .search, #nav-button { - display: none; -} - -.tocify-wrapper>img { - margin: 0 auto; - display: block; -} - -.content { - font-size: 12px; - - pre, code { - @extend %code-font; - @extend %break-words; - border: 1px solid $print-color; - border-radius: 5px; - font-size: 0.8em; - } - - pre { - code { - border: 0; - } - } - - pre { - padding: 1.3em; - } - - code { - padding: 0.2em; - } - - table { - border: 1px solid $print-color; - tr { - border-bottom: 1px solid $print-color; - } - td,th { - padding: 0.7em; - } - } - - p { - line-height: 1.5; - } - - a { - text-decoration: none; - color: #000; - } - - h1 { - @extend %header-font; - font-size: 2.5em; - padding-top: 0.5em; - padding-bottom: 0.5em; - margin-top: 1em; - margin-bottom: $h1-margin-bottom; - border: 2px solid $print-color-light; - border-width: 2px 0; - text-align: center; - } - - h2 { - @extend %header-font; - font-size: 1.8em; - margin-top: 2em; - border-top: 2px solid $print-color-light; - padding-top: 0.8em; - } - - h1+h2, h1+div+h2 { - border-top: none; - padding-top: 0; - margin-top: 0; - } - - h3, h4 { - @extend %header-font; - font-size: 0.8em; - margin-top: 1.5em; - margin-bottom: 0.8em; - text-transform: uppercase; - } - - h5, h6 { - text-transform: uppercase; - } - - aside { - padding: 1em; - border: 1px solid $print-color-light; - border-radius: 5px; - margin-top: 1.5em; - margin-bottom: 1.5em; - line-height: 1.6; - } - - aside:before { - vertical-align: middle; - padding-right: 0.5em; - font-size: 14px; - } - - aside.notice:before { - @extend %icon-info-sign; - } - - aside.warning:before { - @extend %icon-exclamation-sign; - } - - aside.success:before { - @extend %icon-ok-sign; - } -} - -.copy-clipboard { - @media print { - display: none - } -} diff --git a/samples/rest-notes-slate/slate/source/stylesheets/screen.css.scss b/samples/rest-notes-slate/slate/source/stylesheets/screen.css.scss deleted file mode 100644 index 70e3527df..000000000 --- a/samples/rest-notes-slate/slate/source/stylesheets/screen.css.scss +++ /dev/null @@ -1,633 +0,0 @@ -@charset "utf-8"; -@import 'normalize'; -@import 'variables'; -@import 'icon-font'; -// @import 'rtl'; // uncomment to switch to RTL format - -/* -Copyright 2008-2013 Concur Technologies, Inc. - -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. -*/ - -//////////////////////////////////////////////////////////////////////////////// -// GENERAL STUFF -//////////////////////////////////////////////////////////////////////////////// - -html, body { - color: $main-text; - padding: 0; - margin: 0; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - @extend %default-font; - background-color: $main-bg; - height: 100%; - -webkit-text-size-adjust: none; /* Never autoresize text */ -} - -//////////////////////////////////////////////////////////////////////////////// -// TABLE OF CONTENTS -//////////////////////////////////////////////////////////////////////////////// - -#toc > ul > li > a > span { - float: right; - background-color: #2484FF; - border-radius: 40px; - width: 20px; -} - -.toc-wrapper { - transition: left 0.3s ease-in-out; - - overflow-y: auto; - overflow-x: hidden; - position: fixed; - z-index: 30; - top: 0; - left: 0; - bottom: 0; - width: $nav-width; - background-color: $nav-bg; - font-size: 13px; - font-weight: bold; - - // language selector for mobile devices - .lang-selector { - display: none; - a { - padding-top: 0.5em; - padding-bottom: 0.5em; - } - } - - // This is the logo at the top of the ToC - .logo { - display: block; - max-width: 100%; - margin-bottom: $logo-margin; - } - - &>.search { - position: relative; - - input { - background: $nav-bg; - border-width: 0 0 1px 0; - border-color: $search-box-border-color; - padding: 6px 0 6px 20px; - box-sizing: border-box; - margin: $nav-v-padding $nav-padding; - width: $nav-width - ($nav-padding*2); - outline: none; - color: $nav-text; - border-radius: 0; /* ios has a default border radius */ - } - - &:before { - position: absolute; - top: 17px; - left: $nav-padding; - color: $nav-text; - @extend %icon-search; - } - } - - .search-results { - margin-top: 0; - box-sizing: border-box; - height: 0; - overflow-y: auto; - overflow-x: hidden; - transition-property: height, margin; - transition-duration: 180ms; - transition-timing-function: ease-in-out; - background: $nav-subitem-bg; - &.visible { - height: 30%; - margin-bottom: 1em; - } - - li { - margin: 1em $nav-padding; - line-height: 1; - } - - a { - color: $nav-text; - text-decoration: none; - - &:hover { - text-decoration: underline; - } - } - } - - - // The Table of Contents is composed of multiple nested - // unordered lists. These styles remove the default - // styling of an unordered list because it is ugly. - ul, li { - list-style: none; - margin: 0; - padding: 0; - line-height: 28px; - } - - li { - color: $nav-text; - transition-property: background; - transition-timing-function: linear; - transition-duration: 200ms; - } - - // This is the currently selected ToC entry - .toc-link.active { - background-color: $nav-active-bg; - color: $nav-active-text; - } - - // this is parent links of the currently selected ToC entry - .toc-link.active-parent { - background-color: $nav-active-parent-bg; - color: $nav-active-parent-text; - } - - .toc-list-h2 { - display: none; - background-color: $nav-subitem-bg; - font-weight: 500; - } - - .toc-h2 { - padding-left: $nav-padding + $nav-indent; - font-size: 12px; - } - - .toc-footer { - padding: 1em 0; - margin-top: 1em; - border-top: 1px dashed $nav-footer-border-color; - - li,a { - color: $nav-text; - text-decoration: none; - } - - a:hover { - text-decoration: underline; - } - - li { - font-size: 0.8em; - line-height: 1.7; - text-decoration: none; - } - } -} - -.toc-link, .toc-footer li { - padding: 0 $nav-padding 0 $nav-padding; - display: block; - overflow-x: hidden; - white-space: nowrap; - text-overflow: ellipsis; - text-decoration: none; - color: $nav-text; - transition-property: background; - transition-timing-function: linear; - transition-duration: 130ms; -} - -// button to show navigation on mobile devices -#nav-button { - span { - display: block; - $side-pad: $main-padding / 2 - 8px; - padding: $side-pad $side-pad $side-pad; - background-color: rgba($main-bg, 0.7); - transform-origin: 0 0; - transform: rotate(-90deg) translate(-100%, 0); - border-radius: 0 0 0 5px; - } - padding: 0 1.5em 5em 0; // increase touch size area - display: none; - position: fixed; - top: 0; - left: 0; - z-index: 100; - color: #000; - text-decoration: none; - font-weight: bold; - opacity: 0.7; - line-height: 16px; - img { - height: 16px; - vertical-align: bottom; - } - - transition: left 0.3s ease-in-out; - - &:hover { opacity: 1; } - &.open {left: $nav-width} -} - - -//////////////////////////////////////////////////////////////////////////////// -// PAGE LAYOUT AND CODE SAMPLE BACKGROUND -//////////////////////////////////////////////////////////////////////////////// - -.page-wrapper { - margin-left: $nav-width; - position: relative; - z-index: 10; - background-color: $main-bg; - min-height: 100%; - - padding-bottom: 1px; // prevent margin overflow - - // The dark box is what gives the code samples their dark background. - // It sits essentially under the actual content block, which has a - // transparent background. - // I know, it's hackish, but it's the simplist way to make the left - // half of the content always this background color. - .dark-box { - width: $examples-width; - background-color: $examples-bg; - position: absolute; - right: 0; - top: 0; - bottom: 0; - } - - .lang-selector { - position: fixed; - z-index: 50; - border-bottom: 5px solid $lang-select-active-bg; - } -} - -.lang-selector { - display: flex; - background-color: $lang-select-bg; - width: 100%; - font-weight: bold; - overflow-x: auto; - a { - display: inline; - color: $lang-select-text; - text-decoration: none; - padding: 0 10px; - line-height: 30px; - outline: 0; - - &:active, &:focus { - background-color: $lang-select-pressed-bg; - color: $lang-select-pressed-text; - } - - &.active { - background-color: $lang-select-active-bg; - color: $lang-select-active-text; - } - } - - &:after { - content: ''; - clear: both; - display: block; - } -} - -//////////////////////////////////////////////////////////////////////////////// -// CONTENT STYLES -//////////////////////////////////////////////////////////////////////////////// -// This is all the stuff with the light background in the left half of the page - -.content { - // fixes webkit rendering bug for some: see #538 - -webkit-transform: translateZ(0); - // to place content above the dark box - position: relative; - z-index: 30; - - &:after { - content: ''; - display: block; - clear: both; - } - - &>h1, &>h2, &>h3, &>h4, &>h5, &>h6, &>p, &>table, &>ul, &>ol, &>aside, &>dl { - margin-right: $examples-width; - padding: 0 $main-padding; - box-sizing: border-box; - display: block; - - @extend %left-col; - } - - &>ul, &>ol { - padding-left: $main-padding + 15px; - } - - // the div is the tocify hidden div for placeholding stuff - &>h1, &>h2, &>div { - clear:both; - } - - h1 { - @extend %header-font; - font-size: 25px; - padding-top: 0.5em; - padding-bottom: 0.5em; - margin-bottom: $h1-margin-bottom; - margin-top: 2em; - border-top: 1px solid #ccc; - border-bottom: 1px solid #ccc; - background-color: #fdfdfd; - } - - h1:first-child, div:first-child + h1 { - border-top-width: 0; - margin-top: 0; - } - - h2 { - @extend %header-font; - font-size: 19px; - margin-top: 4em; - margin-bottom: 0; - border-top: 1px solid #ccc; - padding-top: 1.2em; - padding-bottom: 1.2em; - background-image: linear-gradient(to bottom, rgba(#fff, 0.2), rgba(#fff, 0)); - } - - // h2s right after h1s should bump right up - // against the h1s. - h1 + h2, h1 + div + h2 { - margin-top: $h1-margin-bottom * -1; - border-top: none; - } - - h3, h4, h5, h6 { - @extend %header-font; - font-size: 15px; - margin-top: 2.5em; - margin-bottom: 0.8em; - } - - h4, h5, h6 { - font-size: 10px; - } - - hr { - margin: 2em 0; - border-top: 2px solid $examples-bg; - border-bottom: 2px solid $main-bg; - } - - table { - margin-bottom: 1em; - overflow: auto; - th,td { - text-align: left; - vertical-align: top; - line-height: 1.6; - code { - white-space: nowrap; - } - } - - th { - padding: 5px 10px; - border-bottom: 1px solid #ccc; - vertical-align: bottom; - } - - td { - padding: 10px; - } - - tr:last-child { - border-bottom: 1px solid #ccc; - } - - tr:nth-child(odd)>td { - background-color: lighten($main-bg,4.2%); - } - - tr:nth-child(even)>td { - background-color: lighten($main-bg,2.4%); - } - } - - dt { - font-weight: bold; - } - - dd { - margin-left: 15px; - } - - p, li, dt, dd { - line-height: 1.6; - margin-top: 0; - } - - img { - max-width: 100%; - } - - code { - background-color: rgba(0,0,0,0.05); - padding: 3px; - border-radius: 3px; - @extend %break-words; - @extend %code-font; - } - - pre>code { - background-color: transparent; - padding: 0; - } - - aside { - padding-top: 1em; - padding-bottom: 1em; - margin-top: 1.5em; - margin-bottom: 1.5em; - background: $aside-notice-bg; - line-height: 1.6; - - &.warning { - background-color: $aside-warning-bg; - } - - &.success { - background-color: $aside-success-bg; - } - } - - aside:before { - vertical-align: middle; - padding-right: 0.5em; - font-size: 14px; - } - - aside.notice:before { - @extend %icon-info-sign; - } - - aside.warning:before { - @extend %icon-exclamation-sign; - } - - aside.success:before { - @extend %icon-ok-sign; - } - - .search-highlight { - padding: 2px; - margin: -3px; - border-radius: 4px; - border: 1px solid #F7E633; - background: linear-gradient(to top left, #F7E633 0%, #F1D32F 100%); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// CODE SAMPLE STYLES -//////////////////////////////////////////////////////////////////////////////// -// This is all the stuff that appears in the right half of the page - -.content { - &>div.highlight { - clear:none; - } - - pre, blockquote { - background-color: $code-bg; - color: #fff; - - margin: 0; - width: $examples-width; - - float:right; - clear:right; - - box-sizing: border-box; - - @extend %right-col; - - &>p { margin: 0; } - - a { - color: #fff; - text-decoration: none; - border-bottom: dashed 1px #ccc; - } - } - - pre { - @extend %code-font; - padding-top: 2em; - padding-bottom: 2em; - padding: 2em $main-padding; - } - - blockquote { - &>p { - background-color: $code-annotation-bg; - padding: $code-annotation-padding 2em; - color: #eee; - } - } -} - -//////////////////////////////////////////////////////////////////////////////// -// RESPONSIVE DESIGN -//////////////////////////////////////////////////////////////////////////////// -// These are the styles for phones and tablets -// There are also a couple styles disperesed - -@media (max-width: $tablet-width) { - .toc-wrapper { - left: -$nav-width; - - &.open { - left: 0; - } - } - - .page-wrapper { - margin-left: 0; - } - - #nav-button { - display: block; - } - - .toc-link { - padding-top: 0.3em; - padding-bottom: 0.3em; - } -} - -@media (max-width: $phone-width) { - .dark-box { - display: none; - } - - %left-col { - margin-right: 0; - } - - .toc-wrapper .lang-selector { - display: block; - } - - .page-wrapper .lang-selector { - display: none; - } - - %right-col { - width: auto; - float: none; - } - - %right-col + %left-col { - margin-top: $main-padding; - } -} - -.highlight .c, .highlight .cm, .highlight .c1, .highlight .cs { - color: #909090; -} - -.highlight, .highlight .w { - background-color: $code-bg; -} - -.copy-clipboard { - float: right; - fill: #9DAAB6; - cursor: pointer; - opacity: 0.4; - height: 18px; - width: 18px; -} - -.copy-clipboard:hover { - opacity: 0.8; -} diff --git a/samples/rest-notes-slate/src/main/java/com/example/notes/Note.java b/samples/rest-notes-slate/src/main/java/com/example/notes/Note.java deleted file mode 100644 index 53104ede7..000000000 --- a/samples/rest-notes-slate/src/main/java/com/example/notes/Note.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -@Entity -public class Note { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String title; - - private String body; - - @ManyToMany - private List tags; - - @JsonIgnore - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } -} diff --git a/samples/rest-notes-slate/src/main/java/com/example/notes/NoteRepository.java b/samples/rest-notes-slate/src/main/java/com/example/notes/NoteRepository.java deleted file mode 100644 index b7a26a94b..000000000 --- a/samples/rest-notes-slate/src/main/java/com/example/notes/NoteRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import org.springframework.data.repository.CrudRepository; - -public interface NoteRepository extends CrudRepository { - -} diff --git a/samples/rest-notes-slate/src/main/java/com/example/notes/RestNotesSlate.java b/samples/rest-notes-slate/src/main/java/com/example/notes/RestNotesSlate.java deleted file mode 100644 index e20e4feca..000000000 --- a/samples/rest-notes-slate/src/main/java/com/example/notes/RestNotesSlate.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class RestNotesSlate { - - public static void main(String[] args) { - SpringApplication.run(RestNotesSlate.class, args); - } - -} diff --git a/samples/rest-notes-slate/src/main/java/com/example/notes/Tag.java b/samples/rest-notes-slate/src/main/java/com/example/notes/Tag.java deleted file mode 100644 index 8bd834f98..000000000 --- a/samples/rest-notes-slate/src/main/java/com/example/notes/Tag.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2014 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.notes; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -@Entity -public class Tag { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String name; - - @ManyToMany(mappedBy = "tags") - private List notes; - - @JsonIgnore - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getNotes() { - return notes; - } - - public void setNotes(List notes) { - this.notes = notes; - } -} diff --git a/samples/rest-notes-slate/src/main/java/com/example/notes/TagRepository.java b/samples/rest-notes-slate/src/main/java/com/example/notes/TagRepository.java deleted file mode 100644 index 96ad37917..000000000 --- a/samples/rest-notes-slate/src/main/java/com/example/notes/TagRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2014 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.notes; - -import org.springframework.data.repository.CrudRepository; - -public interface TagRepository extends CrudRepository { - -} diff --git a/samples/rest-notes-slate/src/main/resources/application.properties b/samples/rest-notes-slate/src/main/resources/application.properties deleted file mode 100644 index 8e06a8284..000000000 --- a/samples/rest-notes-slate/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -spring.jackson.serialization.indent_output: true \ No newline at end of file diff --git a/samples/rest-notes-slate/src/test/java/com/example/notes/ApiDocumentation.java b/samples/rest-notes-slate/src/test/java/com/example/notes/ApiDocumentation.java deleted file mode 100644 index a84000934..000000000 --- a/samples/rest-notes-slate/src/test/java/com/example/notes/ApiDocumentation.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; -import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; -import static org.springframework.restdocs.templates.TemplateFormats.markdown; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.RequestDispatcher; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.hateoas.MediaTypes; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.restdocs.payload.JsonFieldType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class ApiDocumentation { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - @Autowired - private NoteRepository noteRepository; - - @Autowired - private TagRepository tagRepository; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @Before - public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation).snippets() - .withTemplateFormat(markdown())).build(); - } - - @Test - public void errorExample() throws Exception { - this.mockMvc - .perform(get("/error") - .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 400) - .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, - "/notes") - .requestAttr(RequestDispatcher.ERROR_MESSAGE, - "The tag 'http://localhost:8080/tags/123' does not exist")) - .andDo(print()).andExpect(status().isBadRequest()) - .andExpect(jsonPath("error", is("Bad Request"))) - .andExpect(jsonPath("timestamp", is(notNullValue()))) - .andExpect(jsonPath("status", is(400))) - .andExpect(jsonPath("path", is(notNullValue()))) - .andDo(document("error-example", - responseFields( - fieldWithPath("error").description("The HTTP error that occurred, e.g. `Bad Request`"), - fieldWithPath("path").description("The path to which the request was made"), - fieldWithPath("status").description("The HTTP status code, e.g. `400`"), - fieldWithPath("timestamp").description("The time, in milliseconds, at which the error occurred")))); - } - - @Test - public void indexExample() throws Exception { - this.mockMvc.perform(get("/")) - .andExpect(status().isOk()) - .andDo(document("index-example", - links( - linkWithRel("notes").description("The [Notes](#notes) resource"), - linkWithRel("tags").description("The [Tags](#tags) resource"), - linkWithRel("profile").description("The ALPS profile for the service")), - responseFields( - subsectionWithPath("_links").description("Links to other resources")))); - - } - - @Test - public void notesListExample() throws Exception { - this.noteRepository.deleteAll(); - - createNote("REST maturity model", - "https://martinfowler.com/articles/richardsonMaturityModel.html"); - createNote("Hypertext Application Language (HAL)", - "https://github.com/mikekelly/hal_specification"); - createNote("Application-Level Profile Semantics (ALPS)", "https://github.com/alps-io/spec"); - - this.mockMvc.perform(get("/notes")) - .andExpect(status().isOk()) - .andDo(document("notes-list-example", - responseFields( - subsectionWithPath("_embedded.notes").description("An array of [Note](#note) resources"), - subsectionWithPath("_links").description("Links to other resources")))); - } - - @Test - public void notesCreateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - note.put("tags", Arrays.asList(tagLocation)); - - this.mockMvc.perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(note))).andExpect( - status().isCreated()) - .andDo(document("notes-create-example", - requestFields( - fieldWithPath("title").description("The title of the note"), - fieldWithPath("body").description("The body of the note"), - fieldWithPath("tags").description("An array of [Tag](#tag) resource URIs")))); - } - - @Test - public void noteGetExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - note.put("tags", Arrays.asList(tagLocation)); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - this.mockMvc.perform(get(noteLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("title", is(note.get("title")))) - .andExpect(jsonPath("body", is(note.get("body")))) - .andExpect(jsonPath("_links.self.href", is(noteLocation))) - .andExpect(jsonPath("_links.tags", is(notNullValue()))) - .andDo(document("note-get-example", - links( - linkWithRel("self").description("Canonical link for this resource"), - linkWithRel("note").description("This note"), - linkWithRel("tags").description("This note's tags")), - responseFields( - fieldWithPath("title").description("The title of the note"), - fieldWithPath("body").description("The body of the note"), - subsectionWithPath("_links").description("Links to other resources")))); - } - - @Test - public void tagsListExample() throws Exception { - this.noteRepository.deleteAll(); - this.tagRepository.deleteAll(); - - createTag("REST"); - createTag("Hypermedia"); - createTag("HTTP"); - - this.mockMvc.perform(get("/tags")) - .andExpect(status().isOk()) - .andDo(document("tags-list-example", - responseFields( - subsectionWithPath("_embedded.tags").description("An array of [Tag](#tag) resources"), - subsectionWithPath("_links").description("Links to other resources")))); - } - - @Test - public void tagsCreateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - this.mockMvc.perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andDo(document("tags-create-example", - requestFields( - fieldWithPath("name").description("The name of the tag")))); - } - - @Test - public void noteUpdateExample() throws Exception { - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk()) - .andExpect(jsonPath("title", is(note.get("title")))) - .andExpect(jsonPath("body", is(note.get("body")))) - .andExpect(jsonPath("_links.self.href", is(noteLocation))) - .andExpect(jsonPath("_links.tags", is(notNullValue()))); - - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map noteUpdate = new HashMap(); - noteUpdate.put("tags", Arrays.asList(tagLocation)); - - this.mockMvc.perform( - patch(noteLocation).contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(noteUpdate))) - .andExpect(status().isNoContent()) - .andDo(document("note-update-example", - requestFields( - fieldWithPath("title").description("The title of the note").type(JsonFieldType.STRING).optional(), - fieldWithPath("body").description("The body of the note").type(JsonFieldType.STRING).optional(), - fieldWithPath("tags").description("An array of [tag](#tag) resource URIs").optional()))); - } - - @Test - public void tagGetExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - this.mockMvc.perform(get(tagLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("name", is(tag.get("name")))) - .andDo(document("tag-get-example", - links( - linkWithRel("self").description("Canonical link for this resource"), - linkWithRel("tag").description("This tag"), - linkWithRel("notes").description("The notes that have this tag")), - responseFields( - fieldWithPath("name").description("The name of the tag"), - subsectionWithPath("_links").description("Links to other resources")))); - } - - @Test - public void tagUpdateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map tagUpdate = new HashMap(); - tagUpdate.put("name", "RESTful"); - - this.mockMvc.perform( - patch(tagLocation).contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tagUpdate))) - .andExpect(status().isNoContent()) - .andDo(document("tag-update-example", - requestFields( - fieldWithPath("name").description("The name of the tag")))); - } - - private void createNote(String title, String body) { - Note note = new Note(); - note.setTitle(title); - note.setBody(body); - - this.noteRepository.save(note); - } - - private void createTag(String name) { - Tag tag = new Tag(); - tag.setName(name); - this.tagRepository.save(tag); - } -} diff --git a/samples/rest-notes-spring-data-rest/.mvn/wrapper/maven-wrapper.jar b/samples/rest-notes-spring-data-rest/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index c6feb8bb6..000000000 Binary files a/samples/rest-notes-spring-data-rest/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/samples/rest-notes-spring-data-rest/.mvn/wrapper/maven-wrapper.properties b/samples/rest-notes-spring-data-rest/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index eb9194764..000000000 --- a/samples/rest-notes-spring-data-rest/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/samples/rest-notes-spring-data-rest/mvnw b/samples/rest-notes-spring-data-rest/mvnw deleted file mode 100755 index 63fcc8f0f..000000000 --- a/samples/rest-notes-spring-data-rest/mvnw +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# 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 -# -# 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CMD_LINE_ARGS - diff --git a/samples/rest-notes-spring-data-rest/mvnw.cmd b/samples/rest-notes-spring-data-rest/mvnw.cmd deleted file mode 100644 index 66e928bd1..000000000 --- a/samples/rest-notes-spring-data-rest/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM https://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/samples/rest-notes-spring-data-rest/pom.xml b/samples/rest-notes-spring-data-rest/pom.xml deleted file mode 100644 index 2f95e9eac..000000000 --- a/samples/rest-notes-spring-data-rest/pom.xml +++ /dev/null @@ -1,175 +0,0 @@ - - - 4.0.0 - - com.example - rest-notes-spring-data-rest - 0.0.1-SNAPSHOT - jar - - - org.springframework.boot - spring-boot-starter-parent - 2.6.2 - - - - - UTF-8 - 1.8 - 2.0.7.BUILD-SNAPSHOT - 2.0.206 - - - - - org.springframework.boot - spring-boot-starter-data-rest - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - com.h2database - h2 - runtime - - - - org.junit.vintage - junit-vintage-engine - test - - - org.hamcrest - hamcrest-core - - - - - org.springframework.boot - spring-boot-starter-test - test - - - com.jayway.jsonpath - json-path - test - - - org.springframework.restdocs - spring-restdocs-mockmvc - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*Documentation.java - - - - - org.asciidoctor - asciidoctor-maven-plugin - 1.5.8 - - - generate-docs - prepare-package - - process-asciidoc - - - html - book - - true - - DEBUG - - - - - - - - org.springframework.restdocs - spring-restdocs-asciidoctor - ${spring-restdocs.version} - - - - - maven-resources-plugin - - - copy-resources - prepare-package - - copy-resources - - - ${project.build.outputDirectory}/static/docs - - - ${project.build.directory}/generated-docs - - - - - - - - - - - - spring-milestones - Spring milestones - https://repo.spring.io/milestone - - false - - - - spring-snapshots - Spring snapshots - https://repo.spring.io/snapshot - - true - - - - - - spring-milestones - Spring milestones - https://repo.spring.io/milestone - - false - - - - spring-snapshots - Spring snapshots - https://repo.spring.io/snapshot - - true - - - - - diff --git a/samples/rest-notes-spring-data-rest/src/main/asciidoc/api-guide.adoc b/samples/rest-notes-spring-data-rest/src/main/asciidoc/api-guide.adoc deleted file mode 100644 index 8cb817847..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/asciidoc/api-guide.adoc +++ /dev/null @@ -1,228 +0,0 @@ -= RESTful Notes API Guide -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs -:toc: left -:toclevels: 4 -:sectlinks: -:operation-curl-request-title: Example request -:operation-http-response-title: Example response - -[[overview]] -= Overview - -[[overview_http_verbs]] -== HTTP verbs - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP verbs. - -|=== -| Verb | Usage - -| `GET` -| Used to retrieve a resource - -| `POST` -| Used to create a new resource - -| `PATCH` -| Used to update an existing resource, including partial updates - -| `DELETE` -| Used to delete an existing resource -|=== - -[[overview_http_status_codes]] -== HTTP status codes - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP status codes. - -|=== -| Status code | Usage - -| `200 OK` -| The request completed successfully - -| `201 Created` -| A new resource has been created successfully. The resource's URI is available from the response's -`Location` header - -| `204 No Content` -| An update to an existing resource has been applied successfully - -| `400 Bad Request` -| The request was malformed. The response body will include an error providing further information - -| `404 Not Found` -| The requested resource did not exist -|=== - -[[overview_errors]] -== Errors - -Whenever an error response (status code >= 400) is returned, the body will contain a JSON object -that describes the problem. The error object has the following structure: - -include::{snippets}/error-example/response-fields.adoc[] - -For example, a request that attempts to apply a non-existent tag to a note will produce a -`400 Bad Request` response: - -include::{snippets}/error-example/http-response.adoc[] - -[[overview_hypermedia]] -== Hypermedia - -RESTful Notes uses hypermedia and resources include links to other resources in their -responses. Responses are in https://github.com/mikekelly/hal_specification[Hypertext -Application Language (HAL)] format. Links can be found beneath the `_links` key. Users of -the API should not create URIs themselves, instead they should use the above-described -links to navigate from resource to resource. - -[[resources]] -= Resources - - - -[[resources_index]] -== Index - -The index provides the entry point into the service. - - - -[[resources_index_access]] -=== Accessing the index - -A `GET` request is used to access the index - -operation::index-example[snippets='response-fields,http-response,links'] - - - -[[resources_notes]] -== Notes - -The Notes resources is used to create and list notes - - - -[[resources_notes_list]] -=== Listing notes - -A `GET` request will list all of the service's notes. - -operation::notes-list-example[snippets='response-fields,curl-request,http-response,links'] - - - -[[resources_notes_create]] -=== Creating a note - -A `POST` request is used to create a note. - -operation::notes-create-example[snippets='request-fields,curl-request,http-response'] - - - -[[resources_tags]] -== Tags - -The Tags resource is used to create and list tags. - - - -[[resources_tags_list]] -=== Listing tags - -A `GET` request will list all of the service's tags. - -operation::tags-list-example[snippets='response-fields,curl-request,http-response,links'] - - - -[[resources_tags_create]] -=== Creating a tag - -A `POST` request is used to create a note - -operation::tags-create-example[snippets='request-fields,curl-request,http-response'] - - - -[[resources_note]] -== Note - -The Note resource is used to retrieve, update, and delete individual notes - - - -[[resources_note_links]] -=== Links - -include::{snippets}/note-get-example/links.adoc[] - - - -[[resources_note_retrieve]] -=== Retrieve a note - -A `GET` request will retrieve the details of a note - -operation::note-get-example[snippets='response-fields,curl-request,http-response'] - - - -[[resources_note_update]] -=== Update a note - -A `PATCH` request is used to update a note - -==== Request structure - -include::{snippets}/note-update-example/request-fields.adoc[] - -To leave an attribute of a note unchanged, any of the above may be omitted from the request. - -==== Example request - -include::{snippets}/note-update-example/curl-request.adoc[] - -==== Example response - -include::{snippets}/note-update-example/http-response.adoc[] - - - -[[resources_tag]] -== Tag - -The Tag resource is used to retrieve, update, and delete individual tags - - - -[[resources_tag_links]] -=== Links - -include::{snippets}/tag-get-example/links.adoc[] - - - -[[resources_tag_retrieve]] -=== Retrieve a tag - -A `GET` request will retrieve the details of a tag - -operation::tag-get-example[snippets='response-fields,curl-request,http-response'] - - - -[[resources_tag_update]] -=== Update a tag - -A `PATCH` request is used to update a tag - -operation::tag-update-example[snippets='request-fields,curl-request,http-response'] diff --git a/samples/rest-notes-spring-data-rest/src/main/asciidoc/getting-started-guide.adoc b/samples/rest-notes-spring-data-rest/src/main/asciidoc/getting-started-guide.adoc deleted file mode 100644 index b9ab9136c..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/asciidoc/getting-started-guide.adoc +++ /dev/null @@ -1,175 +0,0 @@ -= RESTful Notes Getting Started Guide -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs -:toc: left -:toclevels: 4 -:sectlinks: - -[[introduction]] -= Introduction - -RESTful Notes is a RESTful web service for creating and storing notes. It uses hypermedia -to describe the relationships between resources and to allow navigation between them. - - - -[[getting_started_running_the_service]] -== Running the service -RESTful Notes is written using https://projects.spring.io/spring-boot[Spring Boot] which -makes it easy to get it up and running so that you can start exploring the REST API. - -The first step is to clone the Git repository: - -[source,bash] ----- -$ git clone https://github.com/spring-projects/spring-restdocs ----- - -Once the clone is complete, you're ready to get the service up and running: - -[source,bash] ----- -$ cd samples/rest-notes-spring-data-rest -$ ./mvnw clean package -$ java -jar target/*.jar ----- - -You can check that the service is up and running by executing a simple request using -cURL: - -include::{snippets}/index/1/curl-request.adoc[] - -This request should yield the following response in the -https://github.com/mikekelly/hal_specification[Hypertext Application Language (HAL)] -format: - -include::{snippets}/index/1/http-response.adoc[] - -Note the `_links` in the JSON response. They are key to navigating the API. - - - -[[getting_started_creating_a_note]] -== Creating a note -Now that you've started the service and verified that it works, the next step is to use -it to create a new note. As you saw above, the URI for working with notes is included as -a link when you perform a `GET` request against the root of the service: - -include::{snippets}/index/1/http-response.adoc[] - -To create a note, you need to execute a `POST` request to this URI including a JSON -payload containing the title and body of the note: - -include::{snippets}/creating-a-note/1/curl-request.adoc[] - -The response from this request should have a status code of `201 Created` and contain a -`Location` header whose value is the URI of the newly created note: - -include::{snippets}/creating-a-note/1/http-response.adoc[] - -To work with the newly created note you use the URI in the `Location` header. For example, -you can access the note's details by performing a `GET` request: - -include::{snippets}/creating-a-note/2/curl-request.adoc[] - -This request will produce a response with the note's details in its body: - -include::{snippets}/creating-a-note/2/http-response.adoc[] - -Note the `tags` link which we'll make use of later. - - - -[[getting_started_creating_a_tag]] -== Creating a tag -To make a note easier to find, it can be associated with any number of tags. To be able -to tag a note, you must first create the tag. - -Referring back to the response for the service's index, the URI for working with tags is -include as a link: - -include::{snippets}/index/1/http-response.adoc[] - -To create a tag you need to execute a `POST` request to this URI, including a JSON -payload containing the name of the tag: - -include::{snippets}/creating-a-note/3/curl-request.adoc[] - -The response from this request should have a status code of `201 Created` and contain a -`Location` header whose value is the URI of the newly created tag: - -include::{snippets}/creating-a-note/3/http-response.adoc[] - -To work with the newly created tag you use the URI in the `Location` header. For example -you can access the tag's details by performing a `GET` request: - -include::{snippets}/creating-a-note/4/curl-request.adoc[] - -This request will produce a response with the tag's details in its body: - -include::{snippets}/creating-a-note/4/http-response.adoc[] - - - -[[getting_started_tagging_a_note]] -== Tagging a note -A tag isn't particularly useful until it's been associated with one or more notes. There -are two ways to tag a note: when the note is first created or by updating an existing -note. We'll look at both of these in turn. - - - -[[getting_started_tagging_a_note_creating]] -=== Creating a tagged note -The process is largely the same as we saw before, but this time, in addition to providing -a title and body for the note, we'll also provide the tag that we want to be associated -with it. - -Once again we execute a `POST` request. However, this time, in an array named tags, we -include the URI of the tag we just created: - -include::{snippets}/creating-a-note/5/curl-request.adoc[] - -Once again, the response's `Location` header tells us the URI of the newly created note: - -include::{snippets}/creating-a-note/5/http-response.adoc[] - -As before, a `GET` request executed against this URI will retrieve the note's details: - -include::{snippets}/creating-a-note/6/curl-request.adoc[] -include::{snippets}/creating-a-note/6/http-response.adoc[] - -To verify that the tag has been associated with the note, we can perform a `GET` request -against the URI from the `tags` link: - -include::{snippets}/creating-a-note/7/curl-request.adoc[] - -The response embeds information about the tag that we've just associated with the note: - -include::{snippets}/creating-a-note/7/http-response.adoc[] - - - -[[getting_started_tagging_a_note_existing]] -=== Tagging an existing note -An existing note can be tagged by executing a `PATCH` request against the note's URI with -a body that contains the array of tags to be associated with the note. We'll used the -URI of the untagged note that we created earlier: - -include::{snippets}/creating-a-note/8/curl-request.adoc[] - -This request should produce a `204 No Content` response: - -include::{snippets}/creating-a-note/8/http-response.adoc[] - -When we first created this note, we noted the tags link included in its details: - -include::{snippets}/creating-a-note/2/http-response.adoc[] - -We can use that link now and execute a `GET` request to see that the note now has a -single tag: - -include::{snippets}/creating-a-note/9/curl-request.adoc[] -include::{snippets}/creating-a-note/9/http-response.adoc[] diff --git a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/Note.java b/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/Note.java deleted file mode 100644 index 5160682a3..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/Note.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2014 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.notes; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -@Entity -public class Note { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String title; - - private String body; - - @ManyToMany - private List tags; - - @JsonIgnore - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } -} diff --git a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/NoteRepository.java b/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/NoteRepository.java deleted file mode 100644 index ba6dd5fb3..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/NoteRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2014 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.notes; - -import org.springframework.data.repository.CrudRepository; - -public interface NoteRepository extends CrudRepository { - -} diff --git a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/RestNotesSpringDataRest.java b/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/RestNotesSpringDataRest.java deleted file mode 100644 index 21195fd55..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/RestNotesSpringDataRest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class RestNotesSpringDataRest { - - public static void main(String[] args) { - SpringApplication.run(RestNotesSpringDataRest.class, args); - } - -} diff --git a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/Tag.java b/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/Tag.java deleted file mode 100644 index 8bd834f98..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/Tag.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2014 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.notes; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -@Entity -public class Tag { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String name; - - @ManyToMany(mappedBy = "tags") - private List notes; - - @JsonIgnore - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getNotes() { - return notes; - } - - public void setNotes(List notes) { - this.notes = notes; - } -} diff --git a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/TagRepository.java b/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/TagRepository.java deleted file mode 100644 index 96ad37917..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/java/com/example/notes/TagRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2014 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.notes; - -import org.springframework.data.repository.CrudRepository; - -public interface TagRepository extends CrudRepository { - -} diff --git a/samples/rest-notes-spring-data-rest/src/main/resources/application.properties b/samples/rest-notes-spring-data-rest/src/main/resources/application.properties deleted file mode 100644 index 8e06a8284..000000000 --- a/samples/rest-notes-spring-data-rest/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -spring.jackson.serialization.indent_output: true \ No newline at end of file diff --git a/samples/rest-notes-spring-data-rest/src/test/java/com/example/notes/ApiDocumentation.java b/samples/rest-notes-spring-data-rest/src/test/java/com/example/notes/ApiDocumentation.java deleted file mode 100644 index 1421acb16..000000000 --- a/samples/rest-notes-spring-data-rest/src/test/java/com/example/notes/ApiDocumentation.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright 2014-2022 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.notes; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; -import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.RequestDispatcher; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.hateoas.MediaTypes; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.restdocs.payload.JsonFieldType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class ApiDocumentation { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - @Autowired - private NoteRepository noteRepository; - - @Autowired - private TagRepository tagRepository; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @Before - public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - } - - @Test - public void errorExample() throws Exception { - this.mockMvc - .perform(get("/error") - .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 400) - .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, - "/notes") - .requestAttr(RequestDispatcher.ERROR_MESSAGE, - "The tag 'http://localhost:8080/tags/123' does not exist")) - .andDo(print()).andExpect(status().isBadRequest()) - .andExpect(jsonPath("error", is("Bad Request"))) - .andExpect(jsonPath("timestamp", is(notNullValue()))) - .andExpect(jsonPath("status", is(400))) - .andExpect(jsonPath("path", is(notNullValue()))) - .andDo(document("error-example", - responseFields( - fieldWithPath("error").description("The HTTP error that occurred, e.g. `Bad Request`"), - fieldWithPath("path").description("The path to which the request was made"), - fieldWithPath("status").description("The HTTP status code, e.g. `400`"), - fieldWithPath("timestamp").description("The time, in milliseconds, at which the error occurred")))); - } - - @Test - public void indexExample() throws Exception { - this.mockMvc.perform(get("/")) - .andExpect(status().isOk()) - .andDo(document("index-example", - links( - linkWithRel("notes").description("The <>"), - linkWithRel("tags").description("The <>"), - linkWithRel("profile").description("The ALPS profile for the service")), - responseFields( - subsectionWithPath("_links").description("<> to other resources")))); - - } - - @Test - public void notesListExample() throws Exception { - this.noteRepository.deleteAll(); - - createNote("REST maturity model", - "https://martinfowler.com/articles/richardsonMaturityModel.html"); - createNote("Hypertext Application Language (HAL)", - "https://github.com/mikekelly/hal_specification"); - createNote("Application-Level Profile Semantics (ALPS)", "https://github.com/alps-io/spec"); - - this.mockMvc.perform(get("/notes")) - .andExpect(status().isOk()) - .andDo(document("notes-list-example", - links( - linkWithRel("self").description("Canonical link for this resource"), - linkWithRel("profile").description("The ALPS profile for this resource")), - responseFields( - subsectionWithPath("_embedded.notes").description("An array of <>"), - subsectionWithPath("_links").description("<> to other resources")))); - } - - @Test - public void notesCreateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - note.put("tags", Arrays.asList(tagLocation)); - - this.mockMvc.perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(note))).andExpect( - status().isCreated()) - .andDo(document("notes-create-example", - requestFields( - fieldWithPath("title").description("The title of the note"), - fieldWithPath("body").description("The body of the note"), - fieldWithPath("tags").description("An array of tag resource URIs")))); - } - - @Test - public void noteGetExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - note.put("tags", Arrays.asList(tagLocation)); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - this.mockMvc.perform(get(noteLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("title", is(note.get("title")))) - .andExpect(jsonPath("body", is(note.get("body")))) - .andExpect(jsonPath("_links.self.href", is(noteLocation))) - .andExpect(jsonPath("_links.tags", is(notNullValue()))) - .andDo(print()) - .andDo(document("note-get-example", - links( - linkWithRel("self").description("Canonical link for this <>"), - linkWithRel("note").description("This <>"), - linkWithRel("tags").description("This note's tags")), - responseFields( - fieldWithPath("title").description("The title of the note"), - fieldWithPath("body").description("The body of the note"), - subsectionWithPath("_links").description("<> to other resources")))); - } - - @Test - public void tagsListExample() throws Exception { - this.noteRepository.deleteAll(); - this.tagRepository.deleteAll(); - - createTag("REST"); - createTag("Hypermedia"); - createTag("HTTP"); - - this.mockMvc.perform(get("/tags")) - .andExpect(status().isOk()) - .andDo(document("tags-list-example", - links( - linkWithRel("self").description("Canonical link for this resource"), - linkWithRel("profile").description("The ALPS profile for this resource")), - responseFields( - subsectionWithPath("_embedded.tags").description("An array of <>"), - subsectionWithPath("_links").description("<> to other resources")))); - } - - @Test - public void tagsCreateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - this.mockMvc.perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andDo(document("tags-create-example", - requestFields( - fieldWithPath("name").description("The name of the tag")))); - } - - @Test - public void noteUpdateExample() throws Exception { - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - this.mockMvc.perform(get(noteLocation)).andExpect(status().isOk()) - .andExpect(jsonPath("title", is(note.get("title")))) - .andExpect(jsonPath("body", is(note.get("body")))) - .andExpect(jsonPath("_links.self.href", is(noteLocation))) - .andExpect(jsonPath("_links.tags", is(notNullValue()))); - - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map noteUpdate = new HashMap(); - noteUpdate.put("tags", Arrays.asList(tagLocation)); - - this.mockMvc.perform( - patch(noteLocation).contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(noteUpdate))) - .andExpect(status().isNoContent()) - .andDo(document("note-update-example", - requestFields( - fieldWithPath("title").description("The title of the note").type(JsonFieldType.STRING).optional(), - fieldWithPath("body").description("The body of the note").type(JsonFieldType.STRING).optional(), - fieldWithPath("tags").description("An array of tag resource URIs").optional()))); - } - - @Test - public void tagGetExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - this.mockMvc.perform(get(tagLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("name", is(tag.get("name")))) - .andDo(document("tag-get-example", - links( - linkWithRel("self").description("Canonical link for this <>"), - linkWithRel("tag").description("This <>"), - linkWithRel("notes").description("The notes that have this tag")), - responseFields( - fieldWithPath("name").description("The name of the tag"), - subsectionWithPath("_links").description("<> to other resources")))); - } - - @Test - public void tagUpdateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()).andReturn().getResponse() - .getHeader("Location"); - - Map tagUpdate = new HashMap(); - tagUpdate.put("name", "RESTful"); - - this.mockMvc.perform( - patch(tagLocation).contentType(MediaTypes.HAL_JSON).content( - this.objectMapper.writeValueAsString(tagUpdate))) - .andExpect(status().isNoContent()) - .andDo(document("tag-update-example", - requestFields( - fieldWithPath("name").description("The name of the tag")))); - } - - private void createNote(String title, String body) { - Note note = new Note(); - note.setTitle(title); - note.setBody(body); - - this.noteRepository.save(note); - } - - private void createTag(String name) { - Tag tag = new Tag(); - tag.setName(name); - this.tagRepository.save(tag); - } -} diff --git a/samples/rest-notes-spring-data-rest/src/test/java/com/example/notes/GettingStartedDocumentation.java b/samples/rest-notes-spring-data-rest/src/test/java/com/example/notes/GettingStartedDocumentation.java deleted file mode 100644 index 6dcecb1af..000000000 --- a/samples/rest-notes-spring-data-rest/src/test/java/com/example/notes/GettingStartedDocumentation.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.hateoas.MediaTypes; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.JsonPath; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class GettingStartedDocumentation { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @Before - public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) - .alwaysDo(document("{method-name}/{step}/")) - .build(); - } - - @Test - public void index() throws Exception { - this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("_links.notes", is(notNullValue()))) - .andExpect(jsonPath("_links.tags", is(notNullValue()))); - } - - @Test - public void creatingANote() throws JsonProcessingException, Exception { - String noteLocation = createNote(); - MvcResult note = getNote(noteLocation); - - String tagLocation = createTag(); - getTag(tagLocation); - - String taggedNoteLocation = createTaggedNote(tagLocation); - MvcResult taggedNote = getNote(taggedNoteLocation); - getTags(getLink(taggedNote, "tags")); - - tagExistingNote(noteLocation, tagLocation); - getTags(getLink(note, "tags")); - } - - String createNote() throws Exception { - Map note = new HashMap(); - note.put("title", "Note creation with cURL"); - note.put("body", "An example of how to create a note using cURL"); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()) - .andExpect(header().string("Location", notNullValue())) - .andReturn().getResponse().getHeader("Location"); - return noteLocation; - } - - MvcResult getNote(String noteLocation) throws Exception { - return this.mockMvc.perform(get(noteLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("title", is(notNullValue()))) - .andExpect(jsonPath("body", is(notNullValue()))) - .andExpect(jsonPath("_links.tags", is(notNullValue()))) - .andReturn(); - } - - String createTag() throws Exception, JsonProcessingException { - Map tag = new HashMap(); - tag.put("name", "getting-started"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andExpect(header().string("Location", notNullValue())) - .andReturn().getResponse().getHeader("Location"); - return tagLocation; - } - - void getTag(String tagLocation) throws Exception { - this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk()) - .andExpect(jsonPath("name", is(notNullValue()))) - .andExpect(jsonPath("_links.notes", is(notNullValue()))); - } - - String createTaggedNote(String tag) throws Exception { - Map note = new HashMap(); - note.put("title", "Tagged note creation with cURL"); - note.put("body", "An example of how to create a tagged note using cURL"); - note.put("tags", Arrays.asList(tag)); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()) - .andExpect(header().string("Location", notNullValue())) - .andReturn().getResponse().getHeader("Location"); - return noteLocation; - } - - void getTags(String noteTagsLocation) throws Exception { - this.mockMvc.perform(get(noteTagsLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("_embedded.tags", hasSize(1))); - } - - void tagExistingNote(String noteLocation, String tagLocation) throws Exception { - Map update = new HashMap(); - update.put("tags", Arrays.asList(tagLocation)); - - this.mockMvc.perform( - patch(noteLocation).contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(update))) - .andExpect(status().isNoContent()); - } - - MvcResult getTaggedExistingNote(String noteLocation) throws Exception { - return this.mockMvc.perform(get(noteLocation)) - .andExpect(status().isOk()) - .andReturn(); - } - - void getTagsForExistingNote(String noteTagsLocation) throws Exception { - this.mockMvc.perform(get(noteTagsLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("_embedded.tags", hasSize(1))); - } - - private String getLink(MvcResult result, String rel) - throws UnsupportedEncodingException { - return JsonPath.parse(result.getResponse().getContentAsString()).read( - "_links." + rel + ".href"); - } -} diff --git a/samples/rest-notes-spring-hateoas/build.gradle b/samples/rest-notes-spring-hateoas/build.gradle deleted file mode 100644 index 6fa86e462..000000000 --- a/samples/rest-notes-spring-hateoas/build.gradle +++ /dev/null @@ -1,69 +0,0 @@ -plugins { - id "eclipse" - id "java" - id "org.asciidoctor.jvm.convert" version "3.3.2" - id "org.springframework.boot" version "2.6.2" -} - -apply plugin: 'io.spring.dependency-management' - -repositories { - mavenLocal() - maven { url 'https://repo.spring.io/milestone' } - maven { url 'https://repo.spring.io/snapshot' } - mavenCentral() -} - -group = 'com.example' - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -ext { - snippetsDir = file('build/generated-snippets') -} - -ext['spring-restdocs.version'] = '2.0.7.BUILD-SNAPSHOT' - -configurations { - asciidoctorExtensions -} - -dependencies { - asciidoctorExtensions 'org.springframework.restdocs:spring-restdocs-asciidoctor' - - implementation 'org.springframework.boot:spring-boot-starter-data-jpa' - implementation 'org.springframework.boot:spring-boot-starter-hateoas' - implementation 'org.springframework.boot:spring-boot-starter-validation' - - runtimeOnly 'com.h2database:h2' - runtimeOnly 'org.atteo:evo-inflector:1.2.1' - - testImplementation 'com.jayway.jsonpath:json-path' - testImplementation 'org.assertj:assertj-core' - testImplementation('org.junit.vintage:junit-vintage-engine') { - exclude group: 'org.hamcrest', module: 'hamcrest-core' - } - testImplementation 'org.springframework.boot:spring-boot-starter-test' - testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' -} - -test { - outputs.dir snippetsDir -} - -asciidoctor { - configurations "asciidoctorExtensions" - inputs.dir snippetsDir - dependsOn test -} - -bootJar { - dependsOn asciidoctor - from ("${asciidoctor.outputDir}/html5") { - into 'static/docs' - } -} - -eclipseJdt.onlyIf { false } -cleanEclipseJdt.onlyIf { false } diff --git a/samples/rest-notes-spring-hateoas/gradle/wrapper/gradle-wrapper.jar b/samples/rest-notes-spring-hateoas/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index e708b1c02..000000000 Binary files a/samples/rest-notes-spring-hateoas/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/samples/rest-notes-spring-hateoas/gradle/wrapper/gradle-wrapper.properties b/samples/rest-notes-spring-hateoas/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 442d9132e..000000000 --- a/samples/rest-notes-spring-hateoas/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/samples/rest-notes-spring-hateoas/gradlew b/samples/rest-notes-spring-hateoas/gradlew deleted file mode 100755 index 4f906e0c8..000000000 --- a/samples/rest-notes-spring-hateoas/gradlew +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/samples/rest-notes-spring-hateoas/gradlew.bat b/samples/rest-notes-spring-hateoas/gradlew.bat deleted file mode 100644 index 107acd32c..000000000 --- a/samples/rest-notes-spring-hateoas/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/samples/rest-notes-spring-hateoas/settings.gradle b/samples/rest-notes-spring-hateoas/settings.gradle deleted file mode 100644 index e69de29bb..000000000 diff --git a/samples/rest-notes-spring-hateoas/src/docs/asciidoc/api-guide.adoc b/samples/rest-notes-spring-hateoas/src/docs/asciidoc/api-guide.adoc deleted file mode 100644 index 90745896e..000000000 --- a/samples/rest-notes-spring-hateoas/src/docs/asciidoc/api-guide.adoc +++ /dev/null @@ -1,229 +0,0 @@ -= RESTful Notes API Guide -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs -:toc: left -:toclevels: 4 -:sectlinks: -:operation-curl-request-title: Example request -:operation-http-response-title: Example response - -[[overview]] -= Overview - -[[overview_http_verbs]] -== HTTP verbs - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP verbs. - -|=== -| Verb | Usage - -| `GET` -| Used to retrieve a resource - -| `POST` -| Used to create a new resource - -| `PATCH` -| Used to update an existing resource, including partial updates - -| `DELETE` -| Used to delete an existing resource -|=== - -[[overview_http_status_codes]] -== HTTP status codes - -RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its -use of HTTP status codes. - -|=== -| Status code | Usage - -| `200 OK` -| The request completed successfully - -| `201 Created` -| A new resource has been created successfully. The resource's URI is available from the response's -`Location` header - -| `204 No Content` -| An update to an existing resource has been applied successfully - -| `400 Bad Request` -| The request was malformed. The response body will include an error providing further information - -| `404 Not Found` -| The requested resource did not exist -|=== - -[[overview_headers]] -== Headers - -Every response has the following header(s): - -include::{snippets}/headers-example/response-headers.adoc[] - -[[overview_errors]] -== Errors - -Whenever an error response (status code >= 400) is returned, the body will contain a JSON object -that describes the problem. The error object has the following structure: - -include::{snippets}/error-example/response-fields.adoc[] - -For example, a request that attempts to apply a non-existent tag to a note will produce a -`400 Bad Request` response: - -include::{snippets}/error-example/http-response.adoc[] - -[[overview_hypermedia]] -== Hypermedia - -RESTful Notes uses hypermedia and resources include links to other resources in their -responses. Responses are in https://github.com/mikekelly/hal_specification[Hypertext -Application Language (HAL)] format. Links can be found beneath the `_links` key. Users of -the API should not create URIs themselves, instead they should use the above-described -links to navigate from resource to resource. - -[[resources]] -= Resources - - - -[[resources_index]] -== Index - -The index provides the entry point into the service. - - - -[[resources_index_access]] -=== Accessing the index - -A `GET` request is used to access the index - -operation::index-example[snippets='response-fields,http-response,links'] - - - -[[resources_notes]] -== Notes - -The Notes resources is used to create and list notes - - - -[[resources_notes_list]] -=== Listing notes - -A `GET` request will list all of the service's notes. - -operation::notes-list-example[snippets='response-fields,curl-request,http-response'] - - - -[[resources_notes_create]] -=== Creating a note - -A `POST` request is used to create a note. - -operation::notes-create-example[snippets='request-fields,curl-request,http-response'] - - - -[[resources_tags]] -== Tags - -The Tags resource is used to create and list tags. - - - -[[resources_tags_list]] -=== Listing tags - -A `GET` request will list all of the service's tags. - -operation::tags-list-example[snippets='response-fields,curl-request,http-response'] - - - -[[resources_tags_create]] -=== Creating a tag - -A `POST` request is used to create a note - -operation::tags-create-example[snippets='request-fields,curl-request,http-response'] - - - -[[resources_note]] -== Note - -The Note resource is used to retrieve, update, and delete individual notes - - - -[[resources_note_links]] -=== Links - -include::{snippets}/note-get-example/links.adoc[] - - - -[[resources_note_retrieve]] -=== Retrieve a note - -A `GET` request will retrieve the details of a note - -operation::note-get-example[snippets='response-fields,curl-request,http-response'] - - - -[[resources_note_update]] -=== Update a note - -A `PATCH` request is used to update a note - -==== Request structure - -include::{snippets}/note-update-example/request-fields.adoc[] - -To leave an attribute of a note unchanged, any of the above may be omitted from the request. - -operation::note-update-example[snippets='curl-request,http-response'] - - - -[[resources_tag]] -== Tag - -The Tag resource is used to retrieve, update, and delete individual tags - - - -[[resources_tag_links]] -=== Links - -include::{snippets}/tag-get-example/links.adoc[] - - - -[[resources_tag_retrieve]] -=== Retrieve a tag - -A `GET` request will retrieve the details of a tag - -operation::tag-get-example[snippets='response-fields,curl-request,http-response'] - - - -[[resources_tag_update]] -=== Update a tag - -A `PATCH` request is used to update a tag - -operation::tag-update-example[snippets='request-fields,curl-request,http-response'] diff --git a/samples/rest-notes-spring-hateoas/src/docs/asciidoc/getting-started-guide.adoc b/samples/rest-notes-spring-hateoas/src/docs/asciidoc/getting-started-guide.adoc deleted file mode 100644 index 7e8346ac7..000000000 --- a/samples/rest-notes-spring-hateoas/src/docs/asciidoc/getting-started-guide.adoc +++ /dev/null @@ -1,173 +0,0 @@ -= RESTful Notes Getting Started Guide -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs -:toc: left -:toclevels: 4 -:sectlinks: - -[[introduction]] -= Introduction - -RESTful Notes is a RESTful web service for creating and storing notes. It uses hypermedia -to describe the relationships between resources and to allow navigation between them. - - - -[[getting_started_running_the_service]] -== Running the service -RESTful Notes is written using https://projects.spring.io/spring-boot[Spring Boot] which -makes it easy to get it up and running so that you can start exploring the REST API. - -The first step is to clone the Git repository: - -[source,bash] ----- -$ git clone https://github.com/spring-projects/spring-restdocs ----- - -Once the clone is complete, you're ready to get the service up and running: - -[source,bash] ----- -$ cd samples/rest-notes-spring-hateoas -$ ./gradlew build -$ java -jar build/libs/*.jar ----- - -You can check that the service is up and running by executing a simple request using -cURL: - -include::{snippets}/index/1/curl-request.adoc[] - -This request should yield the following response: - -include::{snippets}/index/1/http-response.adoc[] - -Note the `_links` in the JSON response. They are key to navigating the API. - - - -[[getting_started_creating_a_note]] -== Creating a note -Now that you've started the service and verified that it works, the next step is to use -it to create a new note. As you saw above, the URI for working with notes is included as -a link when you perform a `GET` request against the root of the service: - -include::{snippets}/index/1/http-response.adoc[] - -To create a note you need to execute a `POST` request to this URI, including a JSON -payload containing the title and body of the note: - -include::{snippets}/creating-a-note/1/curl-request.adoc[] - -The response from this request should have a status code of `201 Created` and contain a -`Location` header whose value is the URI of the newly created note: - -include::{snippets}/creating-a-note/1/http-response.adoc[] - -To work with the newly created note you use the URI in the `Location` header. For example -you can access the note's details by performing a `GET` request: - -include::{snippets}/creating-a-note/2/curl-request.adoc[] - -This request will produce a response with the note's details in its body: - -include::{snippets}/creating-a-note/2/http-response.adoc[] - -Note the `note-tags` link which we'll make use of later. - - - -[[getting_started_creating_a_tag]] -== Creating a tag -To make a note easier to find, it can be associated with any number of tags. To be able -to tag a note, you must first create the tag. - -Referring back to the response for the service's index, the URI for working with tags is -include as a link: - -include::{snippets}/index/1/http-response.adoc[] - -To create a tag you need to execute a `POST` request to this URI, including a JSON -payload containing the name of the tag: - -include::{snippets}/creating-a-note/3/curl-request.adoc[] - -The response from this request should have a status code of `201 Created` and contain a -`Location` header whose value is the URI of the newly created tag: - -include::{snippets}/creating-a-note/3/http-response.adoc[] - -To work with the newly created tag you use the URI in the `Location` header. For example -you can access the tag's details by performing a `GET` request: - -include::{snippets}/creating-a-note/4/curl-request.adoc[] - -This request will produce a response with the tag's details in its body: - -include::{snippets}/creating-a-note/4/http-response.adoc[] - - - -[[getting_started_tagging_a_note]] -== Tagging a note -A tag isn't particularly useful until it's been associated with one or more notes. There -are two ways to tag a note: when the note is first created or by updating an existing -note. We'll look at both of these in turn. - - - -[[getting_started_tagging_a_note_creating]] -=== Creating a tagged note -The process is largely the same as we saw before, but this time, in addition to providing -a title and body for the note, we'll also provide the tag that we want to be associated -with it. - -Once again we execute a `POST` request, but this time, in an array named tags, we include -the URI of the tag we just created: - -include::{snippets}/creating-a-note/5/curl-request.adoc[] - -Once again, the response's `Location` header tells use the URI of the newly created note: - -include::{snippets}/creating-a-note/5/http-response.adoc[] - -As before, a `GET` request executed against this URI will retrieve the note's details: - -include::{snippets}/creating-a-note/6/curl-request.adoc[] -include::{snippets}/creating-a-note/6/http-response.adoc[] - -To see the note's tags, execute a `GET` request against the URI of the note's -`note-tags` link: - -include::{snippets}/creating-a-note/7/curl-request.adoc[] - -The response shows that, as expected, the note has a single tag: - -include::{snippets}/creating-a-note/7/http-response.adoc[] - - - -[[getting_started_tagging_a_note_existing]] -=== Tagging an existing note -An existing note can be tagged by executing a `PATCH` request against the note's URI with -a body that contains the array of tags to be associated with the note. We'll use the -URI of the untagged note that we created earlier: - -include::{snippets}/creating-a-note/8/curl-request.adoc[] - -This request should produce a `204 No Content` response: - -include::{snippets}/creating-a-note/8/http-response.adoc[] - -When we first created this note, we noted the `note-tags` link included in its details: - -include::{snippets}/creating-a-note/2/http-response.adoc[] - -We can use that link now and execute a `GET` request to see that the note now has a -single tag: - -include::{snippets}/creating-a-note/9/curl-request.adoc[] -include::{snippets}/creating-a-note/9/http-response.adoc[] diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/ExceptionSupressingErrorAttributes.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/ExceptionSupressingErrorAttributes.java deleted file mode 100644 index d7725a518..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/ExceptionSupressingErrorAttributes.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2014-2017 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.notes; - -import java.util.Map; - -import org.springframework.boot.web.error.ErrorAttributeOptions; -import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.WebRequest; - -@Component -class ExceptionSupressingErrorAttributes extends DefaultErrorAttributes { - - @Override - public Map getErrorAttributes(WebRequest webRequest, - ErrorAttributeOptions options) { - Map errorAttributes = super.getErrorAttributes(webRequest, options); - errorAttributes.remove("exception"); - Object message = webRequest.getAttribute("javax.servlet.error.message", RequestAttributes.SCOPE_REQUEST); - if (message != null) { - errorAttributes.put("message", message); - } - return errorAttributes; - } -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/IndexController.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/IndexController.java deleted file mode 100644 index 25f69dcda..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/IndexController.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; - -import org.springframework.hateoas.RepresentationModel; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/") -class IndexController { - - @RequestMapping(method=RequestMethod.GET) - public RepresentationModel index() { - RepresentationModel index = new RepresentationModel<>(); - index.add(linkTo(NotesController.class).withRel("notes")); - index.add(linkTo(TagsController.class).withRel("tags")); - return index; - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/Note.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/Note.java deleted file mode 100644 index 46b349dab..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/Note.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -@Entity -public class Note { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String title; - - private String body; - - @ManyToMany - private List tags; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteInput.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteInput.java deleted file mode 100644 index d5fd5c860..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteInput.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import java.net.URI; -import java.util.Collections; -import java.util.List; - -import javax.validation.constraints.NotBlank; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -class NoteInput { - - @NotBlank - private final String title; - - private final String body; - - private final List tagUris; - - @JsonCreator - NoteInput(@JsonProperty("title") String title, - @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) { - this.title = title; - this.body = body; - this.tagUris = tagUris == null ? Collections.emptyList() : tagUris; - } - - String getTitle() { - return title; - } - - String getBody() { - return body; - } - - @JsonProperty("tags") - List getTagUris() { - return this.tagUris; - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NotePatchInput.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NotePatchInput.java deleted file mode 100644 index 6d69bfa8f..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NotePatchInput.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import java.net.URI; -import java.util.Collections; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -class NotePatchInput { - - @NullOrNotBlank - private final String title; - - private final String body; - - private final List tagUris; - - @JsonCreator - NotePatchInput(@JsonProperty("title") String title, - @JsonProperty("body") String body, @JsonProperty("tags") List tagUris) { - this.title = title; - this.body = body; - this.tagUris = tagUris == null ? Collections.emptyList() : tagUris; - } - - String getTitle() { - return title; - } - - String getBody() { - return body; - } - - @JsonProperty("tags") - List getTagUris() { - return this.tagUris; - } -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteRepository.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteRepository.java deleted file mode 100644 index cd9e47352..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import java.util.Collection; -import java.util.List; - -import org.springframework.data.repository.CrudRepository; - -interface NoteRepository extends CrudRepository { - - Note findById(long id); - - List findByTagsIn(Collection tags); - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteRepresentationModelAssembler.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteRepresentationModelAssembler.java deleted file mode 100644 index eb9e4ab65..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NoteRepresentationModelAssembler.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; - -import org.springframework.hateoas.RepresentationModel; -import org.springframework.hateoas.server.core.Relation; -import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; -import org.springframework.stereotype.Component; - -import com.example.notes.NoteRepresentationModelAssembler.NoteModel; - -@Component -class NoteRepresentationModelAssembler extends RepresentationModelAssemblerSupport { - - NoteRepresentationModelAssembler() { - super(NotesController.class, NoteModel.class); - } - - @Override - public NoteModel toModel(Note entity) { - NoteModel noteModel = createModelWithId(entity.getId(), entity); - noteModel.add(linkTo(methodOn(NotesController.class).noteTags(entity.getId())).withRel("note-tags")); - return noteModel; - } - - @Override - protected NoteModel instantiateModel(Note entity) { - return new NoteModel(entity); - } - - @Relation(collectionRelation = "notes", itemRelation = "note") - static class NoteModel extends RepresentationModel { - - private final Note note; - - NoteModel(Note note) { - this.note = note; - } - - public String getTitle() { - return this.note.getTitle(); - } - - public String getBody() { - return this.note.getBody(); - } - - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NotesController.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NotesController.java deleted file mode 100644 index ab7218493..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NotesController.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.springframework.hateoas.CollectionModel; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.util.UriTemplate; - -import com.example.notes.NoteRepresentationModelAssembler.NoteModel; -import com.example.notes.TagRepresentationModelAssembler.TagModel; - -@RestController -@RequestMapping("/notes") -class NotesController { - - private static final UriTemplate TAG_URI_TEMPLATE = new UriTemplate("/tags/{id}"); - - private final NoteRepository noteRepository; - - private final TagRepository tagRepository; - - private final NoteRepresentationModelAssembler noteAssembler; - - private final TagRepresentationModelAssembler tagAssembler; - - NotesController(NoteRepository noteRepository, TagRepository tagRepository, - NoteRepresentationModelAssembler noteAssembler, TagRepresentationModelAssembler tagAssembler) { - this.noteRepository = noteRepository; - this.tagRepository = tagRepository; - this.noteAssembler = noteAssembler; - this.tagAssembler = tagAssembler; - } - - @RequestMapping(method = RequestMethod.GET) - CollectionModel all() { - return noteAssembler.toCollectionModel(this.noteRepository.findAll()); - } - - @ResponseStatus(HttpStatus.CREATED) - @RequestMapping(method = RequestMethod.POST) - HttpHeaders create(@RequestBody NoteInput noteInput) { - Note note = new Note(); - note.setTitle(noteInput.getTitle()); - note.setBody(noteInput.getBody()); - note.setTags(getTags(noteInput.getTagUris())); - - this.noteRepository.save(note); - - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders - .setLocation(linkTo(NotesController.class).slash(note.getId()).toUri()); - - return httpHeaders; - } - - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - void delete(@PathVariable("id") long id) { - this.noteRepository.deleteById(id); - } - - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - NoteModel note(@PathVariable("id") long id) { - return this.noteAssembler.toModel(findNoteById(id)); - } - - @RequestMapping(value = "/{id}/tags", method = RequestMethod.GET) - CollectionModel noteTags(@PathVariable("id") long id) { - return this.tagAssembler.toCollectionModel(findNoteById(id).getTags()); - } - - @RequestMapping(value = "/{id}", method = RequestMethod.PATCH) - @ResponseStatus(HttpStatus.NO_CONTENT) - void updateNote(@PathVariable("id") long id, @RequestBody NotePatchInput noteInput) { - Note note = findNoteById(id); - if (noteInput.getTagUris() != null) { - note.setTags(getTags(noteInput.getTagUris())); - } - if (noteInput.getTitle() != null) { - note.setTitle(noteInput.getTitle()); - } - if (noteInput.getBody() != null) { - note.setBody(noteInput.getBody()); - } - this.noteRepository.save(note); - } - - private Note findNoteById(long id) { - Note note = this.noteRepository.findById(id); - if (note == null) { - throw new ResourceDoesNotExistException(); - } - return note; - } - - private List getTags(List tagLocations) { - List tags = new ArrayList<>(tagLocations.size()); - for (URI tagLocation: tagLocations) { - Tag tag = this.tagRepository.findById(extractTagId(tagLocation)); - if (tag == null) { - throw new IllegalArgumentException("The tag '" + tagLocation - + "' does not exist"); - } - tags.add(tag); - } - return tags; - } - - private long extractTagId(URI tagLocation) { - try { - String idString = TAG_URI_TEMPLATE.match(tagLocation.toASCIIString()).get( - "id"); - return Long.valueOf(idString); - } - catch (RuntimeException ex) { - throw new IllegalArgumentException("The tag '" + tagLocation + "' is invalid"); - } - } -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/ResourceDoesNotExistException.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/ResourceDoesNotExistException.java deleted file mode 100644 index 88327a6fb..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/ResourceDoesNotExistException.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -@SuppressWarnings("serial") -class ResourceDoesNotExistException extends RuntimeException { - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/RestNotesControllerAdvice.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/RestNotesControllerAdvice.java deleted file mode 100644 index bef998e2e..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/RestNotesControllerAdvice.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -@ControllerAdvice -class RestNotesControllerAdvice { - - @ExceptionHandler(IllegalArgumentException.class) - void handleIllegalArgumentException(IllegalArgumentException ex, - HttpServletResponse response) throws IOException { - response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage()); - } - - @ExceptionHandler(ResourceDoesNotExistException.class) - void handleResourceDoesNotExistException(ResourceDoesNotExistException ex, - HttpServletRequest request, HttpServletResponse response) throws IOException { - response.sendError(HttpStatus.NOT_FOUND.value(), - "The resource '" + request.getRequestURI() + "' does not exist"); - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/RestNotesSpringHateoas.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/RestNotesSpringHateoas.java deleted file mode 100644 index f2916a128..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/RestNotesSpringHateoas.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -class RestNotesSpringHateoas { - - public static void main(String[] args) { - SpringApplication.run(RestNotesSpringHateoas.class, args); - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/Tag.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/Tag.java deleted file mode 100644 index b8274227b..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/Tag.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2014 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.notes; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; - -@Entity -public class Tag { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String name; - - @ManyToMany(mappedBy = "tags") - private List notes; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getNotes() { - return notes; - } - - public void setNotes(List notes) { - this.notes = notes; - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagInput.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagInput.java deleted file mode 100644 index bc9b397a2..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagInput.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import javax.validation.constraints.NotBlank; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -class TagInput { - - @NotBlank - private final String name; - - @JsonCreator - TagInput(@NotBlank @JsonProperty("name") String name) { - this.name = name; - } - - String getName() { - return name; - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagPatchInput.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagPatchInput.java deleted file mode 100644 index fd9e8c2fc..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagPatchInput.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -class TagPatchInput { - - @NullOrNotBlank - private final String name; - - @JsonCreator - TagPatchInput(@NullOrNotBlank @JsonProperty("name") String name) { - this.name = name; - } - - String getName() { - return name; - } - -} \ No newline at end of file diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagRepository.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagRepository.java deleted file mode 100644 index f92065260..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagRepository.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import org.springframework.data.repository.CrudRepository; - -interface TagRepository extends CrudRepository { - - Tag findById(long id); - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagRepresentationModelAssembler.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagRepresentationModelAssembler.java deleted file mode 100644 index e2b4a59b3..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagRepresentationModelAssembler.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2014-2021 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.notes; - -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; - -import org.springframework.hateoas.RepresentationModel; -import org.springframework.hateoas.server.core.Relation; -import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport; -import org.springframework.stereotype.Component; - -import com.example.notes.TagRepresentationModelAssembler.TagModel; - -@Component -class TagRepresentationModelAssembler extends RepresentationModelAssemblerSupport { - - TagRepresentationModelAssembler() { - super(TagsController.class, TagModel.class); - } - - @Override - public TagModel toModel(Tag entity) { - TagModel model = new TagModel(entity); - model.add(linkTo(methodOn(TagsController.class).tag(entity.getId())).withSelfRel(), - linkTo(methodOn(TagsController.class).tagNotes(entity.getId())).withRel("tagged-notes")); - return model; - } - - @Override - protected TagModel instantiateModel(Tag entity) { - return new TagModel(entity); - } - - @Relation(collectionRelation = "tags", itemRelation = "tag") - static class TagModel extends RepresentationModel { - - private final Tag tag; - - TagModel(Tag tag) { - this.tag = tag; - } - - public String getName() { - return this.tag.getName(); - } - - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagsController.java b/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagsController.java deleted file mode 100644 index 945cc17b3..000000000 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/TagsController.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2014-2017 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.notes; - -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; - -import org.springframework.hateoas.CollectionModel; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - -import com.example.notes.NoteRepresentationModelAssembler.NoteModel; -import com.example.notes.TagRepresentationModelAssembler.TagModel; - -@RestController -@RequestMapping("tags") -class TagsController { - - private final TagRepository repository; - - private final TagRepresentationModelAssembler tagAssembler; - - private final NoteRepresentationModelAssembler noteAssembler; - - TagsController(TagRepository repository, TagRepresentationModelAssembler tagAssembler, - NoteRepresentationModelAssembler noteAssembler) { - this.repository = repository; - this.tagAssembler = tagAssembler; - this.noteAssembler = noteAssembler; - } - - @RequestMapping(method = RequestMethod.GET) - CollectionModel all() { - return this.tagAssembler.toCollectionModel(this.repository.findAll()); - } - - @ResponseStatus(HttpStatus.CREATED) - @RequestMapping(method = RequestMethod.POST) - HttpHeaders create(@RequestBody TagInput tagInput) { - Tag tag = new Tag(); - tag.setName(tagInput.getName()); - - this.repository.save(tag); - - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setLocation(linkTo(TagsController.class).slash(tag.getId()).toUri()); - - return httpHeaders; - } - - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - void delete(@PathVariable("id") long id) { - this.repository.deleteById(id); - } - - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - TagModel tag(@PathVariable("id") long id) { - return this.tagAssembler.toModel(findTagById(id)); - } - - @RequestMapping(value = "/{id}/notes", method = RequestMethod.GET) - CollectionModel tagNotes(@PathVariable("id") long id) { - return this.noteAssembler.toCollectionModel(findTagById(id).getNotes()); - } - - private Tag findTagById(long id) { - Tag tag = this.repository.findById(id); - if (tag == null) { - throw new ResourceDoesNotExistException(); - } - return tag; - } - - @RequestMapping(value = "/{id}", method = RequestMethod.PATCH) - @ResponseStatus(HttpStatus.NO_CONTENT) - void updateTag(@PathVariable("id") long id, @RequestBody TagPatchInput tagInput) { - Tag tag = findTagById(id); - if (tagInput.getName() != null) { - tag.setName(tagInput.getName()); - } - this.repository.save(tag); - } -} diff --git a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/ApiDocumentation.java b/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/ApiDocumentation.java deleted file mode 100644 index 17cebdb18..000000000 --- a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/ApiDocumentation.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * Copyright 2014-2020 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.notes; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; -import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; -import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; -import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; -import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; -import static org.springframework.restdocs.snippet.Attributes.key; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.RequestDispatcher; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.hateoas.MediaTypes; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.restdocs.constraints.ConstraintDescriptions; -import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; -import org.springframework.restdocs.payload.FieldDescriptor; -import org.springframework.restdocs.payload.JsonFieldType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.util.StringUtils; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class ApiDocumentation { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - private RestDocumentationResultHandler documentationHandler; - - @Autowired - private NoteRepository noteRepository; - - @Autowired - private TagRepository tagRepository; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @Before - public void setUp() { - this.documentationHandler = document("{method-name}", - preprocessRequest(prettyPrint()), - preprocessResponse(prettyPrint())); - - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) - .alwaysDo(this.documentationHandler) - .build(); - } - - @Test - public void headersExample() throws Exception { - this.mockMvc - .perform(get("/")) - .andExpect(status().isOk()) - .andDo(this.documentationHandler.document( - responseHeaders( - headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`")))); - } - - @Test - public void errorExample() throws Exception { - this.mockMvc - .perform(get("/error") - .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 400) - .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, "/notes") - .requestAttr(RequestDispatcher.ERROR_MESSAGE, "The tag 'http://localhost:8080/tags/123' does not exist")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("error", is("Bad Request"))) - .andExpect(jsonPath("timestamp", is(notNullValue()))) - .andExpect(jsonPath("status", is(400))) - .andExpect(jsonPath("path", is(notNullValue()))) - .andDo(this.documentationHandler.document( - responseFields( - fieldWithPath("error").description("The HTTP error that occurred, e.g. `Bad Request`"), - fieldWithPath("message").description("A description of the cause of the error"), - fieldWithPath("path").description("The path to which the request was made"), - fieldWithPath("status").description("The HTTP status code, e.g. `400`"), - fieldWithPath("timestamp").description("The time, in milliseconds, at which the error occurred")))); - } - - @Test - public void indexExample() throws Exception { - this.mockMvc.perform(get("/")) - .andExpect(status().isOk()) - .andDo(this.documentationHandler.document( - links( - linkWithRel("notes").description("The <>"), - linkWithRel("tags").description("The <>")), - responseFields( - subsectionWithPath("_links").description("<> to other resources")))); - } - - @Test - public void notesListExample() throws Exception { - this.noteRepository.deleteAll(); - - createNote("REST maturity model", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - createNote("Hypertext Application Language (HAL)", "https://github.com/mikekelly/hal_specification"); - createNote("Application-Level Profile Semantics (ALPS)", "https://github.com/alps-io/spec"); - - this.mockMvc - .perform(get("/notes")) - .andExpect(status().isOk()) - .andDo(this.documentationHandler.document( - responseFields( - subsectionWithPath("_embedded.notes").description("An array of <>")))); - } - - @Test - public void notesCreateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform(post("/tags") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andReturn().getResponse().getHeader("Location"); - - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - note.put("tags", Arrays.asList(tagLocation)); - - ConstrainedFields fields = new ConstrainedFields(NoteInput.class); - - this.mockMvc - .perform(post("/notes") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(note))) - .andExpect( - status().isCreated()) - .andDo(this.documentationHandler.document( - requestFields( - fields.withPath("title").description("The title of the note"), - fields.withPath("body").description("The body of the note"), - fields.withPath("tags").description("An array of tag resource URIs")))); - } - - @Test - public void noteGetExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform(post("/tags") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andReturn().getResponse().getHeader("Location"); - - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - note.put("tags", Arrays.asList(tagLocation)); - - String noteLocation = this.mockMvc - .perform(post("/notes") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()) - .andReturn().getResponse().getHeader("Location"); - - this.mockMvc - .perform(get(noteLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("title", is(note.get("title")))) - .andExpect(jsonPath("body", is(note.get("body")))) - .andExpect(jsonPath("_links.self.href", is(noteLocation))) - .andExpect(jsonPath("_links.note-tags", is(notNullValue()))) - .andDo(this.documentationHandler.document( - links( - linkWithRel("self").description("This <>"), - linkWithRel("note-tags").description("This note's <>")), - responseFields( - fieldWithPath("title").description("The title of the note"), - fieldWithPath("body").description("The body of the note"), - subsectionWithPath("_links").description("<> to other resources")))); - - } - - @Test - public void tagsListExample() throws Exception { - this.noteRepository.deleteAll(); - this.tagRepository.deleteAll(); - - createTag("REST"); - createTag("Hypermedia"); - createTag("HTTP"); - - this.mockMvc - .perform(get("/tags")) - .andExpect(status().isOk()) - .andDo(this.documentationHandler.document( - responseFields( - subsectionWithPath("_embedded.tags").description("An array of <>")))); - } - - @Test - public void tagsCreateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - ConstrainedFields fields = new ConstrainedFields(TagInput.class); - - this.mockMvc - .perform(post("/tags") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andDo(this.documentationHandler.document( - requestFields( - fields.withPath("name").description("The name of the tag")))); - } - - @Test - public void noteUpdateExample() throws Exception { - Map note = new HashMap(); - note.put("title", "REST maturity model"); - note.put("body", "https://martinfowler.com/articles/richardsonMaturityModel.html"); - - String noteLocation = this.mockMvc - .perform(post("/notes") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()) - .andReturn().getResponse().getHeader("Location"); - - this.mockMvc - .perform(get(noteLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("title", is(note.get("title")))) - .andExpect(jsonPath("body", is(note.get("body")))) - .andExpect(jsonPath("_links.self.href", is(noteLocation))) - .andExpect(jsonPath("_links.note-tags", is(notNullValue()))); - - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform(post("/tags") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andReturn().getResponse().getHeader("Location"); - - Map noteUpdate = new HashMap(); - noteUpdate.put("tags", Arrays.asList(tagLocation)); - - ConstrainedFields fields = new ConstrainedFields(NotePatchInput.class); - - this.mockMvc - .perform(patch(noteLocation) - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(noteUpdate))) - .andExpect(status().isNoContent()) - .andDo(this.documentationHandler.document( - requestFields( - fields.withPath("title") - .description("The title of the note") - .type(JsonFieldType.STRING) - .optional(), - fields.withPath("body") - .description("The body of the note") - .type(JsonFieldType.STRING) - .optional(), - fields.withPath("tags") - .description("An array of tag resource URIs")))); - } - - @Test - public void tagGetExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform(post("/tags") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andReturn().getResponse().getHeader("Location"); - - this.mockMvc - .perform(get(tagLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("name", is(tag.get("name")))) - .andDo(this.documentationHandler.document( - links( - linkWithRel("self").description("This <>"), - linkWithRel("tagged-notes").description("The <> that have this tag")), - responseFields( - fieldWithPath("name").description("The name of the tag"), - subsectionWithPath("_links").description("<> to other resources")))); - } - - @Test - public void tagUpdateExample() throws Exception { - Map tag = new HashMap(); - tag.put("name", "REST"); - - String tagLocation = this.mockMvc - .perform(post("/tags") - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andReturn().getResponse().getHeader("Location"); - - Map tagUpdate = new HashMap(); - tagUpdate.put("name", "RESTful"); - - ConstrainedFields fields = new ConstrainedFields(TagPatchInput.class); - - this.mockMvc - .perform(patch(tagLocation) - .contentType(MediaTypes.HAL_JSON) - .content(this.objectMapper.writeValueAsString(tagUpdate))) - .andExpect(status().isNoContent()) - .andDo(this.documentationHandler.document( - requestFields( - fields.withPath("name").description("The name of the tag")))); - } - - private void createNote(String title, String body) { - Note note = new Note(); - note.setTitle(title); - note.setBody(body); - - this.noteRepository.save(note); - } - - private void createTag(String name) { - Tag tag = new Tag(); - tag.setName(name); - this.tagRepository.save(tag); - } - - private static class ConstrainedFields { - - private final ConstraintDescriptions constraintDescriptions; - - ConstrainedFields(Class input) { - this.constraintDescriptions = new ConstraintDescriptions(input); - } - - private FieldDescriptor withPath(String path) { - return fieldWithPath(path).attributes(key("constraints").value(StringUtils - .collectionToDelimitedString(this.constraintDescriptions - .descriptionsForProperty(path), ". "))); - } - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/GettingStartedDocumentation.java b/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/GettingStartedDocumentation.java deleted file mode 100644 index 38ab9b607..000000000 --- a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/GettingStartedDocumentation.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2014-2016 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.notes; - -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.hateoas.MediaTypes; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.JsonPath; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class GettingStartedDocumentation { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @Before - public void setUp() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) - .apply(documentationConfiguration(this.restDocumentation)) - .alwaysDo(document("{method-name}/{step}/", - preprocessRequest(prettyPrint()), - preprocessResponse(prettyPrint()))) - .build(); - } - - @Test - public void index() throws Exception { - this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("_links.notes", is(notNullValue()))) - .andExpect(jsonPath("_links.tags", is(notNullValue()))); - } - - @Test - public void creatingANote() throws JsonProcessingException, Exception { - String noteLocation = createNote(); - MvcResult note = getNote(noteLocation); - - String tagLocation = createTag(); - getTag(tagLocation); - - String taggedNoteLocation = createTaggedNote(tagLocation); - MvcResult taggedNote = getNote(taggedNoteLocation); - getTags(getLink(taggedNote, "note-tags")); - - tagExistingNote(noteLocation, tagLocation); - getTags(getLink(note, "note-tags")); - } - - String createNote() throws Exception { - Map note = new HashMap(); - note.put("title", "Note creation with cURL"); - note.put("body", "An example of how to create a note using cURL"); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()) - .andExpect(header().string("Location", notNullValue())) - .andReturn().getResponse().getHeader("Location"); - return noteLocation; - } - - MvcResult getNote(String noteLocation) throws Exception { - return this.mockMvc.perform(get(noteLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("title", is(notNullValue()))) - .andExpect(jsonPath("body", is(notNullValue()))) - .andExpect(jsonPath("_links.note-tags", is(notNullValue()))) - .andReturn(); - } - - String createTag() throws Exception, JsonProcessingException { - Map tag = new HashMap(); - tag.put("name", "getting-started"); - - String tagLocation = this.mockMvc - .perform( - post("/tags").contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(tag))) - .andExpect(status().isCreated()) - .andExpect(header().string("Location", notNullValue())) - .andReturn().getResponse().getHeader("Location"); - return tagLocation; - } - - void getTag(String tagLocation) throws Exception { - this.mockMvc.perform(get(tagLocation)).andExpect(status().isOk()) - .andExpect(jsonPath("name", is(notNullValue()))) - .andExpect(jsonPath("_links.tagged-notes", is(notNullValue()))); - } - - String createTaggedNote(String tag) throws Exception { - Map note = new HashMap(); - note.put("title", "Tagged note creation with cURL"); - note.put("body", "An example of how to create a tagged note using cURL"); - note.put("tags", Arrays.asList(tag)); - - String noteLocation = this.mockMvc - .perform( - post("/notes").contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(note))) - .andExpect(status().isCreated()) - .andExpect(header().string("Location", notNullValue())) - .andReturn().getResponse().getHeader("Location"); - return noteLocation; - } - - void getTags(String noteTagsLocation) throws Exception { - this.mockMvc.perform(get(noteTagsLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("_embedded.tags", hasSize(1))); - } - - void tagExistingNote(String noteLocation, String tagLocation) throws Exception { - Map update = new HashMap(); - update.put("tags", Arrays.asList(tagLocation)); - - this.mockMvc.perform( - patch(noteLocation).contentType(MediaTypes.HAL_JSON).content( - objectMapper.writeValueAsString(update))) - .andExpect(status().isNoContent()); - } - - MvcResult getTaggedExistingNote(String noteLocation) throws Exception { - return this.mockMvc.perform(get(noteLocation)) - .andExpect(status().isOk()) - .andReturn(); - } - - void getTagsForExistingNote(String noteTagsLocation) throws Exception { - this.mockMvc.perform(get(noteTagsLocation)) - .andExpect(status().isOk()) - .andExpect(jsonPath("_embedded.tags", hasSize(1))); - } - - private String getLink(MvcResult result, String rel) - throws UnsupportedEncodingException { - return JsonPath.parse(result.getResponse().getContentAsString()).read( - "_links." + rel + ".href"); - } -} diff --git a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/NullOrNotBlankTests.java b/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/NullOrNotBlankTests.java deleted file mode 100644 index a7086e729..000000000 --- a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/NullOrNotBlankTests.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2014-2018 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.notes; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; - -import org.junit.Test; - - -public class NullOrNotBlankTests { - - private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - - @Test - public void nullValue() { - Set> violations = validator.validate(new Constrained(null)); - assertThat(violations).isEmpty(); - } - - @Test - public void zeroLengthValue() { - Set> violations = validator.validate(new Constrained("")); - assertThat(violations).hasSize(2); - } - - @Test - public void blankValue() { - Set> violations = validator.validate(new Constrained(" ")); - assertThat(violations).hasSize(2); - } - - @Test - public void nonBlankValue() { - Set> violations = validator.validate(new Constrained("test")); - assertThat(violations).isEmpty(); - } - - static class Constrained { - - @NullOrNotBlank - private final String value; - - public Constrained(String value) { - this.value = value; - } - - } - -} diff --git a/samples/rest-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/constraints/ConstraintDescriptions.properties b/samples/rest-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/constraints/ConstraintDescriptions.properties deleted file mode 100644 index 433d946d5..000000000 --- a/samples/rest-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/constraints/ConstraintDescriptions.properties +++ /dev/null @@ -1,2 +0,0 @@ -com.example.notes.NullOrNotBlank.description=Must be null or not blank -org.hibernate.validator.constraints.NotBlank.description=Must not be blank \ No newline at end of file diff --git a/samples/rest-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/templates/request-fields.snippet b/samples/rest-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/templates/request-fields.snippet deleted file mode 100644 index cd1e825c8..000000000 --- a/samples/rest-notes-spring-hateoas/src/test/resources/org/springframework/restdocs/templates/request-fields.snippet +++ /dev/null @@ -1,11 +0,0 @@ -|=== -|Path|Type|Description|Constraints - -{{#fields}} -|{{path}} -|{{type}} -|{{description}} -|{{constraints}} - -{{/fields}} -|=== \ No newline at end of file diff --git a/samples/testng/build.gradle b/samples/testng/build.gradle deleted file mode 100644 index e7c940ca0..000000000 --- a/samples/testng/build.gradle +++ /dev/null @@ -1,59 +0,0 @@ -plugins { - id "eclipse" - id "java" - id "org.asciidoctor.jvm.convert" version "3.3.2" - id "org.springframework.boot" version "2.6.2" -} - -apply plugin: 'io.spring.dependency-management' - -repositories { - mavenLocal() - maven { url 'https://repo.spring.io/milestone' } - maven { url 'https://repo.spring.io/snapshot' } - mavenCentral() -} - -group = 'com.example' - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -ext { - snippetsDir = file('build/generated-snippets') -} - -ext['spring-restdocs.version'] = '2.0.7.BUILD-SNAPSHOT' - -configurations { - asciidoctorExtensions -} - -dependencies { - asciidoctorExtensions 'org.springframework.restdocs:spring-restdocs-asciidoctor' - implementation 'org.springframework.boot:spring-boot-starter-web' - testImplementation 'org.springframework.boot:spring-boot-starter-test' - testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' - testImplementation 'org.testng:testng:6.9.10' -} - -test { - useTestNG() - outputs.dir snippetsDir -} - -asciidoctor { - configurations "asciidoctorExtensions" - inputs.dir snippetsDir - dependsOn test -} - -bootJar { - dependsOn asciidoctor - from ("${asciidoctor.outputDir}/html5") { - into 'static/docs' - } -} - -eclipseJdt.onlyIf { false } -cleanEclipseJdt.onlyIf { false } diff --git a/samples/testng/gradle/wrapper/gradle-wrapper.jar b/samples/testng/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index e708b1c02..000000000 Binary files a/samples/testng/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/samples/testng/gradle/wrapper/gradle-wrapper.properties b/samples/testng/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 442d9132e..000000000 --- a/samples/testng/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/samples/testng/gradlew b/samples/testng/gradlew deleted file mode 100755 index 4f906e0c8..000000000 --- a/samples/testng/gradlew +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 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. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/samples/testng/gradlew.bat b/samples/testng/gradlew.bat deleted file mode 100644 index 107acd32c..000000000 --- a/samples/testng/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/samples/testng/settings.gradle b/samples/testng/settings.gradle deleted file mode 100644 index e69de29bb..000000000 diff --git a/samples/testng/src/docs/asciidoc/index.adoc b/samples/testng/src/docs/asciidoc/index.adoc deleted file mode 100644 index ea8b47e49..000000000 --- a/samples/testng/src/docs/asciidoc/index.adoc +++ /dev/null @@ -1,22 +0,0 @@ -= Spring REST Docs TestNG Sample -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs - -Sample application demonstrating how to use Spring REST Docs with TestNG. - -`SampleTestNgApplicationTests` makes a call to a very simple service and produces three -documentation snippets. - -One showing how to make a request using cURL: - -include::{snippets}/sample/curl-request.adoc[] - -One showing the HTTP request: - -include::{snippets}/sample/http-request.adoc[] - -And one showing the HTTP response: - -include::{snippets}/sample/http-response.adoc[] \ No newline at end of file diff --git a/samples/testng/src/main/java/com/example/testng/SampleTestNgApplication.java b/samples/testng/src/main/java/com/example/testng/SampleTestNgApplication.java deleted file mode 100644 index f0c6ab91a..000000000 --- a/samples/testng/src/main/java/com/example/testng/SampleTestNgApplication.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2014-2016 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.testng; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@SpringBootApplication -public class SampleTestNgApplication { - - public static void main(String[] args) { - new SpringApplication(SampleTestNgApplication.class).run(args); - } - - @RestController - private static class SampleController { - - @RequestMapping("/") - public String index() { - return "Hello, World"; - } - - } - -} diff --git a/samples/testng/src/test/java/com/example/testng/SampleTestNgApplicationTests.java b/samples/testng/src/test/java/com/example/testng/SampleTestNgApplicationTests.java deleted file mode 100644 index 1e0843b74..000000000 --- a/samples/testng/src/test/java/com/example/testng/SampleTestNgApplicationTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2014-2016 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.testng; - -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.lang.reflect.Method; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.restdocs.ManualRestDocumentation; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -@SpringBootTest -public class SampleTestNgApplicationTests extends AbstractTestNGSpringContextTests { - - private final ManualRestDocumentation restDocumentation = new ManualRestDocumentation(); - - @Autowired - private WebApplicationContext context; - - private MockMvc mockMvc; - - @BeforeMethod - public void setUp(Method method) { - this.mockMvc = MockMvcBuilders.webAppContextSetup(context) - .apply(documentationConfiguration(this.restDocumentation)).build(); - this.restDocumentation.beforeTest(getClass(), method.getName()); - } - - @AfterMethod - public void tearDown() { - this.restDocumentation.afterTest(); - } - - @Test - public void sample() throws Exception { - this.mockMvc.perform(get("/")) - .andExpect(status().isOk()) - .andDo(document("sample")); - } - -} diff --git a/samples/web-test-client/build.gradle b/samples/web-test-client/build.gradle deleted file mode 100644 index 09678b59d..000000000 --- a/samples/web-test-client/build.gradle +++ /dev/null @@ -1,60 +0,0 @@ -plugins { - id "org.asciidoctor.jvm.convert" version "3.3.2" -} - -apply plugin: 'java' -apply plugin: 'eclipse' - -repositories { - maven { url 'https://repo.spring.io/milestone' } - maven { url 'https://repo.spring.io/snapshot' } - mavenCentral() - mavenLocal() -} - -group = 'com.example' - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -ext { - snippetsDir = file('build/generated-snippets') -} - -ext['spring-restdocs.version'] = '2.0.7.BUILD-SNAPSHOT' - -configurations { - asciidoctorExtensions -} - -dependencies { - asciidoctorExtensions "org.springframework.restdocs:spring-restdocs-asciidoctor:${project.ext['spring-restdocs.version']}" - - implementation 'io.projectreactor.netty:reactor-netty-http:1.0.15' - implementation 'org.springframework:spring-context:5.3.14' - implementation 'org.springframework:spring-webflux:5.3.14' - - testImplementation 'junit:junit:4.13.1' - testImplementation 'org.springframework:spring-test:5.3.14' - testImplementation "org.springframework.restdocs:spring-restdocs-webtestclient:${project.ext['spring-restdocs.version']}" -} - -test { - outputs.dir snippetsDir -} - -asciidoctor { - configurations "asciidoctorExtensions" - inputs.dir snippetsDir - dependsOn test -} - -jar { - dependsOn asciidoctor - from ("${asciidoctor.outputDir}/html5") { - into 'static/docs' - } -} - -eclipseJdt.onlyIf { false } -cleanEclipseJdt.onlyIf { false } diff --git a/samples/web-test-client/gradle/wrapper/gradle-wrapper.jar b/samples/web-test-client/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 0d4a95168..000000000 Binary files a/samples/web-test-client/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/samples/web-test-client/gradle/wrapper/gradle-wrapper.properties b/samples/web-test-client/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 442d9132e..000000000 --- a/samples/web-test-client/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/samples/web-test-client/gradlew b/samples/web-test-client/gradlew deleted file mode 100755 index cccdd3d51..000000000 --- a/samples/web-test-client/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/samples/web-test-client/gradlew.bat b/samples/web-test-client/gradlew.bat deleted file mode 100644 index f9553162f..000000000 --- a/samples/web-test-client/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/samples/web-test-client/settings.gradle b/samples/web-test-client/settings.gradle deleted file mode 100644 index e69de29bb..000000000 diff --git a/samples/web-test-client/src/docs/asciidoc/index.adoc b/samples/web-test-client/src/docs/asciidoc/index.adoc deleted file mode 100644 index fde62fd3d..000000000 --- a/samples/web-test-client/src/docs/asciidoc/index.adoc +++ /dev/null @@ -1,33 +0,0 @@ -= Spring REST Docs WebTestClient Sample -Andy Wilkinson; -:doctype: book -:icons: font -:source-highlighter: highlightjs - -Sample application demonstrating how to use Spring REST Docs with Spring Framework's -WebTestClient. - -`SampleWebTestClientApplicationTests` makes a call to a very simple service. Six -snippets are produced. One showing how to make a request using cURL: - -include::{snippets}/sample/curl-request.adoc[] - -One showing how to make a request using HTTPie: - -include::{snippets}/sample/httpie-request.adoc[] - -One showing the HTTP request: - -include::{snippets}/sample/http-request.adoc[] - -One showing the request body: - -include::{snippets}/sample/request-body.adoc[] - -One showing the HTTP response: - -include::{snippets}/sample/http-response.adoc[] - -And one showing the response body: - -include::{snippets}/sample/response-body.adoc[] \ No newline at end of file diff --git a/samples/web-test-client/src/main/java/com/example/webtestclient/SampleWebTestClientApplication.java b/samples/web-test-client/src/main/java/com/example/webtestclient/SampleWebTestClientApplication.java deleted file mode 100644 index d44ad9118..000000000 --- a/samples/web-test-client/src/main/java/com/example/webtestclient/SampleWebTestClientApplication.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2014-2022 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.webtestclient; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; -import org.springframework.web.reactive.config.EnableWebFlux; -import org.springframework.web.reactive.function.server.RequestPredicates; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; - -import reactor.netty.http.server.HttpServer; - -@EnableWebFlux -@Configuration -public class SampleWebTestClientApplication { - - @Bean - public RouterFunction routerFunction() { - return RouterFunctions.route(RequestPredicates.GET("/"), (request) -> ServerResponse.status(HttpStatus.OK).bodyValue("Hello, World")); - } - - public static void main(String[] args) { - @SuppressWarnings("resource") - ApplicationContext context = new AnnotationConfigApplicationContext(SampleWebTestClientApplication.class); - RouterFunction routerFunction = context.getBean(RouterFunction.class); - ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(RouterFunctions.toHttpHandler(routerFunction)); - HttpServer httpServer = HttpServer.create().handle(adapter); - httpServer.bindNow(); - } - -} diff --git a/samples/web-test-client/src/test/java/com/example/webtestclient/SampleWebTestClientApplicationTests.java b/samples/web-test-client/src/test/java/com/example/webtestclient/SampleWebTestClientApplicationTests.java deleted file mode 100644 index 47e2ffc00..000000000 --- a/samples/web-test-client/src/test/java/com/example/webtestclient/SampleWebTestClientApplicationTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2014-2022 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.webtestclient; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.reactive.server.WebTestClient; - -import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; -import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = SampleWebTestClientApplication.class) -public class SampleWebTestClientApplicationTests { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - @Autowired - ApplicationContext context; - - private WebTestClient webTestClient; - - @Before - public void setUp() { - this.webTestClient = WebTestClient.bindToApplicationContext(context) - .configureClient().baseUrl("https://api.example.com") - .filter(documentationConfiguration(restDocumentation)) - .build(); - } - - @Test - public void sample() { - this.webTestClient.get().uri("/").exchange() - .expectStatus().isOk().expectBody() - .consumeWith(document("sample")); - } - -} diff --git a/settings.gradle b/settings.gradle index 5c45fdb57..fd285ac1a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -2,6 +2,7 @@ pluginManagement { repositories { mavenCentral() gradlePluginPortal() + maven { url = 'https://repo.spring.io/snapshot' } } resolutionStrategy { eachPlugin { @@ -13,30 +14,14 @@ pluginManagement { } plugins { - id "com.gradle.enterprise" version "3.12.5" - id "io.spring.ge.conventions" version "0.0.13" + id "io.spring.develocity.conventions" version "0.0.23" } rootProject.name = "spring-restdocs" -settings.gradle.projectsLoaded { - gradleEnterprise { - buildScan { - settings.gradle.rootProject.getBuildDir().mkdirs() - new File(settings.gradle.rootProject.getBuildDir(), "build-scan-uri.txt").text = "build scan not generated" - buildScanPublished { scan -> - new File(settings.gradle.rootProject.getBuildDir(), "build-scan-uri.txt").text = "<${scan.buildScanUri}|build scan>\n" - } - } - } -} - include "docs" include "spring-restdocs-asciidoctor" -include "spring-restdocs-asciidoctor-1.5" -include "spring-restdocs-asciidoctor-1.6" -include "spring-restdocs-asciidoctor-2.x" -include "spring-restdocs-asciidoctor-support" +include "spring-restdocs-bom" include "spring-restdocs-core" include "spring-restdocs-mockmvc" include "spring-restdocs-platform" diff --git a/spring-restdocs-asciidoctor-1.5/build.gradle b/spring-restdocs-asciidoctor-1.5/build.gradle deleted file mode 100644 index 05dfb19a3..000000000 --- a/spring-restdocs-asciidoctor-1.5/build.gradle +++ /dev/null @@ -1,19 +0,0 @@ -plugins { - id "java" -} - -description = "AsciidoctorJ 1.5 extensions for Spring REST Docs" - -dependencies { - compileOnly("org.asciidoctor:asciidoctorj:$asciidoctorj15Version") - - implementation(project(":spring-restdocs-asciidoctor-support")) - - internal(platform(project(":spring-restdocs-platform"))) - - testImplementation("junit:junit") - testImplementation("org.asciidoctor:asciidoctorj:$asciidoctorj15Version") - testImplementation("org.assertj:assertj-core") - - testRuntimeOnly(project(":spring-restdocs-asciidoctor-support")) -} diff --git a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15Preprocessor.java b/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15Preprocessor.java deleted file mode 100644 index d1dd40181..000000000 --- a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15Preprocessor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2014-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.restdocs.asciidoctor; - -import org.asciidoctor.ast.Document; -import org.asciidoctor.extension.Preprocessor; -import org.asciidoctor.extension.PreprocessorReader; - -/** - * {@link Preprocessor} that sets defaults for REST Docs-related {@link Document} - * attributes. - * - * @author Andy Wilkinson - */ -final class DefaultAttributesAsciidoctorJ15Preprocessor extends Preprocessor { - - private final SnippetsDirectoryResolver snippetsDirectoryResolver = new SnippetsDirectoryResolver(); - - @Override - public PreprocessorReader process(Document document, PreprocessorReader reader) { - document.setAttr("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()), - false); - return reader; - } - -} diff --git a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ15ExtensionRegistry.java b/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ15ExtensionRegistry.java deleted file mode 100644 index 91897ef66..000000000 --- a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ15ExtensionRegistry.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.asciidoctor; - -import org.asciidoctor.Asciidoctor; -import org.asciidoctor.extension.spi.ExtensionRegistry; - -/** - * AsciidoctorJ 1.5 {@link ExtensionRegistry} for Spring REST Docs. - * - * @author Andy Wilkinson - */ -public final class RestDocsAsciidoctorJ15ExtensionRegistry implements ExtensionRegistry { - - @Override - public void register(Asciidoctor asciidoctor) { - if (!asciidoctorJ15()) { - return; - } - asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor()); - asciidoctor.rubyExtensionRegistry() - .loadClass(RestDocsAsciidoctorJ15ExtensionRegistry.class - .getResourceAsStream("/extensions/operation_block_macro.rb")) - .blockMacro("operation", "OperationBlockMacro"); - } - - private boolean asciidoctorJ15() { - try { - return !Class.forName("org.asciidoctor.extension.JavaExtensionRegistry").isInterface(); - } - catch (Throwable ex) { - return false; - } - } - -} diff --git a/spring-restdocs-asciidoctor-1.6/build.gradle b/spring-restdocs-asciidoctor-1.6/build.gradle deleted file mode 100644 index 7a9695a6f..000000000 --- a/spring-restdocs-asciidoctor-1.6/build.gradle +++ /dev/null @@ -1,19 +0,0 @@ -plugins { - id "java" -} - -description = "AsciidoctorJ 1.6 extensions for Spring REST Docs" - -dependencies { - compileOnly("org.asciidoctor:asciidoctorj:$asciidoctorj16Version") - - implementation(project(":spring-restdocs-asciidoctor-support")) - - internal(platform(project(":spring-restdocs-platform"))) - - testImplementation("junit:junit") - testImplementation("org.asciidoctor:asciidoctorj:$asciidoctorj16Version") - testImplementation("org.assertj:assertj-core") - - testRuntimeOnly(project(":spring-restdocs-asciidoctor-support")) -} diff --git a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ16ExtensionRegistry.java b/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ16ExtensionRegistry.java deleted file mode 100644 index 5fec5147e..000000000 --- a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ16ExtensionRegistry.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.asciidoctor; - -import org.asciidoctor.Asciidoctor; -import org.asciidoctor.extension.spi.ExtensionRegistry; - -/** - * AsciidoctorJ 1.6 {@link ExtensionRegistry} for Spring REST Docs. - * - * @author Andy Wilkinson - */ -public final class RestDocsAsciidoctorJ16ExtensionRegistry implements ExtensionRegistry { - - @Override - public void register(Asciidoctor asciidoctor) { - if (!asciidoctorJ16()) { - return; - } - asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor()); - asciidoctor.rubyExtensionRegistry() - .loadClass(RestDocsAsciidoctorJ16ExtensionRegistry.class - .getResourceAsStream("/extensions/operation_block_macro.rb")) - .blockMacro("operation", "OperationBlockMacro"); - } - - private boolean asciidoctorJ16() { - try { - return Class.forName("org.asciidoctor.extension.JavaExtensionRegistry").isInterface(); - } - catch (Throwable ex) { - return false; - } - } - -} diff --git a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java b/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java deleted file mode 100644 index fd03600b7..000000000 --- a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2014-2022 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. - */ - -/** - * Support for Asciidoctor. - */ -package org.springframework.restdocs.asciidoctor; diff --git a/spring-restdocs-asciidoctor-1.6/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16PreprocessorTests.java b/spring-restdocs-asciidoctor-1.6/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16PreprocessorTests.java deleted file mode 100644 index ec91a3394..000000000 --- a/spring-restdocs-asciidoctor-1.6/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16PreprocessorTests.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2014-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.restdocs.asciidoctor; - -import java.io.File; - -import org.asciidoctor.Asciidoctor; -import org.asciidoctor.Attributes; -import org.asciidoctor.Options; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link DefaultAttributesAsciidoctorJ16Preprocessor}. - * - * @author Andy Wilkinson - */ -public class DefaultAttributesAsciidoctorJ16PreprocessorTests { - - @Test - public void snippetsAttributeIsSet() { - String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../..")); - assertThat(converted).contains("build" + File.separatorChar + "generated-snippets"); - } - - @Test - public void snippetsAttributeFromConvertArgumentIsNotOverridden() { - String converted = createAsciidoctor().convert("{snippets}", - createOptions("snippets=custom projectdir=../../..")); - assertThat(converted).contains("custom"); - } - - @Test - public void snippetsAttributeFromDocumentPreambleIsNotOverridden() { - String converted = createAsciidoctor().convert(":snippets: custom\n{snippets}", - createOptions("projectdir=../../..")); - assertThat(converted).contains("custom"); - } - - private Options createOptions(String attributes) { - Options options = new Options(); - options.setAttributes(new Attributes(attributes)); - return options; - } - - private Asciidoctor createAsciidoctor() { - Asciidoctor asciidoctor = Asciidoctor.Factory.create(); - asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor()); - return asciidoctor; - } - -} diff --git a/spring-restdocs-asciidoctor-2.x/build.gradle b/spring-restdocs-asciidoctor-2.x/build.gradle deleted file mode 100644 index bc6361e7f..000000000 --- a/spring-restdocs-asciidoctor-2.x/build.gradle +++ /dev/null @@ -1,18 +0,0 @@ -plugins { - id "java" -} -description = "AsciidoctorJ 2.x extensions for Spring REST Docs" - -dependencies { - compileOnly("org.asciidoctor:asciidoctorj:$asciidoctorj20Version") - - implementation(project(":spring-restdocs-asciidoctor-support")) - - internal(platform(project(":spring-restdocs-platform"))) - - testImplementation("junit:junit") - testImplementation("org.asciidoctor:asciidoctorj:$asciidoctorj20Version") - testImplementation("org.assertj:assertj-core") - - testRuntimeOnly(project(":spring-restdocs-asciidoctor-support")) -} diff --git a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ2xPreprocessor.java b/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ2xPreprocessor.java deleted file mode 100644 index 3ed0a62ca..000000000 --- a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ2xPreprocessor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2014-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.restdocs.asciidoctor; - -import org.asciidoctor.ast.Document; -import org.asciidoctor.extension.Preprocessor; -import org.asciidoctor.extension.PreprocessorReader; - -/** - * {@link Preprocessor} that sets defaults for REST Docs-related {@link Document} - * attributes. - * - * @author Andy Wilkinson - */ -final class DefaultAttributesAsciidoctorJ2xPreprocessor extends Preprocessor { - - private final SnippetsDirectoryResolver snippetsDirectoryResolver = new SnippetsDirectoryResolver(); - - @Override - public void process(Document document, PreprocessorReader reader) { - document.setAttribute("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()), - false); - } - -} diff --git a/spring-restdocs-asciidoctor-2.x/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ2xPreprocessorTests.java b/spring-restdocs-asciidoctor-2.x/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ2xPreprocessorTests.java deleted file mode 100644 index 4bb84aab4..000000000 --- a/spring-restdocs-asciidoctor-2.x/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ2xPreprocessorTests.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2014-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.restdocs.asciidoctor; - -import java.io.File; - -import org.asciidoctor.Asciidoctor; -import org.asciidoctor.Attributes; -import org.asciidoctor.Options; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link DefaultAttributesAsciidoctorJ2xPreprocessor}. - * - * @author Andy Wilkinson - */ -public class DefaultAttributesAsciidoctorJ2xPreprocessorTests { - - @Test - public void snippetsAttributeIsSet() { - String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../..")); - assertThat(converted).contains("build" + File.separatorChar + "generated-snippets"); - } - - @Test - public void snippetsAttributeFromConvertArgumentIsNotOverridden() { - String converted = createAsciidoctor().convert("{snippets}", - createOptions("snippets=custom projectdir=../../..")); - assertThat(converted).contains("custom"); - } - - @Test - public void snippetsAttributeFromDocumentPreambleIsNotOverridden() { - String converted = createAsciidoctor().convert(":snippets: custom\n{snippets}", - createOptions("projectdir=../../..")); - assertThat(converted).contains("custom"); - } - - private Options createOptions(String attributes) { - Options options = new Options(); - options.setAttributes(new Attributes(attributes)); - return options; - } - - private Asciidoctor createAsciidoctor() { - Asciidoctor asciidoctor = Asciidoctor.Factory.create(); - asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ2xPreprocessor()); - return asciidoctor; - } - -} diff --git a/spring-restdocs-asciidoctor-support/build.gradle b/spring-restdocs-asciidoctor-support/build.gradle deleted file mode 100644 index a6ef58c4b..000000000 --- a/spring-restdocs-asciidoctor-support/build.gradle +++ /dev/null @@ -1,12 +0,0 @@ -plugins { - id "java" -} - -description = "Support code for AsciidoctorJ extensions for Spring REST Docs" - -dependencies { - internal(platform(project(":spring-restdocs-platform"))) - - testImplementation("junit:junit") - testImplementation("org.assertj:assertj-core") -} diff --git a/spring-restdocs-asciidoctor/build.gradle b/spring-restdocs-asciidoctor/build.gradle index 5f4bc1f12..f9d1f685d 100644 --- a/spring-restdocs-asciidoctor/build.gradle +++ b/spring-restdocs-asciidoctor/build.gradle @@ -1,53 +1,24 @@ plugins { - id "io.spring.compatibility-test" version "0.0.2" id "java-library" id "maven-publish" } description = "Spring REST Docs Asciidoctor Extension" -configurations { - merge - testRuntimeOnly { extendsFrom merge } -} - dependencies { - internal(platform(project(":spring-restdocs-platform"))) + implementation("org.asciidoctor:asciidoctorj") - merge project(":spring-restdocs-asciidoctor-1.5") - merge project(":spring-restdocs-asciidoctor-1.6") - merge project(":spring-restdocs-asciidoctor-2.x") + internal(platform(project(":spring-restdocs-platform"))) - testImplementation("junit:junit") - testImplementation("org.apache.pdfbox:pdfbox") { - exclude group: "commons-logging", module: "commons-logging" - } - testImplementation("org.asciidoctor:asciidoctorj:1.5.8.1") + testImplementation("org.apache.pdfbox:pdfbox") testImplementation("org.assertj:assertj-core") + testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.springframework:spring-core") testRuntimeOnly("org.asciidoctor:asciidoctorj-pdf") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") } -jar { - dependsOn(":spring-restdocs-asciidoctor-1.5:jar") - dependsOn(":spring-restdocs-asciidoctor-1.6:jar") - dependsOn(":spring-restdocs-asciidoctor-2.x:jar") - from configurations.merge.collect { file -> zipTree(file) } -} - -compatibilityTest { - dependency('AsciidoctorJ') { asciidoctorJ -> - asciidoctorJ.groupId = "org.asciidoctor" - asciidoctorJ.artifactId = "asciidoctorj" - asciidoctorJ.versions = [ - asciidoctorj16Version, - asciidoctorj20Version, - asciidoctorj21Version, - asciidoctorj22Version, - asciidoctorj23Version, - asciidoctorj24Version, - asciidoctorj25Version, - ] - } +tasks.named("test") { + useJUnitPlatform() } diff --git a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16Preprocessor.java b/spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessor.java similarity index 82% rename from spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16Preprocessor.java rename to spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessor.java index 409cf658c..7fa6ce5df 100644 --- a/spring-restdocs-asciidoctor-1.6/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ16Preprocessor.java +++ b/spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -19,6 +19,7 @@ import org.asciidoctor.ast.Document; import org.asciidoctor.extension.Preprocessor; import org.asciidoctor.extension.PreprocessorReader; +import org.asciidoctor.extension.Reader; /** * {@link Preprocessor} that sets defaults for REST Docs-related {@link Document} @@ -26,14 +27,15 @@ * * @author Andy Wilkinson */ -final class DefaultAttributesAsciidoctorJ16Preprocessor extends Preprocessor { +final class DefaultAttributesPreprocessor extends Preprocessor { private final SnippetsDirectoryResolver snippetsDirectoryResolver = new SnippetsDirectoryResolver(); @Override - public void process(Document document, PreprocessorReader reader) { + public Reader process(Document document, PreprocessorReader reader) { document.setAttribute("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()), false); + return reader; } } diff --git a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ2xExtensionRegistry.java b/spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsExtensionRegistry.java similarity index 76% rename from spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ2xExtensionRegistry.java rename to spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsExtensionRegistry.java index a64d4b58c..0a58a7cf9 100644 --- a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsAsciidoctorJ2xExtensionRegistry.java +++ b/spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/RestDocsExtensionRegistry.java @@ -20,18 +20,17 @@ import org.asciidoctor.jruby.extension.spi.ExtensionRegistry; /** - * AsciidoctorJ 2.x {@link ExtensionRegistry} for Spring REST Docs. + * {@link ExtensionRegistry} for Spring REST Docs. * * @author Andy Wilkinson */ -public final class RestDocsAsciidoctorJ2xExtensionRegistry implements ExtensionRegistry { +public final class RestDocsExtensionRegistry implements ExtensionRegistry { @Override public void register(Asciidoctor asciidoctor) { - asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ2xPreprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesPreprocessor()); asciidoctor.rubyExtensionRegistry() - .loadClass(RestDocsAsciidoctorJ2xExtensionRegistry.class - .getResourceAsStream("/extensions/operation_block_macro.rb")) + .loadClass(RestDocsExtensionRegistry.class.getResourceAsStream("/extensions/operation_block_macro.rb")) .blockMacro("operation", "OperationBlockMacro"); } diff --git a/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java b/spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java similarity index 88% rename from spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java rename to spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java index 87c83cade..dfbb957a8 100644 --- a/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java +++ b/spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2021 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. @@ -25,8 +25,7 @@ /** * Resolves the directory from which snippets can be read for inclusion in an Asciidoctor - * document. The resolved directory is relative to the {@code docdir} of the Asciidoctor - * document that it being rendered. + * document. The resolved directory is absolute. * * @author Andy Wilkinson */ @@ -41,7 +40,7 @@ File getSnippetsDirectory(Map attributes) { private File getMavenSnippetsDirectory(Map attributes) { Path docdir = Paths.get(getRequiredAttribute(attributes, "docdir")); - return new File(docdir.relativize(findPom(docdir).getParent()).toFile(), "target/generated-snippets"); + return new File(findPom(docdir).getParent().toFile(), "target/generated-snippets").getAbsoluteFile(); } private Path findPom(Path docdir) { @@ -58,7 +57,8 @@ private Path findPom(Path docdir) { private File getGradleSnippetsDirectory(Map attributes) { return new File(getRequiredAttribute(attributes, "gradle-projectdir", - () -> getRequiredAttribute(attributes, "projectdir")), "build/generated-snippets"); + () -> getRequiredAttribute(attributes, "projectdir")), "build/generated-snippets") + .getAbsoluteFile(); } private String getRequiredAttribute(Map attributes, String name) { diff --git a/spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java b/spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java similarity index 100% rename from spring-restdocs-asciidoctor-1.5/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java rename to spring-restdocs-asciidoctor/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java diff --git a/spring-restdocs-asciidoctor/src/main/resources/META-INF/services/org.asciidoctor.extension.spi.ExtensionRegistry b/spring-restdocs-asciidoctor/src/main/resources/META-INF/services/org.asciidoctor.extension.spi.ExtensionRegistry deleted file mode 100644 index ccdd8d45c..000000000 --- a/spring-restdocs-asciidoctor/src/main/resources/META-INF/services/org.asciidoctor.extension.spi.ExtensionRegistry +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.restdocs.asciidoctor.RestDocsAsciidoctorJ15ExtensionRegistry -org.springframework.restdocs.asciidoctor.RestDocsAsciidoctorJ16ExtensionRegistry diff --git a/spring-restdocs-asciidoctor/src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry b/spring-restdocs-asciidoctor/src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry index 249b935ab..7123d5b51 100644 --- a/spring-restdocs-asciidoctor/src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry +++ b/spring-restdocs-asciidoctor/src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry @@ -1 +1 @@ -org.springframework.restdocs.asciidoctor.RestDocsAsciidoctorJ2xExtensionRegistry +org.springframework.restdocs.asciidoctor.RestDocsExtensionRegistry diff --git a/spring-restdocs-asciidoctor-support/src/main/resources/extensions/operation_block_macro.rb b/spring-restdocs-asciidoctor/src/main/resources/extensions/operation_block_macro.rb similarity index 100% rename from spring-restdocs-asciidoctor-support/src/main/resources/extensions/operation_block_macro.rb rename to spring-restdocs-asciidoctor/src/main/resources/extensions/operation_block_macro.rb diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java index d9039f862..d6df5f917 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/AbstractOperationBlockMacroTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -34,13 +34,11 @@ import org.asciidoctor.Asciidoctor; import org.asciidoctor.Attributes; import org.asciidoctor.Options; -import org.asciidoctor.OptionsBuilder; import org.asciidoctor.SafeMode; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.util.FileSystemUtils; @@ -52,42 +50,42 @@ * @author Gerrit Meier * @author Andy Wilkinson */ -public abstract class AbstractOperationBlockMacroTests { +abstract class AbstractOperationBlockMacroTests { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + private final Asciidoctor asciidoctor = Asciidoctor.Factory.create(); - private Options options; + @TempDir + protected File temp; - private final Asciidoctor asciidoctor = Asciidoctor.Factory.create(); + private Options options; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { prepareOperationSnippets(getBuildOutputLocation()); - this.options = OptionsBuilder.options().safe(SafeMode.UNSAFE).baseDir(getSourceLocation()).get(); + this.options = Options.builder().safe(SafeMode.UNSAFE).baseDir(getSourceLocation()).build(); this.options.setAttributes(getAttributes()); CapturingLogHandler.clear(); } - @After - public void verifyLogging() { + @AfterEach + void verifyLogging() { assertThat(CapturingLogHandler.getLogRecords()).isEmpty(); } - public void prepareOperationSnippets(File buildOutputLocation) throws IOException { + private void prepareOperationSnippets(File buildOutputLocation) throws IOException { File destination = new File(buildOutputLocation, "generated-snippets/some-operation"); destination.mkdirs(); FileSystemUtils.copyRecursively(new File("src/test/resources/some-operation"), destination); } @Test - public void codeBlockSnippetInclude() throws Exception { + void codeBlockSnippetInclude() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-simple")); } @Test - public void operationWithParameterizedName() throws Exception { + void operationWithParameterizedName() throws Exception { Attributes attributes = getAttributes(); attributes.setAttribute("name", "some"); this.options.setAttributes(attributes); @@ -96,20 +94,20 @@ public void operationWithParameterizedName() throws Exception { } @Test - public void codeBlockSnippetIncludeWithPdfBackend() throws Exception { + void codeBlockSnippetIncludeWithPdfBackend() throws Exception { File output = configurePdfOutput(); this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", this.options); assertThat(extractStrings(output)).containsExactly("Curl request", "$ curl 'http://localhost:8080/' -i", "1"); } @Test - public void tableSnippetInclude() throws Exception { + void tableSnippetInclude() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-table")); } @Test - public void tableSnippetIncludeWithPdfBackend() throws Exception { + void tableSnippetIncludeWithPdfBackend() throws Exception { File output = configurePdfOutput(); this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", this.options); assertThat(extractStrings(output)).containsExactly("Response fields", "Path", "Type", "Description", "a", @@ -117,14 +115,14 @@ public void tableSnippetIncludeWithPdfBackend() throws Exception { } @Test - public void includeSnippetInSection() throws Exception { + void includeSnippetInSection() throws Exception { String result = this.asciidoctor.convert("= A\n:doctype: book\n:sectnums:\n\nAlpha\n\n== B\n\nBravo\n\n" + "operation::some-operation[snippets='curl-request']\n\n== C\n", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-in-section")); } @Test - public void includeSnippetInSectionWithAbsoluteLevelOffset() throws Exception { + void includeSnippetInSectionWithAbsoluteLevelOffset() throws Exception { String result = this.asciidoctor .convert("= A\n:doctype: book\n:sectnums:\n:leveloffset: 1\n\nAlpha\n\n= B\n\nBravo\n\n" + "operation::some-operation[snippets='curl-request']\n\n= C\n", this.options); @@ -132,7 +130,7 @@ public void includeSnippetInSectionWithAbsoluteLevelOffset() throws Exception { } @Test - public void includeSnippetInSectionWithRelativeLevelOffset() throws Exception { + void includeSnippetInSectionWithRelativeLevelOffset() throws Exception { String result = this.asciidoctor .convert("= A\n:doctype: book\n:sectnums:\n:leveloffset: +1\n\nAlpha\n\n= B\n\nBravo\n\n" + "operation::some-operation[snippets='curl-request']\n\n= C\n", this.options); @@ -140,7 +138,7 @@ public void includeSnippetInSectionWithRelativeLevelOffset() throws Exception { } @Test - public void includeSnippetInSectionWithPdfBackend() throws Exception { + void includeSnippetInSectionWithPdfBackend() throws Exception { File output = configurePdfOutput(); this.asciidoctor.convert("== Section\n" + "operation::some-operation[snippets='curl-request']", this.options); assertThat(extractStrings(output)).containsExactly("Section", "Curl request", @@ -148,26 +146,26 @@ public void includeSnippetInSectionWithPdfBackend() throws Exception { } @Test - public void includeMultipleSnippets() throws Exception { + void includeMultipleSnippets() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[snippets='curl-request,http-request']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("multiple-snippets")); } @Test - public void useMacroWithoutSnippetAttributeAddsAllSnippets() throws Exception { + void useMacroWithoutSnippetAttributeAddsAllSnippets() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[]", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets")); } @Test - public void useMacroWithEmptySnippetAttributeAddsAllSnippets() throws Exception { + void useMacroWithEmptySnippetAttributeAddsAllSnippets() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[snippets=]", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets")); } @Test - public void includingMissingSnippetAddsWarning() throws Exception { + void includingMissingSnippetAddsWarning() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[snippets='missing-snippet']", this.options); assertThat(result).startsWith(getExpectedContentFromFile("missing-snippet")); assertThat(CapturingLogHandler.getLogRecords()).hasSize(1); @@ -178,13 +176,13 @@ public void includingMissingSnippetAddsWarning() throws Exception { } @Test - public void defaultTitleIsProvidedForCustomSnippet() throws Exception { + void defaultTitleIsProvidedForCustomSnippet() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[snippets='custom-snippet']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("custom-snippet-default-title")); } @Test - public void missingOperationIsHandledGracefully() throws Exception { + void missingOperationIsHandledGracefully() throws Exception { String result = this.asciidoctor.convert("operation::missing-operation[]", this.options); assertThat(result).startsWith(getExpectedContentFromFile("missing-operation")); assertThat(CapturingLogHandler.getLogRecords()).hasSize(1); @@ -195,14 +193,14 @@ public void missingOperationIsHandledGracefully() throws Exception { } @Test - public void titleOfBuiltInSnippetCanBeCustomizedUsingDocumentAttribute() throws URISyntaxException, IOException { + void titleOfBuiltInSnippetCanBeCustomizedUsingDocumentAttribute() throws URISyntaxException, IOException { String result = this.asciidoctor.convert(":operation-curl-request-title: Example request\n" + "operation::some-operation[snippets='curl-request']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("built-in-snippet-custom-title")); } @Test - public void titleOfCustomSnippetCanBeCustomizedUsingDocumentAttribute() throws Exception { + void titleOfCustomSnippetCanBeCustomizedUsingDocumentAttribute() throws Exception { String result = this.asciidoctor.convert(":operation-custom-snippet-title: Customized title\n" + "operation::some-operation[snippets='custom-snippet']", this.options); assertThat(result).isEqualTo(getExpectedContentFromFile("custom-snippet-custom-title")); diff --git a/spring-restdocs-asciidoctor-1.5/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15PreprocessorTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessorTests.java similarity index 76% rename from spring-restdocs-asciidoctor-1.5/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15PreprocessorTests.java rename to spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessorTests.java index 1dcd91531..b5921dbaa 100644 --- a/spring-restdocs-asciidoctor-1.5/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesAsciidoctorJ15PreprocessorTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -21,46 +21,46 @@ import org.asciidoctor.Asciidoctor; import org.asciidoctor.Attributes; import org.asciidoctor.Options; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** - * Tests for {@link DefaultAttributesAsciidoctorJ15Preprocessor}. + * Tests for {@link DefaultAttributesPreprocessor}. * * @author Andy Wilkinson */ -public class DefaultAttributesAsciidoctorJ15PreprocessorTests { +class DefaultAttributesPreprocessorTests { @Test - public void snippetsAttributeIsSet() { + void snippetsAttributeIsSet() { String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../..")); assertThat(converted).contains("build" + File.separatorChar + "generated-snippets"); } @Test - public void snippetsAttributeFromConvertArgumentIsNotOverridden() { + void snippetsAttributeFromConvertArgumentIsNotOverridden() { String converted = createAsciidoctor().convert("{snippets}", createOptions("snippets=custom projectdir=../../..")); assertThat(converted).contains("custom"); } @Test - public void snippetsAttributeFromDocumentPreambleIsNotOverridden() { + void snippetsAttributeFromDocumentPreambleIsNotOverridden() { String converted = createAsciidoctor().convert(":snippets: custom\n{snippets}", createOptions("projectdir=../../..")); assertThat(converted).contains("custom"); } private Options createOptions(String attributes) { - Options options = new Options(); - options.setAttributes(new Attributes(attributes)); + Options options = Options.builder().build(); + options.setAttributes(Attributes.builder().arguments(attributes).build()); return options; } private Asciidoctor createAsciidoctor() { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); - asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor()); + asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesPreprocessor()); return asciidoctor; } diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java index 04eddf354..1ed21adb9 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/GradleOperationBlockMacroTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -19,45 +19,42 @@ import java.io.File; import org.asciidoctor.Attributes; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.ValueSource; /** * Tests for Ruby operation block macro when used in a Gradle build. * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class GradleOperationBlockMacroTests extends AbstractOperationBlockMacroTests { +@ParameterizedClass +@ValueSource(strings = { "projectdir", "gradle-projectdir" }) +class GradleOperationBlockMacroTests extends AbstractOperationBlockMacroTests { private final String attributeName; - public GradleOperationBlockMacroTests(String attributeName) { + GradleOperationBlockMacroTests(String attributeName) { this.attributeName = attributeName; } - @Parameters(name = "{0}") - public static Object[] parameters() { - return new Object[] { "projectdir", "gradle-projectdir" }; - } - + @Override protected Attributes getAttributes() { - Attributes attributes = new Attributes(); - attributes.setAttribute(this.attributeName, new File(temp.getRoot(), "gradle-project").getAbsolutePath()); + Attributes attributes = Attributes.builder() + .attribute(this.attributeName, new File(this.temp, "gradle-project").getAbsolutePath()) + .build(); return attributes; } @Override protected File getBuildOutputLocation() { - File outputLocation = new File(temp.getRoot(), "gradle-project/build"); + File outputLocation = new File(this.temp, "gradle-project/build"); outputLocation.mkdirs(); return outputLocation; } @Override protected File getSourceLocation() { - File sourceLocation = new File(temp.getRoot(), "gradle-project/src/docs/asciidoc"); + File sourceLocation = new File(this.temp, "gradle-project/src/docs/asciidoc"); if (!sourceLocation.exists()) { sourceLocation.mkdirs(); } diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java index 0738144c1..f02f326f9 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/MavenOperationBlockMacroTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -20,32 +20,32 @@ import java.io.IOException; import org.asciidoctor.Attributes; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; /** * Tests for Ruby operation block macro when used in a Maven build. * * @author Andy Wilkinson */ -public class MavenOperationBlockMacroTests extends AbstractOperationBlockMacroTests { +class MavenOperationBlockMacroTests extends AbstractOperationBlockMacroTests { - @Before - public void setMavenHome() { + @BeforeEach + void setMavenHome() { System.setProperty("maven.home", "maven-home"); } - @After - public void clearMavenHome() { + @AfterEach + void clearMavenHome() { System.clearProperty("maven.home"); } + @Override protected Attributes getAttributes() { try { File sourceLocation = getSourceLocation(); new File(sourceLocation.getParentFile().getParentFile().getParentFile(), "pom.xml").createNewFile(); - Attributes attributes = new Attributes(); - attributes.setAttribute("docdir", sourceLocation.getAbsolutePath()); + Attributes attributes = Attributes.builder().attribute("docdir", sourceLocation.getAbsolutePath()).build(); return attributes; } catch (IOException ex) { @@ -55,14 +55,14 @@ protected Attributes getAttributes() { @Override protected File getBuildOutputLocation() { - File outputLocation = new File(temp.getRoot(), "maven-project/target"); + File outputLocation = new File(this.temp, "maven-project/target"); outputLocation.mkdirs(); return outputLocation; } @Override protected File getSourceLocation() { - File sourceLocation = new File(temp.getRoot(), "maven-project/src/main/asciidoc"); + File sourceLocation = new File(this.temp, "maven-project/src/main/asciidoc"); if (!sourceLocation.exists()) { sourceLocation.mkdirs(); } diff --git a/spring-restdocs-asciidoctor-support/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java similarity index 80% rename from spring-restdocs-asciidoctor-support/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java rename to spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java index b6cc1b246..9ca213b93 100644 --- a/spring-restdocs-asciidoctor-support/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -21,9 +21,8 @@ import java.util.HashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @@ -35,23 +34,23 @@ */ public class SnippetsDirectoryResolverTests { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + File temp; @Test - public void mavenProjectsUseTargetGeneratedSnippetsRelativeToDocdir() throws IOException { - this.temporaryFolder.newFile("pom.xml"); + public void mavenProjectsUseTargetGeneratedSnippets() throws IOException { + new File(this.temp, "pom.xml").createNewFile(); Map attributes = new HashMap<>(); - attributes.put("docdir", new File(this.temporaryFolder.getRoot(), "src/main/asciidoc").getAbsolutePath()); + attributes.put("docdir", new File(this.temp, "src/main/asciidoc").getAbsolutePath()); File snippetsDirectory = getMavenSnippetsDirectory(attributes); - assertThat(snippetsDirectory).isRelative(); - assertThat(snippetsDirectory).isEqualTo(new File("../../../target/generated-snippets")); + assertThat(snippetsDirectory).isAbsolute(); + assertThat(snippetsDirectory).isEqualTo(new File(this.temp, "target/generated-snippets")); } @Test public void illegalStateExceptionWhenMavenPomCannotBeFound() { Map attributes = new HashMap<>(); - String docdir = new File(this.temporaryFolder.getRoot(), "src/main/asciidoc").getAbsolutePath(); + String docdir = new File(this.temp, "src/main/asciidoc").getAbsolutePath(); attributes.put("docdir", docdir); assertThatIllegalStateException().isThrownBy(() -> getMavenSnippetsDirectory(attributes)) .withMessage("pom.xml not found in '" + docdir + "' or above"); @@ -69,7 +68,8 @@ public void gradleProjectsUseBuildGeneratedSnippetsBeneathGradleProjectdir() { Map attributes = new HashMap<>(); attributes.put("gradle-projectdir", "project/dir"); File snippetsDirectory = new SnippetsDirectoryResolver().getSnippetsDirectory(attributes); - assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets")); + assertThat(snippetsDirectory).isAbsolute(); + assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets").getAbsoluteFile()); } @Test @@ -78,7 +78,8 @@ public void gradleProjectsUseBuildGeneratedSnippetsBeneathGradleProjectdirWhenBo attributes.put("gradle-projectdir", "project/dir"); attributes.put("projectdir", "fallback/dir"); File snippetsDirectory = new SnippetsDirectoryResolver().getSnippetsDirectory(attributes); - assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets")); + assertThat(snippetsDirectory).isAbsolute(); + assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets").getAbsoluteFile()); } @Test @@ -86,7 +87,8 @@ public void gradleProjectsUseBuildGeneratedSnippetsBeneathProjectdirWhenGradlePr Map attributes = new HashMap<>(); attributes.put("projectdir", "project/dir"); File snippetsDirectory = new SnippetsDirectoryResolver().getSnippetsDirectory(attributes); - assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets")); + assertThat(snippetsDirectory).isAbsolute(); + assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets").getAbsoluteFile()); } @Test diff --git a/spring-restdocs-bom/build.gradle b/spring-restdocs-bom/build.gradle new file mode 100644 index 000000000..bd0b4ce5c --- /dev/null +++ b/spring-restdocs-bom/build.gradle @@ -0,0 +1,16 @@ +plugins { + id "java-platform" + id "maven-publish" +} + +description = "Spring REST Docs Bill of Materials" + +dependencies { + constraints { + api(project(":spring-restdocs-asciidoctor")) + api(project(":spring-restdocs-core")) + api(project(":spring-restdocs-mockmvc")) + api(project(":spring-restdocs-restassured")) + api(project(":spring-restdocs-webtestclient")) + } +} \ No newline at end of file diff --git a/spring-restdocs-core/build.gradle b/spring-restdocs-core/build.gradle index d0433fd09..496bb1a39 100644 --- a/spring-restdocs-core/build.gradle +++ b/spring-restdocs-core/build.gradle @@ -1,5 +1,4 @@ plugins { - id "io.spring.compatibility-test" version "0.0.2" id "java-library" id "java-test-fixtures" id "maven-publish" @@ -19,10 +18,10 @@ task jmustacheRepackJar(type: Jar) { repackJar -> repackJar.archiveVersion = jmustacheVersion doLast() { - project.ant { + ant { taskdef name: "jarjar", classname: "com.tonicsystems.jarjar.JarJarTask", classpath: configurations.jarjar.asPath - jarjar(destfile: repackJar.archivePath) { + jarjar(destfile: repackJar.archiveFile.get()) { configurations.jmustache.each { originalJar -> zipfileset(src: originalJar, includes: "**/*.class") } @@ -33,6 +32,8 @@ task jmustacheRepackJar(type: Jar) { repackJar -> } dependencies { + compileOnly("org.apiguardian:apiguardian-api") + implementation("com.fasterxml.jackson.core:jackson-databind") implementation("org.springframework:spring-web") implementation(files(jmustacheRepackJar)) @@ -45,32 +46,39 @@ dependencies { jmustache("com.samskivert:jmustache@jar") optional(platform(project(":spring-restdocs-platform"))) - optional("javax.validation:validation-api") - optional("junit:junit") + optional("jakarta.validation:jakarta.validation-api") optional("org.hibernate.validator:hibernate-validator") optional("org.junit.jupiter:junit-jupiter-api") - + testFixturesApi(platform(project(":spring-restdocs-platform"))) - testFixturesApi("junit:junit") testFixturesApi("org.assertj:assertj-core") - testFixturesApi("org.hamcrest:hamcrest-core") + testFixturesApi("org.junit.jupiter:junit-jupiter") + testFixturesApi("org.mockito:mockito-core") + + testFixturesCompileOnly("org.apiguardian:apiguardian-api") + testFixturesImplementation(files(jmustacheRepackJar)) testFixturesImplementation("org.hamcrest:hamcrest-library") + testFixturesImplementation("org.mockito:mockito-core") testFixturesImplementation("org.springframework:spring-core") testFixturesImplementation("org.springframework:spring-web") + + testFixturesRuntimeOnly("org.junit.platform:junit-platform-launcher") + + testCompileOnly("org.apiguardian:apiguardian-api") - testImplementation("junit:junit") testImplementation("org.assertj:assertj-core") testImplementation("org.javamoney:moneta") testImplementation("org.mockito:mockito-core") testImplementation("org.springframework:spring-test") - testRuntimeOnly("org.glassfish:javax.el:3.0.0") + testRuntimeOnly("org.apache.tomcat.embed:tomcat-embed-el") + testRuntimeOnly("org.junit.platform:junit-platform-engine") } jar { dependsOn jmustacheRepackJar - from(zipTree(jmustacheRepackJar.archivePath)) { + from(zipTree(jmustacheRepackJar.archiveFile.get())) { include "org/springframework/restdocs/**" } } @@ -83,9 +91,6 @@ components.java.withVariantsFromConfiguration(configurations.testFixturesRuntime skip() } -compatibilityTest { - dependency("Spring Framework") { springFramework -> - springFramework.groupId = "org.springframework" - springFramework.versions = ["5.1.+", "5.2.+", "5.3.+"] - } +tasks.named("test") { + useJUnitPlatform() } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/JUnitRestDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/JUnitRestDocumentation.java deleted file mode 100644 index bbf99d94d..000000000 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/JUnitRestDocumentation.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2014-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.restdocs; - -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * A JUnit {@link TestRule} used to automatically manage the - * {@link RestDocumentationContext}. - * - * @author Andy Wilkinson - * @since 1.1.0 - */ -public class JUnitRestDocumentation implements RestDocumentationContextProvider, TestRule { - - private final ManualRestDocumentation delegate; - - /** - * Creates a new {@code JUnitRestDocumentation} instance that will generate snippets - * to <gradle/maven build path>/generated-snippet. - */ - public JUnitRestDocumentation() { - this.delegate = new ManualRestDocumentation(); - } - - /** - * Creates a new {@code JUnitRestDocumentation} instance that will generate snippets - * to the given {@code outputDirectory}. - * @param outputDirectory the output directory - */ - public JUnitRestDocumentation(String outputDirectory) { - this.delegate = new ManualRestDocumentation(outputDirectory); - } - - @Override - public Statement apply(final Statement base, final Description description) { - return new Statement() { - - @Override - public void evaluate() throws Throwable { - Class testClass = description.getTestClass(); - String methodName = description.getMethodName(); - JUnitRestDocumentation.this.delegate.beforeTest(testClass, methodName); - try { - base.evaluate(); - } - finally { - JUnitRestDocumentation.this.delegate.afterTest(); - } - } - - }; - - } - - @Override - public RestDocumentationContext beforeOperation() { - return this.delegate.beforeOperation(); - } - -} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java index cb56676e5..037189541 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/ManualRestDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -18,13 +18,15 @@ import java.io.File; +import org.junit.jupiter.api.extension.Extension; + /** * {@code ManualRestDocumentation} is used to manually manage the * {@link RestDocumentationContext}. Primarly intended for use with TestNG, but suitable * for use in any environment where manual management of the context is required. *

        - * Users of JUnit should use {@link JUnitRestDocumentation} and take advantage of its - * Rule-based support for automatic management of the context. + * Users of JUnit should use {@link RestDocumentationExtension} and take advantage of its + * {@link Extension}-based support for automatic management of the context. * * @author Andy Wilkinson * @since 1.1.0 diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java index 74f5979b2..efc21ba4e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CliOperationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2025 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. @@ -18,21 +18,19 @@ import java.net.URI; import java.util.Arrays; +import java.util.Base64; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.stream.Collectors; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; -import org.springframework.util.Base64Utils; /** * An {@link OperationRequest} wrapper with methods that are useful when producing a @@ -65,15 +63,6 @@ String getBasicAuthCredentials() { return null; } - Parameters getNonPartParameters() { - Parameters parameters = getParameters(); - Parameters nonPartParameters = new Parameters(); - nonPartParameters.putAll(parameters); - Set partNames = getParts().stream().map(OperationRequestPart::getName).collect(Collectors.toSet()); - nonPartParameters.keySet().removeAll(partNames); - return nonPartParameters; - } - @Override public byte[] getContent() { return this.delegate.getContent(); @@ -87,7 +76,7 @@ public String getContentAsString() { @Override public HttpHeaders getHeaders() { HttpHeaders filteredHeaders = new HttpHeaders(); - for (Entry> header : this.delegate.getHeaders().entrySet()) { + for (Entry> header : this.delegate.getHeaders().headerSet()) { if (allowedHeader(header)) { filteredHeaders.put(header.getKey(), header.getValue()); } @@ -115,11 +104,6 @@ public HttpMethod getMethod() { return this.delegate.getMethod(); } - @Override - public Parameters getParameters() { - return this.delegate.getParameters(); - } - @Override public Collection getParts() { return this.delegate.getParts(); @@ -153,7 +137,7 @@ static boolean isBasicAuthHeader(List value) { } static String decodeBasicAuthHeader(List value) { - return new String(Base64Utils.decodeFromString(value.get(0).substring(6))); + return new String(Base64.getDecoder().decode(value.get(0).substring(6))); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java index 5a3e070da..469973aee 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/CurlRequestSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -22,12 +22,11 @@ import java.util.Map; import java.util.Map.Entry; -import org.springframework.http.HttpMethod; +import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; import org.springframework.restdocs.snippet.Snippet; import org.springframework.restdocs.snippet.TemplatedSnippet; @@ -82,21 +81,9 @@ protected Map createModel(Operation operation) { private String getUrl(Operation operation) { OperationRequest request = operation.getRequest(); - Parameters uniqueParameters = request.getParameters().getUniqueParameters(operation.getRequest().getUri()); - if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) { - return String.format("'%s%s%s'", request.getUri(), - StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", uniqueParameters.toQueryString()); - } return String.format("'%s'", request.getUri()); } - private boolean includeParametersInUri(OperationRequest request) { - HttpMethod method = request.getMethod(); - return (method != HttpMethod.PUT && method != HttpMethod.POST && method != HttpMethod.PATCH) - || (request.getContent().length > 0 && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); - } - private String getOptions(Operation operation) { StringBuilder builder = new StringBuilder(); writeIncludeHeadersInOutputOption(builder); @@ -145,8 +132,12 @@ private void writeHttpMethod(OperationRequest request, StringBuilder builder) { } private void writeHeaders(CliOperationRequest request, List lines) { - for (Entry> entry : request.getHeaders().entrySet()) { + for (Entry> entry : request.getHeaders().headerSet()) { for (String header : entry.getValue()) { + if (StringUtils.hasText(request.getContentAsString()) && HttpHeaders.CONTENT_TYPE.equals(entry.getKey()) + && MediaType.APPLICATION_FORM_URLENCODED.equals(request.getHeaders().getContentType())) { + continue; + } lines.add(String.format("-H '%s: %s'", entry.getKey(), header)); } } @@ -176,24 +167,6 @@ private void writeContent(CliOperationRequest request, List lines) { if (StringUtils.hasText(content)) { lines.add(String.format("-d '%s'", content)); } - else if (!request.getParts().isEmpty()) { - for (Entry> entry : request.getNonPartParameters().entrySet()) { - for (String value : entry.getValue()) { - lines.add(String.format("-F '%s=%s'", entry.getKey(), value)); - } - } - } - else if (request.isPutOrPost()) { - writeContentUsingParameters(request, lines); - } - } - - private void writeContentUsingParameters(OperationRequest request, List lines) { - Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri()); - String queryString = uniqueParameters.toQueryString(); - if (StringUtils.hasText(queryString)) { - lines.add(String.format("-d '%s'", queryString)); - } } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java index 2327f02b4..8b92fa0bf 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cli/HttpieRequestSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -25,12 +25,11 @@ import java.util.Map.Entry; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; +import org.springframework.restdocs.operation.FormParameters; import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; import org.springframework.restdocs.snippet.Snippet; import org.springframework.restdocs.snippet.TemplatedSnippet; @@ -85,6 +84,9 @@ protected Map createModel(Operation operation) { } private Object getContentStandardIn(CliOperationRequest request) { + if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())) { + return ""; + } String content = request.getContentAsString(); if (StringUtils.hasText(content)) { return String.format("echo '%s' | ", content); @@ -102,21 +104,15 @@ private String getOptions(CliOperationRequest request) { } private String getUrl(OperationRequest request) { - Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri()); - if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) { - return String.format("'%s%s%s'", request.getUri(), - StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", uniqueParameters.toQueryString()); - } return String.format("'%s'", request.getUri()); } private String getRequestItems(CliOperationRequest request) { List lines = new ArrayList<>(); - writeFormDataIfNecessary(request, lines); writeHeaders(request, lines); writeCookies(request, lines); - writeParametersIfNecessary(request, lines); + writeFormDataIfNecessary(request, lines); return this.commandFormatter.format(lines); } @@ -125,24 +121,11 @@ private void writeOptions(OperationRequest request, PrintWriter writer) { if (!request.getParts().isEmpty()) { writer.print("--multipart "); } - else if (!request.getParameters().getUniqueParameters(request.getUri()).isEmpty() - && !includeParametersInUri(request) && includeParametersAsFormOptions(request)) { + else if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())) { writer.print("--form "); } } - private boolean includeParametersInUri(OperationRequest request) { - HttpMethod method = request.getMethod(); - return (method != HttpMethod.PUT && method != HttpMethod.POST && method != HttpMethod.PATCH) - || (request.getContent().length > 0 && !MediaType.APPLICATION_FORM_URLENCODED - .isCompatibleWith(request.getHeaders().getContentType())); - } - - private boolean includeParametersAsFormOptions(OperationRequest request) { - return request.getMethod() != HttpMethod.GET && (request.getContent().length == 0 - || !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())); - } - private void writeUserOptionIfNecessary(CliOperationRequest request, PrintWriter writer) { String credentials = request.getBasicAuthCredentials(); if (credentials != null) { @@ -155,23 +138,33 @@ private void writeMethodIfNecessary(OperationRequest request, PrintWriter writer } private void writeFormDataIfNecessary(OperationRequest request, List lines) { - for (OperationRequestPart part : request.getParts()) { - StringBuilder oneLine = new StringBuilder(); - oneLine.append(String.format("'%s'", part.getName())); - if (!StringUtils.hasText(part.getSubmittedFileName())) { - oneLine.append(String.format("='%s'", part.getContentAsString())); - } - else { - oneLine.append(String.format("@'%s'", part.getSubmittedFileName())); - } + if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType())) { + FormParameters.from(request) + .forEach((key, values) -> values.forEach((value) -> lines.add(String.format("'%s=%s'", key, value)))); + } + else { + for (OperationRequestPart part : request.getParts()) { + StringBuilder oneLine = new StringBuilder(); + oneLine.append(String.format("'%s'", part.getName())); + if (!StringUtils.hasText(part.getSubmittedFileName())) { + oneLine.append(String.format("='%s'", part.getContentAsString())); + } + else { + oneLine.append(String.format("@'%s'", part.getSubmittedFileName())); + } - lines.add(oneLine.toString()); + lines.add(oneLine.toString()); + } } } private void writeHeaders(OperationRequest request, List lines) { HttpHeaders headers = request.getHeaders(); - for (Entry> entry : headers.entrySet()) { + for (Entry> entry : headers.headerSet()) { + if (entry.getKey().equals(HttpHeaders.CONTENT_TYPE) + && headers.getContentType().isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) { + continue; + } for (String header : entry.getValue()) { // HTTPie adds Content-Type automatically with --form if (!request.getParts().isEmpty() && entry.getKey().equals(HttpHeaders.CONTENT_TYPE) @@ -189,29 +182,4 @@ private void writeCookies(OperationRequest request, List lines) { } } - private void writeParametersIfNecessary(CliOperationRequest request, List lines) { - if (StringUtils.hasText(request.getContentAsString())) { - return; - } - if (!request.getParts().isEmpty()) { - writeContentUsingParameters(request.getNonPartParameters(), lines); - } - else if (request.isPutOrPost()) { - writeContentUsingParameters(request.getParameters().getUniqueParameters(request.getUri()), lines); - } - } - - private void writeContentUsingParameters(Parameters parameters, List lines) { - for (Map.Entry> entry : parameters.entrySet()) { - if (entry.getValue().isEmpty()) { - lines.add(String.format("'%s='", entry.getKey())); - } - else { - for (String value : entry.getValue()) { - lines.add(String.format("'%s=%s'", entry.getKey(), value)); - } - } - } - } - } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java index 46fcfe92b..59788d061 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -20,29 +20,28 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; -import javax.validation.constraints.AssertFalse; -import javax.validation.constraints.AssertTrue; -import javax.validation.constraints.DecimalMax; -import javax.validation.constraints.DecimalMin; -import javax.validation.constraints.Digits; -import javax.validation.constraints.Email; -import javax.validation.constraints.Future; -import javax.validation.constraints.FutureOrPresent; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.Negative; -import javax.validation.constraints.NegativeOrZero; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Null; -import javax.validation.constraints.Past; -import javax.validation.constraints.PastOrPresent; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Positive; -import javax.validation.constraints.PositiveOrZero; -import javax.validation.constraints.Size; - +import jakarta.validation.constraints.AssertFalse; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.DecimalMax; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.Digits; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.Future; +import jakarta.validation.constraints.FutureOrPresent; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Negative; +import jakarta.validation.constraints.NegativeOrZero; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Null; +import jakarta.validation.constraints.Past; +import jakarta.validation.constraints.PastOrPresent; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.PositiveOrZero; +import jakarta.validation.constraints.Size; import org.hibernate.validator.constraints.CodePointLength; import org.hibernate.validator.constraints.CreditCardNumber; import org.hibernate.validator.constraints.Currency; @@ -52,7 +51,6 @@ import org.hibernate.validator.constraints.Mod10Check; import org.hibernate.validator.constraints.Mod11Check; import org.hibernate.validator.constraints.Range; -import org.hibernate.validator.constraints.SafeHtml; import org.hibernate.validator.constraints.URL; import org.springframework.util.PropertyPlaceholderHelper; @@ -63,10 +61,10 @@ * A {@link ConstraintDescriptionResolver} that resolves constraint descriptions from a * {@link ResourceBundle}. The resource bundle's keys are the name of the constraint with * {@code .description} appended. For example, the key for the constraint named - * {@code javax.validation.constraints.NotNull} is - * {@code javax.validation.constraints.NotNull.description}. + * {@code jakarta.validation.constraints.NotNull} is + * {@code jakarta.validation.constraints.NotNull.description}. *

        - * Default descriptions are provided for Bean Validation 2.0's constraints: + * Default descriptions are provided for all of Bean Validation 3.1's constraints: * *

          *
        • {@link AssertFalse} @@ -94,22 +92,19 @@ *
        * *

        - * Default descriptions are also provided for Hibernate Validator's constraints: + * Default descriptions are also provided for the following Hibernate Validator + * constraints: * *

          *
        • {@link CodePointLength} *
        • {@link CreditCardNumber} *
        • {@link Currency} *
        • {@link EAN} - *
        • {@link org.hibernate.validator.constraints.Email} *
        • {@link Length} *
        • {@link LuhnCheck} *
        • {@link Mod10Check} *
        • {@link Mod11Check} - *
        • {@link org.hibernate.validator.constraints.NotBlank} - *
        • {@link org.hibernate.validator.constraints.NotEmpty} *
        • {@link Range} - *
        • {@link SafeHtml} *
        • {@link URL} *
        * diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java index e8e9fecbc..28910a938 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/constraints/ValidatorConstraintResolver.java @@ -19,19 +19,19 @@ import java.util.ArrayList; import java.util.List; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; -import javax.validation.constraints.NotNull; -import javax.validation.metadata.BeanDescriptor; -import javax.validation.metadata.ConstraintDescriptor; -import javax.validation.metadata.PropertyDescriptor; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorFactory; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.metadata.BeanDescriptor; +import jakarta.validation.metadata.ConstraintDescriptor; +import jakarta.validation.metadata.PropertyDescriptor; /** * A {@link ConstraintResolver} that uses a Bean Validation {@link Validator} to resolve * constraints. The name of the constraint is the fully-qualified class name of the * constraint annotation. For example, a {@link NotNull} constraint will be named - * {@code javax.validation.constraints.NotNull}. + * {@code jakarta.validation.constraints.NotNull}. * * @author Andy Wilkinson * diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/AbstractCookiesSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/AbstractCookiesSnippet.java new file mode 100644 index 000000000..19201586b --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/AbstractCookiesSnippet.java @@ -0,0 +1,158 @@ +/* + * Copyright 2014-2022 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.restdocs.cookies; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.springframework.restdocs.operation.Operation; +import org.springframework.restdocs.snippet.TemplatedSnippet; +import org.springframework.util.Assert; + +/** + * Abstract {@link TemplatedSnippet} subclass that provides a base for snippets that + * document a RESTful resource's request or response cookies. + * + * @author Clyde Stubbs + * @author Andy Wilkinson + * @since 3.0 + */ +public abstract class AbstractCookiesSnippet extends TemplatedSnippet { + + private final Map descriptorsByName = new LinkedHashMap<>(); + + private final boolean ignoreUndocumentedCookies; + + /** + * Creates a new {@code AbstractCookiesSnippet} that will produce a snippet named + * {@code -cookies}. The cookies will be documented using the given + * {@code descriptors} and the given {@code attributes} will be included in the model + * during template rendering. + * @param type the type of the cookies + * @param descriptors the cookie descriptors + * @param attributes the additional attributes + * @param ignoreUndocumentedCookies whether undocumented cookies should be ignored + */ + protected AbstractCookiesSnippet(String type, List descriptors, Map attributes, + boolean ignoreUndocumentedCookies) { + super(type + "-cookies", attributes); + for (CookieDescriptor descriptor : descriptors) { + Assert.notNull(descriptor.getName(), "Cookie descriptors must have a name"); + if (!descriptor.isIgnored()) { + Assert.notNull(descriptor.getDescription(), "The descriptor for cookie '" + descriptor.getName() + + "' must either have a description or be marked as ignored"); + } + this.descriptorsByName.put(descriptor.getName(), descriptor); + } + this.ignoreUndocumentedCookies = ignoreUndocumentedCookies; + } + + @Override + protected Map createModel(Operation operation) { + verifyCookieDescriptors(operation); + + Map model = new HashMap<>(); + List> cookies = new ArrayList<>(); + for (CookieDescriptor descriptor : this.descriptorsByName.values()) { + if (!descriptor.isIgnored()) { + cookies.add(createModelForDescriptor(descriptor)); + } + } + model.put("cookies", cookies); + return model; + } + + private void verifyCookieDescriptors(Operation operation) { + Set actualCookies = extractActualCookies(operation); + Set expectedCookies = new HashSet<>(); + for (Entry entry : this.descriptorsByName.entrySet()) { + if (!entry.getValue().isOptional()) { + expectedCookies.add(entry.getKey()); + } + } + Set undocumentedCookies; + if (this.ignoreUndocumentedCookies) { + undocumentedCookies = Collections.emptySet(); + } + else { + undocumentedCookies = new HashSet<>(actualCookies); + undocumentedCookies.removeAll(this.descriptorsByName.keySet()); + } + Set missingCookies = new HashSet<>(expectedCookies); + missingCookies.removeAll(actualCookies); + + if (!undocumentedCookies.isEmpty() || !missingCookies.isEmpty()) { + verificationFailed(undocumentedCookies, missingCookies); + } + } + + /** + * Extracts the names of the cookies from the request or response of the given + * {@code operation}. + * @param operation the operation + * @return the cookie names + */ + protected abstract Set extractActualCookies(Operation operation); + + /** + * Called when the documented cookies do not match the actual cookies. + * @param undocumentedCookies the cookies that were found in the operation but were + * not documented + * @param missingCookies the cookies that were documented but were not found in the + * operation + */ + protected abstract void verificationFailed(Set undocumentedCookies, Set missingCookies); + + /** + * Returns the list of {@link CookieDescriptor CookieDescriptors} that will be used to + * generate the documentation. + * @return the cookie descriptors + */ + protected final Map getCookieDescriptors() { + return this.descriptorsByName; + } + + /** + * Returns whether or not this snippet ignores undocumented cookies. + * @return {@code true} if undocumented cookies are ignored, otherwise {@code false} + */ + protected final boolean isIgnoreUndocumentedCookies() { + return this.ignoreUndocumentedCookies; + } + + /** + * Returns a model for the given {@code descriptor}. + * @param descriptor the descriptor + * @return the model + */ + protected Map createModelForDescriptor(CookieDescriptor descriptor) { + Map model = new HashMap<>(); + model.put("name", descriptor.getName()); + model.put("description", descriptor.getDescription()); + model.put("optional", descriptor.isOptional()); + model.putAll(descriptor.getAttributes()); + return model; + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/CookieDescriptor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/CookieDescriptor.java new file mode 100644 index 000000000..97ee508c8 --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/CookieDescriptor.java @@ -0,0 +1,69 @@ +/* + * Copyright 2014-2022 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.restdocs.cookies; + +import org.springframework.restdocs.snippet.IgnorableDescriptor; + +/** + * A description of a cookie found in a request or response. + * + * @author Clyde Stubbs + * @author Andy Wilkinson + * @since 3.0 + * @see CookieDocumentation#cookieWithName(String) + */ +public class CookieDescriptor extends IgnorableDescriptor { + + private final String name; + + private boolean optional; + + /** + * Creates a new {@code CookieDescriptor} describing the cookie with the given + * {@code name}. + * @param name the name + */ + protected CookieDescriptor(String name) { + this.name = name; + } + + /** + * Marks the cookie as optional. + * @return {@code this} + */ + public final CookieDescriptor optional() { + this.optional = true; + return this; + } + + /** + * Returns the name for the cookie. + * @return the cookie name + */ + public final String getName() { + return this.name; + } + + /** + * Returns {@code true} if the described cookie is optional, otherwise {@code false}. + * @return {@code true} if the described cookie is optional, otherwise {@code false} + */ + public final boolean isOptional() { + return this.optional; + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/CookieDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/CookieDocumentation.java new file mode 100644 index 000000000..20c20f43f --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/CookieDocumentation.java @@ -0,0 +1,316 @@ +/* + * Copyright 2014-2022 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.restdocs.cookies; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.springframework.restdocs.snippet.Snippet; + +/** + * Static factory methods for documenting a RESTful API's request and response cookies. + * + * @author Clyde Stubbs + * @author Andy Wilkinson + * @since 3.0 + */ +public abstract class CookieDocumentation { + + private CookieDocumentation() { + + } + + /** + * Creates a {@code CookieDescriptor} that describes a cookie with the given + * {@code name}. + * @param name the name of the cookie + * @return a {@code CookieDescriptor} ready for further configuration + */ + public static CookieDescriptor cookieWithName(String name) { + return new CookieDescriptor(name); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * request. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the request, + * a failure will also occur. + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet requestCookies(CookieDescriptor... descriptors) { + return requestCookies(Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * request. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the request, + * a failure will also occur. + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet requestCookies(List descriptors) { + return new RequestCookiesSnippet(descriptors); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * request. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * request, a failure will occur. Any undocumented cookies will be ignored. + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet relaxedRequestCookies(CookieDescriptor... descriptors) { + return relaxedRequestCookies(Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * request. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * request, a failure will occur. Any undocumented cookies will be ignored. + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet relaxedRequestCookies(List descriptors) { + return new RequestCookiesSnippet(descriptors, true); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's request. The given {@code attributes} will be available during snippet + * generation and the cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the request, + * a failure will also occur. + * @param attributes the attributes + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet requestCookies(Map attributes, + CookieDescriptor... descriptors) { + return requestCookies(attributes, Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's request. The given {@code attributes} will be available during snippet + * generation and the cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the request, + * a failure will also occur. + * @param attributes the attributes + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet requestCookies(Map attributes, + List descriptors) { + return new RequestCookiesSnippet(descriptors, attributes); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's request. The given {@code attributes} will be available during snippet + * generation and the cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * request, a failure will occur. Any undocumented cookies will be ignored. + * @param attributes the attributes + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet relaxedRequestCookies(Map attributes, + CookieDescriptor... descriptors) { + return relaxedRequestCookies(attributes, Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's request. The given {@code attributes} will be available during snippet + * generation and the cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * request, a failure will occur. Any undocumented cookies will be ignored. + * @param attributes the attributes + * @param descriptors the descriptions of the request's cookies + * @return the snippet that will document the request cookies + * @see #cookieWithName(String) + */ + public static RequestCookiesSnippet relaxedRequestCookies(Map attributes, + List descriptors) { + return new RequestCookiesSnippet(descriptors, attributes, true); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * response. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is present in the response, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the + * response, a failure will also occur. + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet responseCookies(CookieDescriptor... descriptors) { + return responseCookies(Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * response. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is present in the response, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the + * response, a failure will also occur. + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet responseCookies(List descriptors) { + return new ResponseCookiesSnippet(descriptors); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * response. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * response, a failure will occur. Any undocumented cookies will be ignored. + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet relaxedResponseCookies(CookieDescriptor... descriptors) { + return relaxedResponseCookies(Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API operation's + * response. The cookies will be documented using the given {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * response, a failure will occur. Any undocumented cookies will be ignored. + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet relaxedResponseCookies(List descriptors) { + return new ResponseCookiesSnippet(descriptors, true); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's response. The given {@code attributes} will be available during + * snippet generation and the cookies will be documented using the given + * {@code descriptors}. + *

        + * If a cookie is present in the response, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the + * response, a failure will also occur. + * @param attributes the attributes + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet responseCookies(Map attributes, + CookieDescriptor... descriptors) { + return responseCookies(attributes, Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's response. The given {@code attributes} will be available during + * snippet generation and the cookies will be documented using the given + * {@code descriptors}. + *

        + * If a cookie is present in the response, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a + * cookie is documented, is not marked as optional, and is not present in the + * response, a failure will also occur. + * @param attributes the attributes + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet responseCookies(Map attributes, + List descriptors) { + return new ResponseCookiesSnippet(descriptors, attributes); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's response. The given {@code attributes} will be available during + * snippet generation and the cookies will be documented using the given + * {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * response, a failure will occur. Any undocumented cookies will be ignored. + * @param attributes the attributes + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet relaxedResponseCookies(Map attributes, + CookieDescriptor... descriptors) { + return relaxedResponseCookies(attributes, Arrays.asList(descriptors)); + } + + /** + * Returns a new {@link Snippet} that will document the cookies of the API + * operations's response. The given {@code attributes} will be available during + * snippet generation and the cookies will be documented using the given + * {@code descriptors}. + *

        + * If a cookie is documented, is not marked as optional, and is not present in the + * response, a failure will occur. Any undocumented cookies will be ignored. + * @param attributes the attributes + * @param descriptors the descriptions of the response's cookies + * @return the snippet that will document the response cookies + * @see #cookieWithName(String) + */ + public static ResponseCookiesSnippet relaxedResponseCookies(Map attributes, + List descriptors) { + return new ResponseCookiesSnippet(descriptors, attributes, true); + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/RequestCookiesSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/RequestCookiesSnippet.java new file mode 100644 index 000000000..e5f4d5d2a --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/RequestCookiesSnippet.java @@ -0,0 +1,136 @@ +/* + * Copyright 2014-2022 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.restdocs.cookies; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.restdocs.operation.Operation; +import org.springframework.restdocs.operation.RequestCookie; +import org.springframework.restdocs.snippet.Snippet; +import org.springframework.restdocs.snippet.SnippetException; + +/** + * A {@link Snippet} that documents the cookies in a request. + * + * @author Clyde Stubbs + * @author Andy Wilkinson + * @since 3.0 + * @see CookieDocumentation#requestCookies(CookieDescriptor...) + * @see CookieDocumentation#requestCookies(Map, CookieDescriptor...) + */ +public class RequestCookiesSnippet extends AbstractCookiesSnippet { + + /** + * Creates a new {@code RequestCookiesSnippet} that will document the cookies in the + * request using the given {@code descriptors}. + * @param descriptors the descriptors + */ + protected RequestCookiesSnippet(List descriptors) { + this(descriptors, null, false); + } + + /** + * Creates a new {@code RequestCookiesSnippet} that will document the cookies in the + * request using the given {@code descriptors}. If {@code ignoreUndocumentedCookies} + * is {@code true}, undocumented cookies will be ignored and will not trigger a + * failure. + * @param descriptors the descriptors + * @param ignoreUndocumentedCookies whether undocumented cookies should be ignored + */ + protected RequestCookiesSnippet(List descriptors, boolean ignoreUndocumentedCookies) { + this(descriptors, null, ignoreUndocumentedCookies); + } + + /** + * Creates a new {@code RequestCookiesSnippet} that will document the cookies in the + * request using the given {@code descriptors}. The given {@code attributes} will be + * included in the model during template rendering. Undocumented cookies will not be + * ignored. + * @param descriptors the descriptors + * @param attributes the additional attributes + */ + protected RequestCookiesSnippet(List descriptors, Map attributes) { + this(descriptors, attributes, false); + } + + /** + * Creates a new {@code RequestCookiesSnippet} that will document the cookies in the + * request using the given {@code descriptors}. The given {@code attributes} will be + * included in the model during template rendering. + * @param descriptors the descriptors + * @param attributes the additional attributes + * @param ignoreUndocumentedCookies whether undocumented cookies should be ignored + */ + protected RequestCookiesSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedCookies) { + super("request", descriptors, attributes, ignoreUndocumentedCookies); + } + + @Override + protected Set extractActualCookies(Operation operation) { + HashSet actualCookies = new HashSet<>(); + for (RequestCookie cookie : operation.getRequest().getCookies()) { + actualCookies.add(cookie.getName()); + } + return actualCookies; + } + + @Override + protected void verificationFailed(Set undocumentedCookies, Set missingCookies) { + String message = ""; + if (!undocumentedCookies.isEmpty()) { + message += "Cookies with the following names were not documented: " + undocumentedCookies; + } + if (!missingCookies.isEmpty()) { + if (message.length() > 0) { + message += ". "; + } + message += "Cookies with the following names were not found in the request: " + missingCookies; + } + throw new SnippetException(message); + } + + /** + * Returns a new {@code RequestCookiesSnippet} configured with this snippet's + * attributes and its descriptors combined with the given + * {@code additionalDescriptors}. + * @param additionalDescriptors the additional descriptors + * @return the new snippet + */ + public final RequestCookiesSnippet and(CookieDescriptor... additionalDescriptors) { + return and(Arrays.asList(additionalDescriptors)); + } + + /** + * Returns a new {@code RequestCookiesSnippet} configured with this snippet's + * attributes and its descriptors combined with the given + * {@code additionalDescriptors}. + * @param additionalDescriptors the additional descriptors + * @return the new snippet + */ + public final RequestCookiesSnippet and(List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(this.getCookieDescriptors().values()); + combinedDescriptors.addAll(additionalDescriptors); + return new RequestCookiesSnippet(combinedDescriptors, getAttributes(), isIgnoreUndocumentedCookies()); + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/ResponseCookiesSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/ResponseCookiesSnippet.java new file mode 100644 index 000000000..f6a5176f9 --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/ResponseCookiesSnippet.java @@ -0,0 +1,132 @@ +/* + * Copyright 2014-2022 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.restdocs.cookies; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.springframework.restdocs.operation.Operation; +import org.springframework.restdocs.operation.ResponseCookie; +import org.springframework.restdocs.snippet.Snippet; +import org.springframework.restdocs.snippet.SnippetException; + +/** + * A {@link Snippet} that documents the cookies in a response. + * + * @author Clyde Stubbs + * @author Andy Wilkinson + * @since 3.0 + * @see CookieDocumentation#responseCookies(CookieDescriptor...) + * @see CookieDocumentation#responseCookies(Map, CookieDescriptor...) + */ +public class ResponseCookiesSnippet extends AbstractCookiesSnippet { + + /** + * Creates a new {@code ResponseCookiesSnippet} that will document the cookies in the + * response using the given {@code descriptors}. + * @param descriptors the descriptors + */ + protected ResponseCookiesSnippet(List descriptors) { + this(descriptors, null, false); + } + + /** + * Creates a new {@code ResponseCookiesSnippet} that will document the cookies in the + * response using the given {@code descriptors}. If {@code ignoreUndocumentedCookies} + * is {@code true}, undocumented cookies will be ignored and will not trigger a + * failure. + * @param descriptors the descriptors + * @param ignoreUndocumentedCookies whether undocumented cookies should be ignored + */ + protected ResponseCookiesSnippet(List descriptors, boolean ignoreUndocumentedCookies) { + this(descriptors, null, ignoreUndocumentedCookies); + } + + /** + * Creates a new {@code ResponseCookiesSnippet} that will document the cookies in the + * response using the given {@code descriptors}. The given {@code attributes} will be + * included in the model during template rendering. Undocumented cookies will not be + * ignored. + * @param descriptors the descriptors + * @param attributes the additional attributes + */ + protected ResponseCookiesSnippet(List descriptors, Map attributes) { + this(descriptors, attributes, false); + } + + /** + * Creates a new {@code ResponseCookiesSnippet} that will document the cookies in the + * response using the given {@code descriptors}. The given {@code attributes} will be + * included in the model during template rendering. + * @param descriptors the descriptors + * @param attributes the additional attributes + * @param ignoreUndocumentedCookies whether undocumented cookies should be ignored + */ + protected ResponseCookiesSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedCookies) { + super("response", descriptors, attributes, ignoreUndocumentedCookies); + } + + @Override + protected Set extractActualCookies(Operation operation) { + return operation.getResponse().getCookies().stream().map(ResponseCookie::getName).collect(Collectors.toSet()); + } + + @Override + protected void verificationFailed(Set undocumentedCookies, Set missingCookies) { + String message = ""; + if (!undocumentedCookies.isEmpty()) { + message += "Cookies with the following names were not documented: " + undocumentedCookies; + } + if (!missingCookies.isEmpty()) { + if (message.length() > 0) { + message += ". "; + } + message += "Cookies with the following names were not found in the response: " + missingCookies; + } + throw new SnippetException(message); + } + + /** + * Returns a new {@code ResponseCookiesSnippet} configured with this snippet's + * attributes and its descriptors combined with the given + * {@code additionalDescriptors}. + * @param additionalDescriptors the additional descriptors + * @return the new snippet + */ + public final ResponseCookiesSnippet and(CookieDescriptor... additionalDescriptors) { + return and(Arrays.asList(additionalDescriptors)); + } + + /** + * Returns a new {@code ResponseCookiesSnippet} configured with this snippet's + * attributes and its descriptors combined with the given + * {@code additionalDescriptors}. + * @param additionalDescriptors the additional descriptors + * @return the new snippet + */ + public final ResponseCookiesSnippet and(List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(this.getCookieDescriptors().values()); + combinedDescriptors.addAll(additionalDescriptors); + return new ResponseCookiesSnippet(combinedDescriptors, getAttributes(), isIgnoreUndocumentedCookies()); + } + +} diff --git a/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/package-info.java similarity index 84% rename from spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java rename to spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/package-info.java index fd03600b7..afc01d60f 100644 --- a/spring-restdocs-asciidoctor-support/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/cookies/package-info.java @@ -15,6 +15,6 @@ */ /** - * Support for Asciidoctor. + * Documenting the cookies of a RESTful API's requests and responses. */ -package org.springframework.restdocs.asciidoctor; +package org.springframework.restdocs.cookies; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java index e64e7c08b..79d587928 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/RequestHeadersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -57,7 +57,7 @@ protected RequestHeadersSnippet(List descriptors, Map extractActualHeaders(Operation operation) { - return operation.getRequest().getHeaders().keySet(); + return operation.getRequest().getHeaders().headerNames(); } /** diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java index e1acb6812..ea9687e52 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/headers/ResponseHeadersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -57,7 +57,7 @@ protected ResponseHeadersSnippet(List descriptors, Map extractActualHeaders(Operation operation) { - return operation.getResponse().getHeaders().keySet(); + return operation.getResponse().getHeaders().headerNames(); } /** diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java index e25ca7a81..87087b315 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpRequestSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -23,8 +23,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Set; -import java.util.stream.Collectors; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -32,7 +30,6 @@ import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; import org.springframework.restdocs.snippet.Snippet; import org.springframework.restdocs.snippet.TemplatedSnippet; @@ -78,15 +75,6 @@ protected Map createModel(Operation operation) { private String getPath(OperationRequest request) { String path = request.getUri().getRawPath(); String queryString = request.getUri().getRawQuery(); - Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri()); - if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) { - if (StringUtils.hasText(queryString)) { - queryString = queryString + "&" + uniqueParameters.toQueryString(); - } - else { - queryString = uniqueParameters.toQueryString(); - } - } if (StringUtils.hasText(queryString)) { path = path + "?" + queryString; } @@ -103,7 +91,7 @@ private boolean includeParametersInUri(OperationRequest request) { private List> getHeaders(OperationRequest request) { List> headers = new ArrayList<>(); - for (Entry> header : request.getHeaders().entrySet()) { + for (Entry> header : request.getHeaders().headerSet()) { for (String value : header.getValue()) { if (HttpHeaders.CONTENT_TYPE.equals(header.getKey()) && !request.getParts().isEmpty()) { headers.add(header(header.getKey(), String.format("%s; boundary=%s", value, MULTIPART_BOUNDARY))); @@ -115,8 +103,12 @@ private List> getHeaders(OperationRequest request) { } } + List cookies = new ArrayList<>(); for (RequestCookie cookie : request.getCookies()) { - headers.add(header(HttpHeaders.COOKIE, String.format("%s=%s", cookie.getName(), cookie.getValue()))); + cookies.add(String.format("%s=%s", cookie.getName(), cookie.getValue())); + } + if (!cookies.isEmpty()) { + headers.add(header(HttpHeaders.COOKIE, String.join("; ", cookies))); } if (requiresFormEncodingContentTypeHeader(request)) { @@ -132,46 +124,21 @@ private String getRequestBody(OperationRequest request) { if (StringUtils.hasText(content)) { writer.printf("%n%s", content); } - else if (isPutOrPost(request)) { - if (request.getParts().isEmpty()) { - String queryString = request.getParameters().getUniqueParameters(request.getUri()).toQueryString(); - if (StringUtils.hasText(queryString)) { - writer.println(); - writer.print(queryString); - } - } - else { + else if (isPutPostOrPatch(request)) { + if (!request.getParts().isEmpty()) { writeParts(request, writer); } } return httpRequest.toString(); } - private boolean isPutOrPost(OperationRequest request) { - return HttpMethod.PUT.equals(request.getMethod()) || HttpMethod.POST.equals(request.getMethod()); + private boolean isPutPostOrPatch(OperationRequest request) { + return HttpMethod.PUT.equals(request.getMethod()) || HttpMethod.POST.equals(request.getMethod()) + || HttpMethod.PATCH.equals(request.getMethod()); } private void writeParts(OperationRequest request, PrintWriter writer) { writer.println(); - Set partNames = request.getParts() - .stream() - .map(OperationRequestPart::getName) - .collect(Collectors.toSet()); - for (Entry> parameter : request.getParameters().entrySet()) { - if (!partNames.contains(parameter.getKey())) { - if (parameter.getValue().isEmpty()) { - writePartBoundary(writer); - writePart(parameter.getKey(), "", null, null, writer); - } - else { - for (String value : parameter.getValue()) { - writePartBoundary(writer); - writePart(parameter.getKey(), value, null, null, writer); - writer.println(); - } - } - } - } for (OperationRequestPart part : request.getParts()) { writePartBoundary(writer); writePart(part, writer); @@ -207,8 +174,7 @@ private void writeMultipartEnd(PrintWriter writer) { } private boolean requiresFormEncodingContentTypeHeader(OperationRequest request) { - return request.getHeaders().get(HttpHeaders.CONTENT_TYPE) == null && isPutOrPost(request) - && !request.getParameters().getUniqueParameters(request.getUri()).isEmpty() + return request.getHeaders().get(HttpHeaders.CONTENT_TYPE) == null && isPutPostOrPatch(request) && !includeParametersInUri(request); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpResponseSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpResponseSnippet.java index 7e4a9c113..919d312f9 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpResponseSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/http/HttpResponseSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -23,6 +23,7 @@ import java.util.Map.Entry; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.snippet.Snippet; @@ -59,15 +60,9 @@ protected Map createModel(Operation operation) { Map model = new HashMap<>(); model.put("responseBody", responseBody(response)); model.put("headers", headers(response)); - HttpStatus status = response.getStatus(); - if (status != null) { - model.put("statusCode", status.value()); - model.put("statusReason", status.getReasonPhrase()); - } - else { - model.put("statusCode", response.getStatusCode()); - model.put("statusReason", ""); - } + HttpStatusCode status = response.getStatus(); + model.put("statusCode", status.value()); + model.put("statusReason", (status instanceof HttpStatus) ? ((HttpStatus) status).getReasonPhrase() : ""); return model; } @@ -78,7 +73,7 @@ private String responseBody(OperationResponse response) { private List> headers(OperationResponse response) { List> headers = new ArrayList<>(); - for (Entry> header : response.getHeaders().entrySet()) { + for (Entry> header : response.getHeaders().headerSet()) { List values = header.getValue(); for (String value : values) { headers.add(header(header.getKey(), value)); diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java index ef2a9e8ec..bdf5772cb 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -30,6 +30,7 @@ * content type. * * @author Andy Wilkinson + * @author Oliver Drotbohm */ class ContentTypeLinkExtractor implements LinkExtractor { @@ -37,7 +38,10 @@ class ContentTypeLinkExtractor implements LinkExtractor { ContentTypeLinkExtractor() { this.linkExtractors.put(MediaType.APPLICATION_JSON, new AtomLinkExtractor()); - this.linkExtractors.put(HalLinkExtractor.HAL_MEDIA_TYPE, new HalLinkExtractor()); + LinkExtractor halLinkExtractor = new HalLinkExtractor(); + this.linkExtractors.put(HalLinkExtractor.HAL_MEDIA_TYPE, halLinkExtractor); + this.linkExtractors.put(HalLinkExtractor.VND_HAL_MEDIA_TYPE, halLinkExtractor); + this.linkExtractors.put(HalLinkExtractor.HAL_FORMS_MEDIA_TYPE, halLinkExtractor); } ContentTypeLinkExtractor(Map linkExtractors) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HalLinkExtractor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HalLinkExtractor.java index f93c572a7..e56f32ba8 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HalLinkExtractor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/hypermedia/HalLinkExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2025 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. @@ -30,11 +30,16 @@ * format. * * @author Andy Wilkinson + * @author Oliver Drotbohm */ class HalLinkExtractor extends AbstractJsonLinkExtractor { static final MediaType HAL_MEDIA_TYPE = new MediaType("application", "hal+json"); + static final MediaType VND_HAL_MEDIA_TYPE = new MediaType("application", "vnd.hal+json"); + + static final MediaType HAL_FORMS_MEDIA_TYPE = new MediaType("application", "prs.hal-forms+json"); + @Override public Map> extractLinks(Map json) { Map> extractedLinks = new LinkedHashMap<>(); diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryStringParser.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/FormParameters.java similarity index 55% rename from spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryStringParser.java rename to spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/FormParameters.java index 49d637dd3..5cabb84e3 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryStringParser.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/FormParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -17,36 +17,46 @@ package org.springframework.restdocs.operation; import java.io.UnsupportedEncodingException; -import java.net.URI; import java.net.URLDecoder; import java.util.LinkedList; import java.util.List; import java.util.Scanner; +import org.springframework.util.LinkedMultiValueMap; + /** - * A parser for the query string of a URI. + * A request's form parameters, derived from its form URL encoded body content. * * @author Andy Wilkinson + * @since 3.0.0 */ -public class QueryStringParser { +public final class FormParameters extends LinkedMultiValueMap { + + private FormParameters() { + + } /** - * Parses the query string of the given {@code uri} and returns the resulting - * {@link Parameters}. - * @param uri the uri to parse - * @return the parameters parsed from the query string + * Extracts the form parameters from the body of the given {@code request}. If the + * request has no body content, an empty {@code FormParameters} is returned, rather + * than {@code null}. + * @param request the request + * @return the form parameters extracted from the body content */ - public Parameters parse(URI uri) { - String query = uri.getRawQuery(); - if (query != null) { - return parse(query); + public static FormParameters from(OperationRequest request) { + return of(request.getContentAsString()); + } + + private static FormParameters of(String bodyContent) { + if (bodyContent == null || bodyContent.length() == 0) { + return new FormParameters(); } - return new Parameters(); + return parse(bodyContent); } - private Parameters parse(String query) { - Parameters parameters = new Parameters(); - try (Scanner scanner = new Scanner(query)) { + private static FormParameters parse(String bodyContent) { + FormParameters parameters = new FormParameters(); + try (Scanner scanner = new Scanner(bodyContent)) { scanner.useDelimiter("&"); while (scanner.hasNext()) { processParameter(scanner.next(), parameters); @@ -55,7 +65,7 @@ private Parameters parse(String query) { return parameters; } - private void processParameter(String parameter, Parameters parameters) { + private static void processParameter(String parameter, FormParameters parameters) { String[] components = parameter.split("="); if (components.length > 0 && components.length < 3) { if (components.length == 2) { @@ -64,7 +74,7 @@ private void processParameter(String parameter, Parameters parameters) { parameters.add(decode(name), decode(value)); } else { - List values = parameters.computeIfAbsent(components[0], (p) -> new LinkedList()); + List values = parameters.computeIfAbsent(components[0], (p) -> new LinkedList<>()); values.add(""); } } @@ -73,12 +83,12 @@ private void processParameter(String parameter, Parameters parameters) { } } - private String decode(String encoded) { + private static String decode(String encoded) { try { return URLDecoder.decode(encoded, "UTF-8"); } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException("Unable to URL encode " + encoded + " using UTF-8", ex); + throw new IllegalStateException("Unable to URL decode " + encoded + " using UTF-8", ex); } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequest.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequest.java index c8b6fb358..7e36c2f37 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequest.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2022 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. @@ -58,14 +58,6 @@ public interface OperationRequest { */ HttpMethod getMethod(); - /** - * Returns the request's parameters. For a {@code GET} request, the parameters are - * derived from the query string. For a {@code POST} request, the parameters are - * derived form the request's body. - * @return the parameters - */ - Parameters getParameters(); - /** * Returns the request's parts, provided that it is a multipart request. If not, then * an empty {@link Collection} is returned. diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java index 0c4968d62..39d0f5f73 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationRequestFactory.java @@ -17,7 +17,6 @@ package org.springframework.restdocs.operation; import java.net.URI; -import java.net.URISyntaxException; import java.util.Collection; import java.util.Collections; @@ -39,15 +38,15 @@ public class OperationRequestFactory { * @param method the request method * @param content the content of the request * @param headers the request's headers - * @param parameters the request's parameters * @param parts the request's parts * @param cookies the request's cookies * @return the {@code OperationRequest} + * @since 3.0.0 */ public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, - Parameters parameters, Collection parts, Collection cookies) { - return new StandardOperationRequest(uri, method, content, augmentHeaders(headers, uri, content), parameters, - parts, cookies); + Collection parts, Collection cookies) { + return new StandardOperationRequest(uri, method, content, augmentHeaders(headers, uri, content), + (parts != null) ? parts : Collections.emptyList(), cookies); } /** @@ -58,13 +57,13 @@ public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpH * @param method the request method * @param content the content of the request * @param headers the request's headers - * @param parameters the request's parameters * @param parts the request's parts * @return the {@code OperationRequest} + * @since 3.0.0 */ public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, - Parameters parameters, Collection parts) { - return create(uri, method, content, headers, parameters, parts, Collections.emptyList()); + Collection parts) { + return create(uri, method, content, headers, parts, Collections.emptyList()); } /** @@ -77,8 +76,7 @@ public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpH */ public OperationRequest createFrom(OperationRequest original, byte[] newContent) { return new StandardOperationRequest(original.getUri(), original.getMethod(), newContent, - getUpdatedHeaders(original.getHeaders(), newContent), original.getParameters(), original.getParts(), - original.getCookies()); + getUpdatedHeaders(original.getHeaders(), newContent), original.getParts(), original.getCookies()); } /** @@ -90,33 +88,7 @@ public OperationRequest createFrom(OperationRequest original, byte[] newContent) */ public OperationRequest createFrom(OperationRequest original, HttpHeaders newHeaders) { return new StandardOperationRequest(original.getUri(), original.getMethod(), original.getContent(), newHeaders, - original.getParameters(), original.getParts(), original.getCookies()); - } - - /** - * Creates a new {@code OperationRequest} based on the given {@code original} but with - * the given {@code newParameters} applied. The query string of a {@code GET} request - * will be updated to reflect the new parameters. - * @param original the original request - * @param newParameters the new parameters - * @return the new request with the parameters applied - */ - public OperationRequest createFrom(OperationRequest original, Parameters newParameters) { - URI uri = (original.getMethod() == HttpMethod.GET) ? updateQueryString(original.getUri(), newParameters) - : original.getUri(); - return new StandardOperationRequest(uri, original.getMethod(), original.getContent(), original.getHeaders(), - newParameters, original.getParts(), original.getCookies()); - } - - private URI updateQueryString(URI originalUri, Parameters parameters) { - try { - return new URI(originalUri.getScheme(), originalUri.getUserInfo(), originalUri.getHost(), - originalUri.getPort(), originalUri.getPath(), - parameters.isEmpty() ? null : parameters.toQueryString(), originalUri.getFragment()); - } - catch (URISyntaxException ex) { - throw new RuntimeException(ex); - } + original.getParts(), original.getCookies()); } private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, URI uri, byte[] content) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponse.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponse.java index 378160d42..344b4e9a9 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponse.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -16,13 +16,16 @@ package org.springframework.restdocs.operation; +import java.util.Collection; + import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; /** * The response that was received as part of performing an operation on a RESTful service. * * @author Andy Wilkinson + * @author Clyde Stubbs * @see Operation * @see Operation#getRequest() */ @@ -30,17 +33,9 @@ public interface OperationResponse { /** * Returns the status of the response. - * @return the status or {@code null} if the status is unknown to {@link HttpStatus} - */ - HttpStatus getStatus(); - - /** - * Returns the status code of the response. - * @return the status code + * @return the status, never {@code null} */ - default int getStatusCode() { - throw new UnsupportedOperationException(); - } + HttpStatusCode getStatus(); /** * Returns the headers in the response. @@ -64,4 +59,12 @@ default int getStatusCode() { */ String getContentAsString(); + /** + * Returns the {@link ResponseCookie cookies} returned with the response. If no + * cookies were returned an empty collection is returned. + * @return the cookies, never {@code null} + * @since 3.0 + */ + Collection getCookies(); + } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java index 2768451b1..b9c749ab1 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/OperationResponseFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -16,33 +16,49 @@ package org.springframework.restdocs.operation; +import java.util.Collection; +import java.util.Collections; + import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; /** * A factory for creating {@link OperationResponse OperationResponses}. * * @author Andy Wilkinson + * @author Clyde Stubbs */ public class OperationResponseFactory { /** - * Creates a new {@link OperationResponse}. If the response has any content, the given - * {@code headers} will be augmented to ensure that they include a + * Creates a new {@link OperationResponse} without cookies. If the response has any + * content, the given {@code headers} will be augmented to ensure that they include a * {@code Content-Length} header. * @param status the status of the response * @param headers the request's headers * @param content the content of the request * @return the {@code OperationResponse} - * @deprecated since 2.0.4 in favor of {@link #create(int, HttpHeaders, byte[])} + * @since 3.0.0 */ - @Deprecated - public OperationResponse create(HttpStatus status, HttpHeaders headers, byte[] content) { - return this.create(status.value(), headers, content); + public OperationResponse create(HttpStatusCode status, HttpHeaders headers, byte[] content) { + return new StandardOperationResponse(status, augmentHeaders(headers, content), content, + Collections.emptyList()); } - public OperationResponse create(int status, HttpHeaders headers, byte[] content) { - return new StandardOperationResponse(status, augmentHeaders(headers, content), content); + /** + * Creates a new {@link OperationResponse}. If the response has any content, the given + * {@code headers} will be augmented to ensure that they include a + * {@code Content-Length} header. + * @param status the status of the response + * @param headers the request's headers + * @param content the content of the request + * @param cookies the cookies + * @return the {@code OperationResponse} + * @since 3.0.0 + */ + public OperationResponse create(HttpStatusCode status, HttpHeaders headers, byte[] content, + Collection cookies) { + return new StandardOperationResponse(status, augmentHeaders(headers, content), content, cookies); } /** @@ -55,8 +71,8 @@ public OperationResponse create(int status, HttpHeaders headers, byte[] content) * @return the new response with the new content */ public OperationResponse createFrom(OperationResponse original, byte[] newContent) { - return new StandardOperationResponse(original.getStatusCode(), - getUpdatedHeaders(original.getHeaders(), newContent), newContent); + return new StandardOperationResponse(original.getStatus(), getUpdatedHeaders(original.getHeaders(), newContent), + newContent, original.getCookies()); } /** @@ -67,7 +83,8 @@ public OperationResponse createFrom(OperationResponse original, byte[] newConten * @return the new response with the new headers */ public OperationResponse createFrom(OperationResponse original, HttpHeaders newHeaders) { - return new StandardOperationResponse(original.getStatusCode(), newHeaders, original.getContent()); + return new StandardOperationResponse(original.getStatus(), newHeaders, original.getContent(), + original.getCookies()); } private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, byte[] content) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/Parameters.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/Parameters.java deleted file mode 100644 index 0e3558e5f..000000000 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/Parameters.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2014-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.restdocs.operation; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URLEncoder; -import java.util.List; -import java.util.Map; - -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.StringUtils; - -/** - * The parameters received in a request. - * - * @author Andy Wilkinson - */ -@SuppressWarnings("serial") -public class Parameters extends LinkedMultiValueMap { - - /** - * Converts the parameters to a query string suitable for use in a URI or the body of - * a form-encoded request. - * @return the query string - */ - public String toQueryString() { - StringBuilder sb = new StringBuilder(); - for (Map.Entry> entry : entrySet()) { - if (entry.getValue().isEmpty()) { - append(sb, entry.getKey()); - } - else { - for (String value : entry.getValue()) { - append(sb, entry.getKey(), value); - } - } - } - return sb.toString(); - } - - /** - * Returns a new {@code Parameters} containing only the parameters that do no appear - * in the query string of the given {@code uri}. - * @param uri the uri - * @return the unique parameters - */ - public Parameters getUniqueParameters(URI uri) { - Parameters queryStringParameters = new QueryStringParser().parse(uri); - Parameters uniqueParameters = new Parameters(); - - for (Map.Entry> parameter : entrySet()) { - addIfUnique(parameter, queryStringParameters, uniqueParameters); - } - return uniqueParameters; - } - - private void addIfUnique(Map.Entry> parameter, Parameters queryStringParameters, - Parameters uniqueParameters) { - if (!queryStringParameters.containsKey(parameter.getKey())) { - uniqueParameters.put(parameter.getKey(), parameter.getValue()); - } - else { - List candidates = parameter.getValue(); - List existing = queryStringParameters.get(parameter.getKey()); - for (String candidate : candidates) { - if (!existing.contains(candidate)) { - uniqueParameters.add(parameter.getKey(), candidate); - } - } - } - } - - private static void append(StringBuilder sb, String key) { - append(sb, key, ""); - } - - private static void append(StringBuilder sb, String key, String value) { - doAppend(sb, urlEncodeUTF8(key) + "=" + urlEncodeUTF8(value)); - } - - private static void doAppend(StringBuilder sb, String toAppend) { - if (sb.length() > 0) { - sb.append("&"); - } - sb.append(toAppend); - } - - private static String urlEncodeUTF8(String s) { - if (!StringUtils.hasLength(s)) { - return ""; - } - try { - return URLEncoder.encode(s, "UTF-8"); - } - catch (UnsupportedEncodingException ex) { - throw new IllegalStateException("Unable to URL encode " + s + " using UTF-8", ex); - } - } - -} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryParameters.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryParameters.java new file mode 100644 index 000000000..17f7fc1c6 --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/QueryParameters.java @@ -0,0 +1,90 @@ +/* + * Copyright 2014-2022 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.restdocs.operation; + +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.LinkedList; +import java.util.List; +import java.util.Scanner; + +import org.springframework.util.LinkedMultiValueMap; + +/** + * A request's query parameters, derived from its URI's query string. + * + * @author Andy Wilkinson + * @since 3.0.0 + */ +public final class QueryParameters extends LinkedMultiValueMap { + + private QueryParameters() { + + } + + /** + * Extracts the query parameters from the query string of the given {@code request}. + * If the request has no query string, an empty {@code QueryParameters} is returned, + * rather than {@code null}. + * @param request the request + * @return the query parameters extracted from the request's query string + */ + public static QueryParameters from(OperationRequest request) { + return from(request.getUri().getRawQuery()); + } + + private static QueryParameters from(String queryString) { + if (queryString == null || queryString.length() == 0) { + return new QueryParameters(); + } + return parse(queryString); + } + + private static QueryParameters parse(String query) { + QueryParameters parameters = new QueryParameters(); + try (Scanner scanner = new Scanner(query)) { + scanner.useDelimiter("&"); + while (scanner.hasNext()) { + processParameter(scanner.next(), parameters); + } + } + return parameters; + } + + private static void processParameter(String parameter, QueryParameters parameters) { + String[] components = parameter.split("="); + if (components.length > 0 && components.length < 3) { + if (components.length == 2) { + String name = components[0]; + String value = components[1]; + parameters.add(decode(name), decode(value)); + } + else { + List values = parameters.computeIfAbsent(components[0], (p) -> new LinkedList<>()); + values.add(""); + } + } + else { + throw new IllegalArgumentException("The parameter '" + parameter + "' is malformed"); + } + } + + private static String decode(String encoded) { + return URLDecoder.decode(encoded, StandardCharsets.UTF_8); + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/ResponseCookie.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/ResponseCookie.java new file mode 100644 index 000000000..9cf39302e --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/ResponseCookie.java @@ -0,0 +1,57 @@ +/* + * Copyright 2014-2022 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.restdocs.operation; + +/** + * A representation of a Cookie returned in a response. + * + * @author Clyde Stubbs + * @since 3.0 + */ +public final class ResponseCookie { + + private final String name; + + private final String value; + + /** + * Creates a new {@code ResponseCookie} with the given {@code name} and {@code value}. + * @param name the name of the cookie + * @param value the value of the cookie + */ + public ResponseCookie(String name, String value) { + this.name = name; + this.value = value; + } + + /** + * Returns the name of the cookie. + * @return the name + */ + public String getName() { + return this.name; + } + + /** + * Returns the value of the cookie. + * @return the value + */ + public String getValue() { + return this.value; + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java index 204ab28f2..bdf65934a 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -32,8 +32,6 @@ class StandardOperationRequest extends AbstractOperationMessage implements Opera private HttpMethod method; - private Parameters parameters; - private Collection parts; private URI uri; @@ -48,16 +46,14 @@ class StandardOperationRequest extends AbstractOperationMessage implements Opera * @param method the method * @param content the content * @param headers the headers - * @param parameters the parameters * @param parts the parts * @param cookies the cookies */ - StandardOperationRequest(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, Parameters parameters, + StandardOperationRequest(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, Collection parts, Collection cookies) { super(content, headers); this.uri = uri; this.method = method; - this.parameters = parameters; this.parts = parts; this.cookies = cookies; } @@ -67,11 +63,6 @@ public HttpMethod getMethod() { return this.method; } - @Override - public Parameters getParameters() { - return this.parameters; - } - @Override public Collection getParts() { return Collections.unmodifiableCollection(this.parts); diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java index 3a169365b..667d03ca8 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/StandardOperationResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -16,17 +16,22 @@ package org.springframework.restdocs.operation; +import java.util.Collection; + import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; /** * Standard implementation of {@link OperationResponse}. * * @author Andy Wilkinson + * @author Clyde Stubbs */ class StandardOperationResponse extends AbstractOperationMessage implements OperationResponse { - private final int status; + private final HttpStatusCode status; + + private Collection cookies; /** * Creates a new response with the given {@code status}, {@code headers}, and @@ -34,20 +39,23 @@ class StandardOperationResponse extends AbstractOperationMessage implements Oper * @param status the status of the response * @param headers the headers of the response * @param content the content of the response + * @param cookies any cookies included in the response */ - StandardOperationResponse(int status, HttpHeaders headers, byte[] content) { + StandardOperationResponse(HttpStatusCode status, HttpHeaders headers, byte[] content, + Collection cookies) { super(content, headers); this.status = status; + this.cookies = cookies; } @Override - public HttpStatus getStatus() { - return HttpStatus.resolve(this.status); + public HttpStatusCode getStatus() { + return this.status; } @Override - public int getStatusCode() { - return this.status; + public Collection getCookies() { + return this.cookies; } } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessor.java deleted file mode 100644 index 01710e992..000000000 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessor.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2014-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.restdocs.operation.preprocess; - -import java.util.List; -import java.util.Map.Entry; - -import org.springframework.http.HttpHeaders; -import org.springframework.restdocs.operation.OperationRequest; -import org.springframework.restdocs.operation.OperationRequestFactory; -import org.springframework.restdocs.operation.OperationResponse; -import org.springframework.restdocs.operation.OperationResponseFactory; - -/** - * An {@link OperationPreprocessor} that removes headers. The headers to remove are - * provided as constructor arguments and can be either plain string or patterns to match - * against the headers found - * - * @author Andy Wilkinson - */ -class HeaderRemovingOperationPreprocessor implements OperationPreprocessor { - - private final OperationRequestFactory requestFactory = new OperationRequestFactory(); - - private final OperationResponseFactory responseFactory = new OperationResponseFactory(); - - private final HeaderFilter headerFilter; - - HeaderRemovingOperationPreprocessor(HeaderFilter headerFilter) { - this.headerFilter = headerFilter; - } - - @Override - public OperationResponse preprocess(OperationResponse response) { - return this.responseFactory.createFrom(response, removeHeaders(response.getHeaders())); - } - - @Override - public OperationRequest preprocess(OperationRequest request) { - return this.requestFactory.createFrom(request, removeHeaders(request.getHeaders())); - } - - private HttpHeaders removeHeaders(HttpHeaders originalHeaders) { - HttpHeaders processedHeaders = new HttpHeaders(); - for (Entry> header : originalHeaders.entrySet()) { - if (!this.headerFilter.excludeHeader(header.getKey())) { - processedHeaders.put(header.getKey(), header.getValue()); - } - } - return processedHeaders; - } - -} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeadersModifyingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeadersModifyingOperationPreprocessor.java new file mode 100644 index 000000000..001f7789d --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/HeadersModifyingOperationPreprocessor.java @@ -0,0 +1,218 @@ +/* + * Copyright 2014-2025 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.restdocs.operation.preprocess; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.springframework.http.HttpHeaders; +import org.springframework.restdocs.operation.OperationRequest; +import org.springframework.restdocs.operation.OperationRequestFactory; +import org.springframework.restdocs.operation.OperationResponse; +import org.springframework.restdocs.operation.OperationResponseFactory; +import org.springframework.util.Assert; + +/** + * An {@link OperationPreprocessor} that modifies a request or response by adding, + * setting, or removing headers. + * + * @author Jihoon Cha + * @author Andy Wilkinson + * @since 3.0.0 + */ +public class HeadersModifyingOperationPreprocessor implements OperationPreprocessor { + + private final OperationRequestFactory requestFactory = new OperationRequestFactory(); + + private final OperationResponseFactory responseFactory = new OperationResponseFactory(); + + private final List modifications = new ArrayList<>(); + + @Override + public OperationRequest preprocess(OperationRequest request) { + return this.requestFactory.createFrom(request, preprocess(request.getHeaders())); + } + + @Override + public OperationResponse preprocess(OperationResponse response) { + return this.responseFactory.createFrom(response, preprocess(response.getHeaders())); + } + + private HttpHeaders preprocess(HttpHeaders headers) { + HttpHeaders modifiedHeaders = new HttpHeaders(); + modifiedHeaders.addAll(headers); + for (Modification modification : this.modifications) { + modification.applyTo(modifiedHeaders); + } + return modifiedHeaders; + } + + /** + * Adds a header with the given {@code name} and {@code value}. + * @param name the name + * @param value the value + * @return {@code this} + */ + public HeadersModifyingOperationPreprocessor add(String name, String value) { + this.modifications.add(new AddHeaderModification(name, value)); + return this; + } + + /** + * Sets the header with the given {@code name} to have the given {@code values}. + * @param name the name + * @param values the values + * @return {@code this} + */ + public HeadersModifyingOperationPreprocessor set(String name, String... values) { + Assert.notEmpty(values, "At least one value must be provided"); + this.modifications.add(new SetHeaderModification(name, Arrays.asList(values))); + return this; + } + + /** + * Removes the header with the given {@code name}. + * @param name the name of the parameter + * @return {@code this} + */ + public HeadersModifyingOperationPreprocessor remove(String name) { + this.modifications.add(new RemoveHeaderModification(name)); + return this; + } + + /** + * Removes the given {@code value} from the header with the given {@code name}. + * @param name the name + * @param value the value + * @return {@code this} + */ + public HeadersModifyingOperationPreprocessor remove(String name, String value) { + this.modifications.add(new RemoveValueHeaderModification(name, value)); + return this; + } + + /** + * Remove headers that match the given {@code namePattern} regular expression. + * @param namePattern the name pattern + * @return {@code this} + * @see Matcher#matches() + */ + public HeadersModifyingOperationPreprocessor removeMatching(String namePattern) { + this.modifications.add(new RemoveHeadersByNamePatternModification(Pattern.compile(namePattern))); + return this; + } + + private interface Modification { + + void applyTo(HttpHeaders headers); + + } + + private static final class AddHeaderModification implements Modification { + + private final String name; + + private final String value; + + private AddHeaderModification(String name, String value) { + this.name = name; + this.value = value; + } + + @Override + public void applyTo(HttpHeaders headers) { + headers.add(this.name, this.value); + } + + } + + private static final class SetHeaderModification implements Modification { + + private final String name; + + private final List values; + + private SetHeaderModification(String name, List values) { + this.name = name; + this.values = values; + } + + @Override + public void applyTo(HttpHeaders headers) { + headers.put(this.name, this.values); + } + + } + + private static final class RemoveHeaderModification implements Modification { + + private final String name; + + private RemoveHeaderModification(String name) { + this.name = name; + } + + @Override + public void applyTo(HttpHeaders headers) { + headers.remove(this.name); + } + + } + + private static final class RemoveValueHeaderModification implements Modification { + + private final String name; + + private final String value; + + private RemoveValueHeaderModification(String name, String value) { + this.name = name; + this.value = value; + } + + @Override + public void applyTo(HttpHeaders headers) { + List values = headers.get(this.name); + if (values != null) { + values.remove(this.value); + if (values.isEmpty()) { + headers.remove(this.name); + } + } + } + + } + + private static final class RemoveHeadersByNamePatternModification implements Modification { + + private final Pattern namePattern; + + private RemoveHeadersByNamePatternModification(Pattern namePattern) { + this.namePattern = namePattern; + } + + @Override + public void applyTo(HttpHeaders headers) { + headers.headerNames().removeIf((name) -> this.namePattern.matcher(name).matches()); + } + + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessor.java deleted file mode 100644 index 943213434..000000000 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessor.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2014-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.restdocs.operation.preprocess; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.springframework.restdocs.operation.OperationRequest; -import org.springframework.restdocs.operation.OperationRequestFactory; -import org.springframework.restdocs.operation.Parameters; -import org.springframework.util.Assert; - -/** - * An {@link OperationPreprocessor} that can be used to modify a request's - * {@link OperationRequest#getParameters()} by adding, setting, and removing parameters. - * - * @author Andy Wilkinson - * @since 1.1.0 - */ -public final class ParametersModifyingOperationPreprocessor extends OperationPreprocessorAdapter { - - private final OperationRequestFactory requestFactory = new OperationRequestFactory(); - - private final List modifications = new ArrayList<>(); - - @Override - public OperationRequest preprocess(OperationRequest request) { - Parameters parameters = new Parameters(); - parameters.putAll(request.getParameters()); - for (Modification modification : this.modifications) { - modification.apply(parameters); - } - return this.requestFactory.createFrom(request, parameters); - } - - /** - * Adds a parameter with the given {@code name} and {@code value}. - * @param name the name - * @param value the value - * @return {@code this} - */ - public ParametersModifyingOperationPreprocessor add(String name, String value) { - this.modifications.add(new AddParameterModification(name, value)); - return this; - } - - /** - * Sets the parameter with the given {@code name} to have the given {@code values}. - * @param name the name - * @param values the values - * @return {@code this} - */ - public ParametersModifyingOperationPreprocessor set(String name, String... values) { - Assert.notEmpty(values, "At least one value must be provided"); - this.modifications.add(new SetParameterModification(name, Arrays.asList(values))); - return this; - } - - /** - * Removes the parameter with the given {@code name}. - * @param name the name of the parameter - * @return {@code this} - */ - public ParametersModifyingOperationPreprocessor remove(String name) { - this.modifications.add(new RemoveParameterModification(name)); - return this; - } - - /** - * Removes the given {@code value} from the parameter with the given {@code name}. - * @param name the name - * @param value the value - * @return {@code this} - */ - public ParametersModifyingOperationPreprocessor remove(String name, String value) { - this.modifications.add(new RemoveValueParameterModification(name, value)); - return this; - } - - private interface Modification { - - void apply(Parameters parameters); - - } - - private static final class AddParameterModification implements Modification { - - private final String name; - - private final String value; - - private AddParameterModification(String name, String value) { - this.name = name; - this.value = value; - } - - @Override - public void apply(Parameters parameters) { - parameters.add(this.name, this.value); - } - - } - - private static final class SetParameterModification implements Modification { - - private final String name; - - private final List values; - - private SetParameterModification(String name, List values) { - this.name = name; - this.values = values; - } - - @Override - public void apply(Parameters parameters) { - parameters.put(this.name, this.values); - } - - } - - private static final class RemoveParameterModification implements Modification { - - private final String name; - - private RemoveParameterModification(String name) { - this.name = name; - } - - @Override - public void apply(Parameters parameters) { - parameters.remove(this.name); - } - - } - - private static final class RemoveValueParameterModification implements Modification { - - private final String name; - - private final String value; - - private RemoveValueParameterModification(String name, String value) { - this.name = name; - this.value = value; - } - - @Override - public void apply(Parameters parameters) { - List values = parameters.get(this.name); - if (values != null) { - values.remove(this.value); - if (values.isEmpty()) { - parameters.remove(this.name); - } - } - } - - } - -} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java index 6be9107c4..6a36ed81e 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/Preprocessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -31,6 +31,7 @@ * * @author Andy Wilkinson * @author Roland Huss + * @author Jihoon Cha */ public final class Preprocessors { @@ -67,30 +68,6 @@ public static OperationPreprocessor prettyPrint() { return new ContentModifyingOperationPreprocessor(new PrettyPrintingContentModifier()); } - /** - * Returns an {@code OperationPreprocessor} that will remove any header from the - * request or response with a name that is equal to one of the given - * {@code headersToRemove}. - * @param headerNames the header names - * @return the preprocessor - * @see String#equals(Object) - */ - public static OperationPreprocessor removeHeaders(String... headerNames) { - return new HeaderRemovingOperationPreprocessor(new ExactMatchHeaderFilter(headerNames)); - } - - /** - * Returns an {@code OperationPreprocessor} that will remove any headers from the - * request or response with a name that matches one of the given - * {@code headerNamePatterns} regular expressions. - * @param headerNamePatterns the header name patterns - * @return the preprocessor - * @see java.util.regex.Matcher#matches() - */ - public static OperationPreprocessor removeMatchingHeaders(String... headerNamePatterns) { - return new HeaderRemovingOperationPreprocessor(new PatternMatchHeaderFilter(headerNamePatterns)); - } - /** * Returns an {@code OperationPreprocessor} that will mask the href of hypermedia * links in the request or response. @@ -123,13 +100,13 @@ public static OperationPreprocessor replacePattern(Pattern pattern, String repla } /** - * Returns a {@code ParametersModifyingOperationPreprocessor} that can then be - * configured to modify the parameters of the request. + * Returns a {@code HeadersModifyingOperationPreprocessor} that can then be configured + * to modify the headers of the request or response. * @return the preprocessor - * @since 1.1.0 + * @since 3.0.0 */ - public static ParametersModifyingOperationPreprocessor modifyParameters() { - return new ParametersModifyingOperationPreprocessor(); + public static HeadersModifyingOperationPreprocessor modifyHeaders() { + return new HeadersModifyingOperationPreprocessor(); } /** diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java index e147a7f61..6e15b74b9 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -134,20 +134,20 @@ public OperationRequest preprocess(OperationRequest request) { HttpHeaders modifiedHeaders = modify(request.getHeaders()); modifiedHeaders.set(HttpHeaders.HOST, modifiedUri.getHost() + ((modifiedUri.getPort() != -1) ? ":" + modifiedUri.getPort() : "")); - return this.contentModifyingDelegate.preprocess(new OperationRequestFactory().create( - uriBuilder.build(true).toUri(), request.getMethod(), request.getContent(), modifiedHeaders, - request.getParameters(), modify(request.getParts()), request.getCookies())); + return this.contentModifyingDelegate + .preprocess(new OperationRequestFactory().create(uriBuilder.build(true).toUri(), request.getMethod(), + request.getContent(), modifiedHeaders, modify(request.getParts()), request.getCookies())); } @Override public OperationResponse preprocess(OperationResponse response) { - return this.contentModifyingDelegate.preprocess(new OperationResponseFactory().create(response.getStatusCode(), - modify(response.getHeaders()), response.getContent())); + return this.contentModifyingDelegate.preprocess(new OperationResponseFactory().create(response.getStatus(), + modify(response.getHeaders()), response.getContent(), response.getCookies())); } private HttpHeaders modify(HttpHeaders headers) { HttpHeaders modified = new HttpHeaders(); - for (Entry> header : headers.entrySet()) { + for (Entry> header : headers.headerSet()) { for (String value : header.getValue()) { modified.add(header.getKey(), this.contentModifier.modify(value)); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java index f9895e897..3ccd56881 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/AbstractBodySnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -31,6 +31,7 @@ * document a RESTful resource's request or response body. * * @author Andy Wilkinson + * @author Achim Grimm */ public abstract class AbstractBodySnippet extends TemplatedSnippet { @@ -73,6 +74,7 @@ protected AbstractBodySnippet(String name, String type, PayloadSubsectionExtract protected Map createModel(Operation operation) { try { MediaType contentType = getContentType(operation); + String language = determineLanguage(contentType); byte[] content = getContent(operation); if (this.subsectionExtractor != null) { content = this.subsectionExtractor.extractSubsection(content, contentType); @@ -80,6 +82,7 @@ protected Map createModel(Operation operation) { Charset charset = extractCharset(contentType); String body = (charset != null) ? new String(content, charset) : new String(content); Map model = new HashMap<>(); + model.put("language", language); model.put("body", body); return model; } @@ -88,6 +91,13 @@ protected Map createModel(Operation operation) { } } + private String determineLanguage(MediaType contentType) { + if (contentType == null) { + return null; + } + return (contentType.getSubtypeSuffix() != null) ? contentType.getSubtypeSuffix() : contentType.getSubtype(); + } + private Charset extractCharset(MediaType contentType) { if (contentType == null) { return null; diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypeResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypeResolver.java index 6c8397c39..7f574a9e9 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypeResolver.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/FieldTypeResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -16,7 +16,6 @@ package org.springframework.restdocs.payload; -import java.util.Collections; import java.util.List; import org.springframework.http.MediaType; @@ -30,20 +29,6 @@ */ public interface FieldTypeResolver { - /** - * Create a {@code FieldTypeResolver} for the given {@code content} and - * {@code contentType}. - * @param content the payload that the {@code FieldTypeResolver} should handle - * @param contentType the content type of the payload - * @return the {@code FieldTypeResolver} - * @deprecated since 2.0.4 in favor of - * {@link #forContentWithDescriptors(byte[], MediaType, List)} - */ - @Deprecated - static FieldTypeResolver forContent(byte[] content, MediaType contentType) { - return forContentWithDescriptors(content, contentType, Collections.emptyList()); - } - /** * Create a {@code FieldTypeResolver} for the given {@code content} and * {@code contentType}, described by the given {@code descriptors}. diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java index c1897084e..9e7610475 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldPath.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2024 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. @@ -153,7 +153,7 @@ enum PathType { /** * The path identifies multiple items in the payload. */ - MULTI; + MULTI } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java index 523d65c81..cce7a7d1a 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/AbstractParametersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2022 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. @@ -126,18 +126,6 @@ private void verifyParameterDescriptors(Operation operation) { */ protected abstract void verificationFailed(Set undocumentedParameters, Set missingParameters); - /** - * Returns a {@code Map} of {@link ParameterDescriptor ParameterDescriptors} that will - * be used to generate the documentation key by their - * {@link ParameterDescriptor#getName()}. - * @return the map of path descriptors - * @deprecated since 1.1.0 in favor of {@link #getParameterDescriptors()} - */ - @Deprecated - protected final Map getFieldDescriptors() { - return this.descriptorsByName; - } - /** * Returns a {@code Map} of {@link ParameterDescriptor ParameterDescriptors} that will * be used to generate the documentation key by their diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestParametersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/FormParametersSnippet.java similarity index 62% rename from spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestParametersSnippet.java rename to spring-restdocs-core/src/main/java/org/springframework/restdocs/request/FormParametersSnippet.java index b1a1afc14..8d5401d51 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestParametersSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/FormParametersSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2020 the original author or authors. + * Copyright 2014-2022 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. @@ -22,36 +22,33 @@ import java.util.Map; import java.util.Set; +import org.springframework.restdocs.operation.FormParameters; import org.springframework.restdocs.operation.Operation; -import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.snippet.Snippet; import org.springframework.restdocs.snippet.SnippetException; /** - * A {@link Snippet} that documents the request parameters supported by a RESTful - * resource. - *

        - * Request parameters are sent as part of the query string or as POSTed form data. + * A {@link Snippet} that documents the form parameters supported by a RESTful resource. * * @author Andy Wilkinson - * @see OperationRequest#getParameters() - * @see RequestDocumentation#requestParameters(ParameterDescriptor...) - * @see RequestDocumentation#requestParameters(Map, ParameterDescriptor...) + * @since 3.0.0 + * @see RequestDocumentation#formParameters(ParameterDescriptor...) + * @see RequestDocumentation#formParameters(Map, ParameterDescriptor...) */ -public class RequestParametersSnippet extends AbstractParametersSnippet { +public class FormParametersSnippet extends AbstractParametersSnippet { /** - * Creates a new {@code RequestParametersSnippet} that will document the request's + * Creates a new {@code FormParametersSnippet} that will document the request's form * parameters using the given {@code descriptors}. Undocumented parameters will * trigger a failure. * @param descriptors the parameter descriptors */ - protected RequestParametersSnippet(List descriptors) { + protected FormParametersSnippet(List descriptors) { this(descriptors, null, false); } /** - * Creates a new {@code RequestParametersSnippet} that will document the request's + * Creates a new {@code FormParametersSnippet} that will document the request's form * parameters using the given {@code descriptors}. If * {@code ignoreUndocumentedParameters} is {@code true}, undocumented parameters will * be ignored and will not trigger a failure. @@ -59,24 +56,24 @@ protected RequestParametersSnippet(List descriptors) { * @param ignoreUndocumentedParameters whether undocumented parameters should be * ignored */ - protected RequestParametersSnippet(List descriptors, boolean ignoreUndocumentedParameters) { + protected FormParametersSnippet(List descriptors, boolean ignoreUndocumentedParameters) { this(descriptors, null, ignoreUndocumentedParameters); } /** - * Creates a new {@code RequestParametersSnippet} that will document the request's + * Creates a new {@code FormParametersSnippet} that will document the request's form * parameters using the given {@code descriptors}. The given {@code attributes} will * be included in the model during template rendering. Undocumented parameters will * trigger a failure. * @param descriptors the parameter descriptors * @param attributes the additional attributes */ - protected RequestParametersSnippet(List descriptors, Map attributes) { + protected FormParametersSnippet(List descriptors, Map attributes) { this(descriptors, attributes, false); } /** - * Creates a new {@code RequestParametersSnippet} that will document the request's + * Creates a new {@code FormParametersSnippet} that will document the request's form * parameters using the given {@code descriptors}. The given {@code attributes} will * be included in the model during template rendering. If * {@code ignoreUndocumentedParameters} is {@code true}, undocumented parameters will @@ -86,54 +83,53 @@ protected RequestParametersSnippet(List descriptors, Map descriptors, Map attributes, + protected FormParametersSnippet(List descriptors, Map attributes, boolean ignoreUndocumentedParameters) { - super("request-parameters", descriptors, attributes, ignoreUndocumentedParameters); + super("form-parameters", descriptors, attributes, ignoreUndocumentedParameters); } @Override protected void verificationFailed(Set undocumentedParameters, Set missingParameters) { String message = ""; if (!undocumentedParameters.isEmpty()) { - message += "Request parameters with the following names were not documented: " + undocumentedParameters; + message += "Form parameters with the following names were not documented: " + undocumentedParameters; } if (!missingParameters.isEmpty()) { if (message.length() > 0) { message += ". "; } - message += "Request parameters with the following names were not found in the request: " - + missingParameters; + message += "Form parameters with the following names were not found in the request: " + missingParameters; } throw new SnippetException(message); } @Override protected Set extractActualParameters(Operation operation) { - return operation.getRequest().getParameters().keySet(); + return FormParameters.from(operation.getRequest()).keySet(); } /** - * Returns a new {@code RequestParametersSnippet} configured with this snippet's + * Returns a new {@code FormParametersSnippet} configured with this snippet's * attributes and its descriptors combined with the given * {@code additionalDescriptors}. * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public RequestParametersSnippet and(ParameterDescriptor... additionalDescriptors) { + public FormParametersSnippet and(ParameterDescriptor... additionalDescriptors) { return and(Arrays.asList(additionalDescriptors)); } /** - * Returns a new {@code RequestParametersSnippet} configured with this snippet's + * Returns a new {@code FormParametersSnippet} configured with this snippet's * attributes and its descriptors combined with the given * {@code additionalDescriptors}. * @param additionalDescriptors the additional descriptors * @return the new snippet */ - public RequestParametersSnippet and(List additionalDescriptors) { + public FormParametersSnippet and(List additionalDescriptors) { List combinedDescriptors = new ArrayList<>(getParameterDescriptors().values()); combinedDescriptors.addAll(additionalDescriptors); - return new RequestParametersSnippet(combinedDescriptors, this.getAttributes(), + return new FormParametersSnippet(combinedDescriptors, this.getAttributes(), this.isIgnoreUndocumentedParameters()); } diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/QueryParametersSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/QueryParametersSnippet.java new file mode 100644 index 000000000..2485c2f3d --- /dev/null +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/QueryParametersSnippet.java @@ -0,0 +1,136 @@ +/* + * Copyright 2014-2022 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.restdocs.request; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.restdocs.operation.Operation; +import org.springframework.restdocs.operation.QueryParameters; +import org.springframework.restdocs.snippet.Snippet; +import org.springframework.restdocs.snippet.SnippetException; + +/** + * A {@link Snippet} that documents the query parameters supported by a RESTful resource. + * + * @author Andy Wilkinson + * @since 3.0.0 + * @see RequestDocumentation#queryParameters(ParameterDescriptor...) + * @see RequestDocumentation#queryParameters(Map, ParameterDescriptor...) + */ +public class QueryParametersSnippet extends AbstractParametersSnippet { + + /** + * Creates a new {@code QueryParametersSnippet} that will document the request's query + * parameters using the given {@code descriptors}. Undocumented parameters will + * trigger a failure. + * @param descriptors the parameter descriptors + */ + protected QueryParametersSnippet(List descriptors) { + this(descriptors, null, false); + } + + /** + * Creates a new {@code QueryParametersSnippet} that will document the request's query + * parameters using the given {@code descriptors}. If + * {@code ignoreUndocumentedParameters} is {@code true}, undocumented parameters will + * be ignored and will not trigger a failure. + * @param descriptors the parameter descriptors + * @param ignoreUndocumentedParameters whether undocumented parameters should be + * ignored + */ + protected QueryParametersSnippet(List descriptors, boolean ignoreUndocumentedParameters) { + this(descriptors, null, ignoreUndocumentedParameters); + } + + /** + * Creates a new {@code QueryParametersSnippet} that will document the request's query + * parameters using the given {@code descriptors}. The given {@code attributes} will + * be included in the model during template rendering. Undocumented parameters will + * trigger a failure. + * @param descriptors the parameter descriptors + * @param attributes the additional attributes + */ + protected QueryParametersSnippet(List descriptors, Map attributes) { + this(descriptors, attributes, false); + } + + /** + * Creates a new {@code QueryParametersSnippet} that will document the request's query + * parameters using the given {@code descriptors}. The given {@code attributes} will + * be included in the model during template rendering. If + * {@code ignoreUndocumentedParameters} is {@code true}, undocumented parameters will + * be ignored and will not trigger a failure. + * @param descriptors the parameter descriptors + * @param attributes the additional attributes + * @param ignoreUndocumentedParameters whether undocumented parameters should be + * ignored + */ + protected QueryParametersSnippet(List descriptors, Map attributes, + boolean ignoreUndocumentedParameters) { + super("query-parameters", descriptors, attributes, ignoreUndocumentedParameters); + } + + @Override + protected void verificationFailed(Set undocumentedParameters, Set missingParameters) { + String message = ""; + if (!undocumentedParameters.isEmpty()) { + message += "Query parameters with the following names were not documented: " + undocumentedParameters; + } + if (!missingParameters.isEmpty()) { + if (message.length() > 0) { + message += ". "; + } + message += "Query parameters with the following names were not found in the request: " + missingParameters; + } + throw new SnippetException(message); + } + + @Override + protected Set extractActualParameters(Operation operation) { + return QueryParameters.from(operation.getRequest()).keySet(); + } + + /** + * Returns a new {@code QueryParametersSnippet} configured with this snippet's + * attributes and its descriptors combined with the given + * {@code additionalDescriptors}. + * @param additionalDescriptors the additional descriptors + * @return the new snippet + */ + public QueryParametersSnippet and(ParameterDescriptor... additionalDescriptors) { + return and(Arrays.asList(additionalDescriptors)); + } + + /** + * Returns a new {@code QueryParametersSnippet} configured with this snippet's + * attributes and its descriptors combined with the given + * {@code additionalDescriptors}. + * @param additionalDescriptors the additional descriptors + * @return the new snippet + */ + public QueryParametersSnippet and(List additionalDescriptors) { + List combinedDescriptors = new ArrayList<>(getParameterDescriptors().values()); + combinedDescriptors.addAll(additionalDescriptors); + return new QueryParametersSnippet(combinedDescriptors, this.getAttributes(), + this.isIgnoreUndocumentedParameters()); + } + +} diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java index 3c051fbca..221006b83 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/request/RequestDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -203,159 +203,321 @@ public static PathParametersSnippet relaxedPathParameters(Map at } /** - * Returns a {@code Snippet} that will document the parameters from the API - * operation's request. The parameters will be documented using the given + * Returns a {@code Snippet} that will document the query parameters from the API + * operation's request. The query parameters will be documented using the given * {@code descriptors}. *

        - * If a parameter is present in the request, but is not documented by one of the + * If a query parameter is present in the request, but is not documented by one of the * descriptors, a failure will occur when the snippet is invoked. Similarly, if a - * parameter is documented, is not marked as optional, and is not present in the + * query parameter is documented, is not marked as optional, and is not present in the * request, a failure will also occur. *

        - * If you do not want to document a request parameter, a parameter descriptor can be + * If you do not want to document a query parameter, a parameter descriptor can be * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from * appearing in the generated snippet while avoiding the failure described above. - * @param descriptors the descriptions of the request's parameters + * @param descriptors the descriptions of the request's query parameters * @return the snippet - * @see OperationRequest#getParameters() + * @since 3.0.0 */ - public static RequestParametersSnippet requestParameters(ParameterDescriptor... descriptors) { - return requestParameters(Arrays.asList(descriptors)); + public static QueryParametersSnippet queryParameters(ParameterDescriptor... descriptors) { + return queryParameters(Arrays.asList(descriptors)); } /** - * Returns a {@code Snippet} that will document the parameters from the API - * operation's request. The parameters will be documented using the given + * Returns a {@code Snippet} that will document the query parameters from the API + * operation's request. The query parameters will be documented using the given * {@code descriptors}. *

        - * If a parameter is present in the request, but is not documented by one of the + * If a query parameter is present in the request, but is not documented by one of the * descriptors, a failure will occur when the snippet is invoked. Similarly, if a - * parameter is documented, is not marked as optional, and is not present in the + * query parameter is documented, is not marked as optional, and is not present in the * request, a failure will also occur. *

        - * If you do not want to document a request parameter, a parameter descriptor can be + * If you do not want to document a query parameter, a parameter descriptor can be * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from * appearing in the generated snippet while avoiding the failure described above. - * @param descriptors the descriptions of the request's parameters + * @param descriptors the descriptions of the request's query parameters * @return the snippet - * @see OperationRequest#getParameters() + * @since 3.0.0 */ - public static RequestParametersSnippet requestParameters(List descriptors) { - return new RequestParametersSnippet(descriptors); + public static QueryParametersSnippet queryParameters(List descriptors) { + return new QueryParametersSnippet(descriptors); } /** - * Returns a {@code Snippet} that will document the parameters from the API - * operation's request. The parameters will be documented using the given + * Returns a {@code Snippet} that will document the query parameters from the API + * operation's request. The query parameters will be documented using the given * {@code descriptors}. *

        - * If a parameter is documented, is not marked as optional, and is not present in the - * response, a failure will occur. Any undocumented parameters will be ignored. - * @param descriptors the descriptions of the request's parameters + * If a query parameter is documented, is not marked as optional, and is not present + * in the response, a failure will occur. Any undocumented query parameters will be + * ignored. + * @param descriptors the descriptions of the request's query parameters * @return the snippet - * @see OperationRequest#getParameters() + * @since 3.0.0 */ - public static RequestParametersSnippet relaxedRequestParameters(ParameterDescriptor... descriptors) { - return relaxedRequestParameters(Arrays.asList(descriptors)); + public static QueryParametersSnippet relaxedQueryParameters(ParameterDescriptor... descriptors) { + return relaxedQueryParameters(Arrays.asList(descriptors)); } /** - * Returns a {@code Snippet} that will document the parameters from the API - * operation's request. The parameters will be documented using the given + * Returns a {@code Snippet} that will document the query parameters from the API + * operation's request. The query parameters will be documented using the given * {@code descriptors}. *

        * If a parameter is documented, is not marked as optional, and is not present in the - * response, a failure will occur. Any undocumented parameters will be ignored. - * @param descriptors the descriptions of the request's parameters + * response, a failure will occur. Any undocumented query parameters will be ignored. + * @param descriptors the descriptions of the request's query parameters * @return the snippet - * @see OperationRequest#getParameters() + * @since 3.0.0 */ - public static RequestParametersSnippet relaxedRequestParameters(List descriptors) { - return new RequestParametersSnippet(descriptors, true); + public static QueryParametersSnippet relaxedQueryParameters(List descriptors) { + return new QueryParametersSnippet(descriptors, true); } /** - * Returns a {@code Snippet} that will document the parameters from the API + * Returns a {@code Snippet} that will document the query parameters from the API * operation's request. The given {@code attributes} will be available during snippet - * rendering and the parameters will be documented using the given {@code descriptors} - * . + * rendering and the query parameters will be documented using the given + * {@code descriptors} . *

        - * If a parameter is present in the request, but is not documented by one of the + * If a query parameter is present in the request, but is not documented by one of the * descriptors, a failure will occur when the snippet is invoked. Similarly, if a - * parameter is documented, is not marked as optional, and is not present in the + * query parameter is documented, is not marked as optional, and is not present in the * request, a failure will also occur. *

        - * If you do not want to document a request parameter, a parameter descriptor can be + * If you do not want to document a query parameter, a parameter descriptor can be * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from * appearing in the generated snippet while avoiding the failure described above. * @param attributes the attributes - * @param descriptors the descriptions of the request's parameters - * @return the snippet that will document the parameters - * @see OperationRequest#getParameters() + * @param descriptors the descriptions of the request's query parameters + * @return the snippet that will document the query parameters + * @since 3.0.0 */ - public static RequestParametersSnippet requestParameters(Map attributes, + public static QueryParametersSnippet queryParameters(Map attributes, ParameterDescriptor... descriptors) { - return requestParameters(attributes, Arrays.asList(descriptors)); + return queryParameters(attributes, Arrays.asList(descriptors)); } /** - * Returns a {@code Snippet} that will document the parameters from the API + * Returns a {@code Snippet} that will document the query parameters from the API * operation's request. The given {@code attributes} will be available during snippet - * rendering and the parameters will be documented using the given {@code descriptors} - * . + * rendering and the query parameters will be documented using the given + * {@code descriptors} . *

        - * If a parameter is present in the request, but is not documented by one of the + * If a query parameter is present in the request, but is not documented by one of the * descriptors, a failure will occur when the snippet is invoked. Similarly, if a - * parameter is documented, is not marked as optional, and is not present in the + * query parameter is documented, is not marked as optional, and is not present in the * request, a failure will also occur. *

        - * If you do not want to document a request parameter, a parameter descriptor can be + * If you do not want to document a query parameter, a parameter descriptor can be * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from * appearing in the generated snippet while avoiding the failure described above. * @param attributes the attributes - * @param descriptors the descriptions of the request's parameters - * @return the snippet that will document the parameters - * @see OperationRequest#getParameters() + * @param descriptors the descriptions of the request's query parameters + * @return the snippet that will document the query parameters + * @since 3.0.0 */ - public static RequestParametersSnippet requestParameters(Map attributes, + public static QueryParametersSnippet queryParameters(Map attributes, List descriptors) { - return new RequestParametersSnippet(descriptors, attributes); + return new QueryParametersSnippet(descriptors, attributes); } /** - * Returns a {@code Snippet} that will document the parameters from the API + * Returns a {@code Snippet} that will document the query parameters from the API * operation's request. The given {@code attributes} will be available during snippet - * rendering and the parameters will be documented using the given {@code descriptors} - * . + * rendering and the query parameters will be documented using the given + * {@code descriptors} . *

        - * If a parameter is documented, is not marked as optional, and is not present in the - * response, a failure will occur. Any undocumented parameters will be ignored. + * If a query parameter is documented, is not marked as optional, and is not present + * in the response, a failure will occur. Any undocumented query parameters will be + * ignored. * @param attributes the attributes - * @param descriptors the descriptions of the request's parameters - * @return the snippet that will document the parameters - * @see OperationRequest#getParameters() + * @param descriptors the descriptions of the request's query parameters + * @return the snippet that will document the query parameters + * @since 3.0.0 */ - public static RequestParametersSnippet relaxedRequestParameters(Map attributes, + public static QueryParametersSnippet relaxedQueryParameters(Map attributes, ParameterDescriptor... descriptors) { - return relaxedRequestParameters(attributes, Arrays.asList(descriptors)); + return relaxedQueryParameters(attributes, Arrays.asList(descriptors)); } /** - * Returns a {@code Snippet} that will document the parameters from the API + * Returns a {@code Snippet} that will document the query parameters from the API * operation's request. The given {@code attributes} will be available during snippet - * rendering and the parameters will be documented using the given {@code descriptors} - * . + * rendering and the query parameters will be documented using the given + * {@code descriptors} . + *

        + * If a query parameter is documented, is not marked as optional, and is not present + * in the response, a failure will occur. Any undocumented query parameters will be + * ignored. + * @param attributes the attributes + * @param descriptors the descriptions of the request's query parameters + * @return the snippet that will document the query parameters + * @since 3.0.0 + */ + public static QueryParametersSnippet relaxedQueryParameters(Map attributes, + List descriptors) { + return new QueryParametersSnippet(descriptors, attributes, true); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The form parameters will be documented using the given + * {@code descriptors}. + *

        + * If a form parameter is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a form + * parameter is documented, is not marked as optional, and is not present in the + * request, a failure will also occur. + *

        + * If you do not want to document a form parameter, a parameter descriptor can be + * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from + * appearing in the generated snippet while avoiding the failure described above. + * @param descriptors the descriptions of the request's form parameters + * @return the snippet + * @since 3.0.0 + */ + public static FormParametersSnippet formParameters(ParameterDescriptor... descriptors) { + return formParameters(Arrays.asList(descriptors)); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The form parameters will be documented using the given + * {@code descriptors}. + *

        + * If a form parameter is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a form + * parameter is documented, is not marked as optional, and is not present in the + * request, a failure will also occur. + *

        + * If you do not want to document a form parameter, a parameter descriptor can be + * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from + * appearing in the generated snippet while avoiding the failure described above. + * @param descriptors the descriptions of the request's form parameters + * @return the snippet + * @since 3.0.0 + */ + public static FormParametersSnippet formParameters(List descriptors) { + return new FormParametersSnippet(descriptors); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The form parameters will be documented using the given + * {@code descriptors}. + *

        + * If a form parameter is documented, is not marked as optional, and is not present in + * the response, a failure will occur. Any undocumented form parameters will be + * ignored. + * @param descriptors the descriptions of the request's form parameters + * @return the snippet + * @since 3.0.0 + */ + public static FormParametersSnippet relaxedFormParameters(ParameterDescriptor... descriptors) { + return relaxedFormParameters(Arrays.asList(descriptors)); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The form parameters will be documented using the given + * {@code descriptors}. *

        * If a parameter is documented, is not marked as optional, and is not present in the - * response, a failure will occur. Any undocumented parameters will be ignored. + * response, a failure will occur. Any undocumented form parameters will be ignored. + * @param descriptors the descriptions of the request's form parameters + * @return the snippet + * @since 3.0.0 + */ + public static FormParametersSnippet relaxedFormParameters(List descriptors) { + return new FormParametersSnippet(descriptors, true); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The given {@code attributes} will be available during snippet + * rendering and the form parameters will be documented using the given + * {@code descriptors} . + *

        + * If a form parameter is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a form + * parameter is documented, is not marked as optional, and is not present in the + * request, a failure will also occur. + *

        + * If you do not want to document a form parameter, a parameter descriptor can be + * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from + * appearing in the generated snippet while avoiding the failure described above. * @param attributes the attributes - * @param descriptors the descriptions of the request's parameters - * @return the snippet that will document the parameters - * @see OperationRequest#getParameters() + * @param descriptors the descriptions of the request's form parameters + * @return the snippet that will document the form parameters + * @since 3.0.0 + */ + public static FormParametersSnippet formParameters(Map attributes, + ParameterDescriptor... descriptors) { + return formParameters(attributes, Arrays.asList(descriptors)); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The given {@code attributes} will be available during snippet + * rendering and the form parameters will be documented using the given + * {@code descriptors} . + *

        + * If a form parameter is present in the request, but is not documented by one of the + * descriptors, a failure will occur when the snippet is invoked. Similarly, if a form + * parameter is documented, is not marked as optional, and is not present in the + * request, a failure will also occur. + *

        + * If you do not want to document a form parameter, a parameter descriptor can be + * marked as {@link ParameterDescriptor#ignored()}. This will prevent it from + * appearing in the generated snippet while avoiding the failure described above. + * @param attributes the attributes + * @param descriptors the descriptions of the request's form parameters + * @return the snippet that will document the form parameters + * @since 3.0.0 + */ + public static FormParametersSnippet formParameters(Map attributes, + List descriptors) { + return new FormParametersSnippet(descriptors, attributes); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The given {@code attributes} will be available during snippet + * rendering and the form parameters will be documented using the given + * {@code descriptors} . + *

        + * If a form parameter is documented, is not marked as optional, and is not present in + * the response, a failure will occur. Any undocumented form parameters will be + * ignored. + * @param attributes the attributes + * @param descriptors the descriptions of the request's form parameters + * @return the snippet that will document the form parameters + * @since 3.0.0 + */ + public static FormParametersSnippet relaxedFormParameters(Map attributes, + ParameterDescriptor... descriptors) { + return relaxedFormParameters(attributes, Arrays.asList(descriptors)); + } + + /** + * Returns a {@code Snippet} that will document the form parameters from the API + * operation's request. The given {@code attributes} will be available during snippet + * rendering and the form parameters will be documented using the given + * {@code descriptors} . + *

        + * If a form parameter is documented, is not marked as optional, and is not present in + * the response, a failure will occur. Any undocumented form parameters will be + * ignored. + * @param attributes the attributes + * @param descriptors the descriptions of the request's form parameters + * @return the snippet that will document the form parameters + * @since 3.0.0 */ - public static RequestParametersSnippet relaxedRequestParameters(Map attributes, + public static FormParametersSnippet relaxedFormParameters(Map attributes, List descriptors) { - return new RequestParametersSnippet(descriptors, attributes, true); + return new FormParametersSnippet(descriptors, attributes, true); } /** @@ -482,7 +644,6 @@ public static RequestPartsSnippet requestParts(Map attributes, * @param attributes the attributes * @param descriptors the descriptions of the request's parts * @return the snippet - * @see OperationRequest#getParameters() */ public static RequestPartsSnippet relaxedRequestParts(Map attributes, RequestPartDescriptor... descriptors) { @@ -499,7 +660,6 @@ public static RequestPartsSnippet relaxedRequestParts(Map attrib * @param attributes the attributes * @param descriptors the descriptions of the request's parts * @return the snippet - * @see OperationRequest#getParameters() */ public static RequestPartsSnippet relaxedRequestParts(Map attributes, List descriptors) { diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java index 95fbb3cce..fb89916b4 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/snippet/TemplatedSnippet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -74,9 +74,9 @@ public void document(Operation operation) throws IOException { RestDocumentationContext context = (RestDocumentationContext) operation.getAttributes() .get(RestDocumentationContext.class.getName()); WriterResolver writerResolver = (WriterResolver) operation.getAttributes().get(WriterResolver.class.getName()); + Map model = createModel(operation); + model.putAll(this.attributes); try (Writer writer = writerResolver.resolve(operation.getName(), this.snippetName, context)) { - Map model = createModel(operation); - model.putAll(this.attributes); TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes() .get(TemplateEngine.class.getName()); writer.append(templateEngine.compileTemplate(this.templateName).render(model)); diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/constraints/DefaultConstraintDescriptions.properties b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/constraints/DefaultConstraintDescriptions.properties index ce699e09a..699b900e2 100644 --- a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/constraints/DefaultConstraintDescriptions.properties +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/constraints/DefaultConstraintDescriptions.properties @@ -1,36 +1,32 @@ -javax.validation.constraints.AssertFalse.description=Must be false -javax.validation.constraints.AssertTrue.description=Must be true -javax.validation.constraints.DecimalMax.description=Must be at most ${value} -javax.validation.constraints.DecimalMin.description=Must be at least ${value} -javax.validation.constraints.Digits.description=Must have at most ${integer} integral digits and ${fraction} fractional digits -javax.validation.constraints.Email.description=Must be a well-formed email address -javax.validation.constraints.Future.description=Must be in the future -javax.validation.constraints.FutureOrPresent.description=Must be in the future or the present -javax.validation.constraints.Max.description=Must be at most ${value} -javax.validation.constraints.Min.description=Must be at least ${value} -javax.validation.constraints.Negative.description=Must be negative -javax.validation.constraints.NegativeOrZero.description=Must be negative or zero -javax.validation.constraints.NotBlank.description=Must not be blank -javax.validation.constraints.NotEmpty.description=Must not be empty -javax.validation.constraints.NotNull.description=Must not be null -javax.validation.constraints.Null.description=Must be null -javax.validation.constraints.Past.description=Must be in the past -javax.validation.constraints.PastOrPresent.description=Must be in the past or the present -javax.validation.constraints.Pattern.description=Must match the regular expression `${regexp}` -javax.validation.constraints.Positive.description=Must be positive -javax.validation.constraints.PositiveOrZero.description=Must be positive or zero -javax.validation.constraints.Size.description=Size must be between ${min} and ${max} inclusive +jakarta.validation.constraints.AssertFalse.description=Must be false +jakarta.validation.constraints.AssertTrue.description=Must be true +jakarta.validation.constraints.DecimalMax.description=Must be at most ${value} +jakarta.validation.constraints.DecimalMin.description=Must be at least ${value} +jakarta.validation.constraints.Digits.description=Must have at most ${integer} integral digits and ${fraction} fractional digits +jakarta.validation.constraints.Email.description=Must be a well-formed email address +jakarta.validation.constraints.Future.description=Must be in the future +jakarta.validation.constraints.FutureOrPresent.description=Must be in the future or the present +jakarta.validation.constraints.Max.description=Must be at most ${value} +jakarta.validation.constraints.Min.description=Must be at least ${value} +jakarta.validation.constraints.Negative.description=Must be negative +jakarta.validation.constraints.NegativeOrZero.description=Must be negative or zero +jakarta.validation.constraints.NotBlank.description=Must not be blank +jakarta.validation.constraints.NotEmpty.description=Must not be empty +jakarta.validation.constraints.NotNull.description=Must not be null +jakarta.validation.constraints.Null.description=Must be null +jakarta.validation.constraints.Past.description=Must be in the past +jakarta.validation.constraints.PastOrPresent.description=Must be in the past or the present +jakarta.validation.constraints.Pattern.description=Must match the regular expression `${regexp}` +jakarta.validation.constraints.Positive.description=Must be positive +jakarta.validation.constraints.PositiveOrZero.description=Must be positive or zero +jakarta.validation.constraints.Size.description=Size must be between ${min} and ${max} inclusive org.hibernate.validator.constraints.CodePointLength.description=Code point length must be between ${min} and ${max} inclusive org.hibernate.validator.constraints.CreditCardNumber.description=Must be a well-formed credit card number org.hibernate.validator.constraints.Currency.description=Must be in an accepted currency unit (${value}) org.hibernate.validator.constraints.EAN.description=Must be a well-formed ${type} number -org.hibernate.validator.constraints.Email.description=Must be a well-formed email address org.hibernate.validator.constraints.Length.description=Length must be between ${min} and ${max} inclusive org.hibernate.validator.constraints.LuhnCheck.description=Must pass the Luhn Modulo 10 checksum algorithm org.hibernate.validator.constraints.Mod10Check.description=Must pass the Mod10 checksum algorithm org.hibernate.validator.constraints.Mod11Check.description=Must pass the Mod11 checksum algorithm -org.hibernate.validator.constraints.NotBlank.description=Must not be blank -org.hibernate.validator.constraints.NotEmpty.description=Must not be empty org.hibernate.validator.constraints.Range.description=Must be at least ${min} and at most ${max} -org.hibernate.validator.constraints.SafeHtml.description=Must be safe HTML org.hibernate.validator.constraints.URL.description=Must be a well-formed URL \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-form-parameters.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-form-parameters.snippet new file mode 100644 index 000000000..9e6f6888a --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-form-parameters.snippet @@ -0,0 +1,9 @@ +|=== +|Parameter|Description + +{{#parameters}} +|{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} +|{{#tableCellContent}}{{description}}{{/tableCellContent}} + +{{/parameters}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-query-parameters.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-query-parameters.snippet new file mode 100644 index 000000000..9e6f6888a --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-query-parameters.snippet @@ -0,0 +1,9 @@ +|=== +|Parameter|Description + +{{#parameters}} +|{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} +|{{#tableCellContent}}{{description}}{{/tableCellContent}} + +{{/parameters}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-body.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-body.snippet index e6cb8e9bd..00da2d085 100644 --- a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-body.snippet +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-body.snippet @@ -1,4 +1,4 @@ -[source,options="nowrap"] +[source{{#language}},{{language}}{{/language}},options="nowrap"] ---- {{body}} ---- \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-cookies.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-cookies.snippet new file mode 100644 index 000000000..0c5315051 --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-cookies.snippet @@ -0,0 +1,9 @@ +|=== +|Name|Description + +{{#cookies}} +|{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} +|{{#tableCellContent}}{{description}}{{/tableCellContent}} + +{{/cookies}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-part-body.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-part-body.snippet index e6cb8e9bd..00da2d085 100644 --- a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-part-body.snippet +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-request-part-body.snippet @@ -1,4 +1,4 @@ -[source,options="nowrap"] +[source{{#language}},{{language}}{{/language}},options="nowrap"] ---- {{body}} ---- \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-response-body.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-response-body.snippet index e6cb8e9bd..00da2d085 100644 --- a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-response-body.snippet +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-response-body.snippet @@ -1,4 +1,4 @@ -[source,options="nowrap"] +[source{{#language}},{{language}}{{/language}},options="nowrap"] ---- {{body}} ---- \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-response-cookies.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-response-cookies.snippet new file mode 100644 index 000000000..0c5315051 --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/asciidoctor/default-response-cookies.snippet @@ -0,0 +1,9 @@ +|=== +|Name|Description + +{{#cookies}} +|{{#tableCellContent}}`+{{name}}+`{{/tableCellContent}} +|{{#tableCellContent}}{{description}}{{/tableCellContent}} + +{{/cookies}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-form-parameters.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-form-parameters.snippet new file mode 100644 index 000000000..681daaa8e --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-form-parameters.snippet @@ -0,0 +1,5 @@ +Parameter | Description +--------- | ----------- +{{#parameters}} +`{{name}}` | {{description}} +{{/parameters}} \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-query-parameters.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-query-parameters.snippet new file mode 100644 index 000000000..681daaa8e --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-query-parameters.snippet @@ -0,0 +1,5 @@ +Parameter | Description +--------- | ----------- +{{#parameters}} +`{{name}}` | {{description}} +{{/parameters}} \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-body.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-body.snippet index b897d4095..6abf3f7e8 100644 --- a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-body.snippet +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-body.snippet @@ -1,3 +1,3 @@ -``` +```{{#language}}{{language}}{{/language}} {{body}} ``` \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-cookies.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-cookies.snippet new file mode 100644 index 000000000..dbc046b82 --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-cookies.snippet @@ -0,0 +1,5 @@ +Name | Description +---- | ----------- +{{#cookies}} +`{{name}}` | {{description}} +{{/cookies}} diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-part-body.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-part-body.snippet index b897d4095..6abf3f7e8 100644 --- a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-part-body.snippet +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-request-part-body.snippet @@ -1,3 +1,3 @@ -``` +```{{#language}}{{language}}{{/language}} {{body}} ``` \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-response-body.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-response-body.snippet index b897d4095..6abf3f7e8 100644 --- a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-response-body.snippet +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-response-body.snippet @@ -1,3 +1,3 @@ -``` +```{{#language}}{{language}}{{/language}} {{body}} ``` \ No newline at end of file diff --git a/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-response-cookies.snippet b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-response-cookies.snippet new file mode 100644 index 000000000..dbc046b82 --- /dev/null +++ b/spring-restdocs-core/src/main/resources/org/springframework/restdocs/templates/markdown/default-response-cookies.snippet @@ -0,0 +1,5 @@ +Name | Description +---- | ----------- +{{#cookies}} +`{{name}}` | {{description}} +{{/cookies}} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java index 42ca747f5..bc0a5d09e 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2025 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. @@ -16,25 +16,16 @@ package org.springframework.restdocs; -import java.util.Arrays; -import java.util.List; - -import org.junit.Rule; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpStatus; import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.GeneratedSnippets; -import org.springframework.restdocs.testfixtures.OperationBuilder; import org.springframework.restdocs.testfixtures.SnippetConditions; import org.springframework.restdocs.testfixtures.SnippetConditions.CodeBlockCondition; import org.springframework.restdocs.testfixtures.SnippetConditions.HttpRequestCondition; import org.springframework.restdocs.testfixtures.SnippetConditions.HttpResponseCondition; import org.springframework.restdocs.testfixtures.SnippetConditions.TableCondition; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; import org.springframework.web.bind.annotation.RequestMethod; /** @@ -42,28 +33,11 @@ * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) public abstract class AbstractSnippetTests { - protected final TemplateFormat templateFormat; - - @Rule - public GeneratedSnippets generatedSnippets; - - @Rule - public OperationBuilder operationBuilder; + protected final TemplateFormat templateFormat = TemplateFormats.asciidoctor(); - @Parameters(name = "{0}") - public static List parameters() { - return Arrays.asList(new Object[] { "Asciidoctor", TemplateFormats.asciidoctor() }, - new Object[] { "Markdown", TemplateFormats.markdown() }); - } - - public AbstractSnippetTests(String name, TemplateFormat templateFormat) { - this.generatedSnippets = new GeneratedSnippets(templateFormat); - this.templateFormat = templateFormat; - this.operationBuilder = new OperationBuilder(this.templateFormat); - } + protected AssertableSnippets snippets; public CodeBlockCondition codeBlock(String language) { return this.codeBlock(language, null); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java index 660164573..3b41392a1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -22,12 +22,13 @@ import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.operation.OperationRequest; @@ -54,7 +55,7 @@ * @author Andy Wilkinson * @author Filip Hrisafov */ -public class RestDocumentationGeneratorTests { +class RestDocumentationGeneratorTests { @SuppressWarnings("unchecked") private final RequestConverter requestConverter = mock(RequestConverter.class); @@ -69,7 +70,8 @@ public class RestDocumentationGeneratorTests { private final OperationRequest operationRequest = new OperationRequestFactory() .create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(), null, null); - private final OperationResponse operationResponse = new OperationResponseFactory().create(0, null, null); + private final OperationResponse operationResponse = new OperationResponseFactory().create(HttpStatus.OK, null, + null); private final Snippet snippet = mock(Snippet.class); @@ -78,7 +80,7 @@ public class RestDocumentationGeneratorTests { private final OperationPreprocessor responsePreprocessor = mock(OperationPreprocessor.class); @Test - public void basicHandling() throws IOException { + void basicHandling() throws IOException { given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); @@ -88,7 +90,7 @@ public void basicHandling() throws IOException { } @Test - public void defaultSnippetsAreCalled() throws IOException { + void defaultSnippetsAreCalled() throws IOException { given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); @@ -105,7 +107,7 @@ public void defaultSnippetsAreCalled() throws IOException { } @Test - public void defaultOperationRequestPreprocessorsAreCalled() throws IOException { + void defaultOperationRequestPreprocessorsAreCalled() throws IOException { given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); @@ -126,7 +128,7 @@ public void defaultOperationRequestPreprocessorsAreCalled() throws IOException { } @Test - public void defaultOperationResponsePreprocessorsAreCalled() throws IOException { + void defaultOperationResponsePreprocessorsAreCalled() throws IOException { given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse); HashMap configuration = new HashMap<>(); @@ -147,7 +149,7 @@ public void defaultOperationResponsePreprocessorsAreCalled() throws IOException } @Test - public void newGeneratorOnlyCallsItsSnippets() throws IOException { + void newGeneratorOnlyCallsItsSnippets() throws IOException { OperationRequestPreprocessor requestPreprocessor = mock(OperationRequestPreprocessor.class); OperationResponsePreprocessor responsePreprocessor = mock(OperationResponsePreprocessor.class); given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest); @@ -197,7 +199,7 @@ private static OperationRequest createRequest() { } private static OperationResponse createResponse() { - return new OperationResponseFactory().create(0, null, null); + return new OperationResponseFactory().create(HttpStatus.OK, null, null); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java index d0dbf6a6a..c69c879bb 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -29,29 +29,28 @@ * @author Tomasz Kopczynski * @author Andy Wilkinson */ -public class ConcatenatingCommandFormatterTests { +class ConcatenatingCommandFormatterTests { private CommandFormatter singleLineFormat = new ConcatenatingCommandFormatter(" "); @Test - public void formattingAnEmptyListProducesAnEmptyString() { + void formattingAnEmptyListProducesAnEmptyString() { assertThat(this.singleLineFormat.format(Collections.emptyList())).isEqualTo(""); } @Test - public void formattingNullProducesAnEmptyString() { + void formattingNullProducesAnEmptyString() { assertThat(this.singleLineFormat.format(null)).isEqualTo(""); } @Test - public void formattingASingleElement() { + void formattingASingleElement() { assertThat(this.singleLineFormat.format(Collections.singletonList("alpha"))).isEqualTo(" alpha"); } @Test - public void formattingMultipleElements() { - assertThat(this.singleLineFormat.format(Arrays.asList("alpha", "bravo"))) - .isEqualTo(String.format(" alpha bravo")); + void formattingMultipleElements() { + assertThat(this.singleLineFormat.format(Arrays.asList("alpha", "bravo"))).isEqualTo(" alpha bravo"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java index f0beb60dc..e0136a1dd 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -17,16 +17,13 @@ package org.springframework.restdocs.cli; import java.io.IOException; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import java.util.Base64; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.util.Base64Utils; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; import static org.assertj.core.api.Assertions.assertThat; @@ -40,265 +37,209 @@ * @author Paul-Christian Volkmer * @author Tomasz Kopczynski */ -@RunWith(Parameterized.class) -public class CurlRequestSnippetTests extends AbstractSnippetTests { +class CurlRequestSnippetTests { private CommandFormatter commandFormatter = CliDocumentation.singleLineFormat(); - public CurlRequestSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } - - @Test - public void getRequest() throws IOException { - new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET")); - } - - @Test - public void getRequestWithParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET")); - } - - @Test - public void nonGetRequest() throws IOException { + @RenderedSnippetTest + void getRequest(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST")); + .document(operationBuilder.request("http://localhost/foo").build()); + assertThat(snippets.curlRequest()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguage("bash").content("$ curl 'http://localhost/foo' -i -X GET")); } - @Test - public void requestWithContent() throws IOException { + @RenderedSnippetTest + void nonGetRequest(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").content("content").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'")); + .document(operationBuilder.request("http://localhost/foo").method("POST").build()); + assertThat(snippets.curlRequest()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguage("bash").content("$ curl 'http://localhost/foo' -i -X POST")); } - @Test - public void getRequestWithQueryString() throws IOException { + @RenderedSnippetTest + void requestWithContent(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); - } - - @Test - public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); + .document(operationBuilder.request("http://localhost/foo").content("content").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X GET -d 'content'")); } - @Test - public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { + @RenderedSnippetTest + void getRequestWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); + .document(operationBuilder.request("http://localhost/foo?param=value").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo?param=value' -i -X GET")); } - @Test - public void getRequestWithDisjointQueryStringAndParameters() throws IOException { + @RenderedSnippetTest + void getRequestWithQueryStringWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); + .document(operationBuilder.request("http://localhost/foo?param").build()); + assertThat(snippets.curlRequest()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguage("bash").content("$ curl 'http://localhost/foo?param' -i -X GET")); } - @Test - public void getRequestWithQueryStringWithNoValue() throws IOException { + @RenderedSnippetTest + void postRequestWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X GET")); + .document(operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo?param=value' -i -X POST")); } - @Test - public void postRequestWithQueryString() throws IOException { + @RenderedSnippetTest + void postRequestWithQueryStringWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X POST")); + .document(operationBuilder.request("http://localhost/foo?param").method("POST").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo?param' -i -X POST")); } - @Test - public void postRequestWithQueryStringWithNoValue() throws IOException { + @RenderedSnippetTest + void postRequestWithOneParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X POST")); + .document(operationBuilder.request("http://localhost/foo").method("POST").content("k1=v1").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); } - @Test - public void postRequestWithOneParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); - } - - @Test - public void postRequestWithOneParameterWithNoValue() throws IOException { - new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='")); - } - - @Test - public void postRequestWithMultipleParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void postRequestWithOneParameterAndExplicitContentType(OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .method("POST") - .param("k1", "v1", "v1-bis") - .param("k2", "v2") + .content("k1=v1") .build()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo' -i -X POST" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); } - @Test - public void postRequestWithUrlEncodedParameter() throws IOException { + @RenderedSnippetTest + void postRequestWithOneParameterWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); + .document(operationBuilder.request("http://localhost/foo").method("POST").content("k1=").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1='")); } - @Test - public void postRequestWithDisjointQueryStringAndParameter() throws IOException { - new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .method("POST") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); + @RenderedSnippetTest + void postRequestWithMultipleParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .method("POST") + .content("k1=v1&k1=v1-bis&k2=v2") + .build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X POST" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); } - @Test - public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { + @RenderedSnippetTest + void postRequestWithUrlEncodedParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") - .method("POST") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST")); + .document(operationBuilder.request("http://localhost/foo").method("POST").content("k1=a%26b").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); } - @Test - public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .method("POST") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); - } - - @Test - public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void postRequestWithJsonData(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .method("POST") - .content("a=alpha&b=bravo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param("a", "alpha") - .param("b", "bravo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .content("{\"a\":\"alpha\"}") .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST " - + "-H 'Content-Type: application/x-www-form-urlencoded' " + "-d 'a=alpha&b=bravo'")); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content( + "$ curl 'http://localhost/foo' -i -X POST -H 'Content-Type: application/json' -d '{\"a\":\"alpha\"}'")); } - @Test - public void putRequestWithOneParameter() throws IOException { + @RenderedSnippetTest + void putRequestWithOneParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); + .document(operationBuilder.request("http://localhost/foo").method("PUT").content("k1=v1").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); } - @Test - public void putRequestWithMultipleParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void putRequestWithMultipleParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .method("PUT") - .param("k1", "v1") - .param("k1", "v1-bis") - .param("k2", "v2") + .content("k1=v1&k1=v1-bis&k2=v2") .build()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo' -i -X PUT" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X PUT" + " -d 'k1=v1&k1=v1-bis&k2=v2'")); } - @Test - public void putRequestWithUrlEncodedParameter() throws IOException { + @RenderedSnippetTest + void putRequestWithUrlEncodedParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); + .document(operationBuilder.request("http://localhost/foo").method("PUT").content("k1=a%26b").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); } - @Test - public void requestWithHeaders() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void requestWithHeaders(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha") .build()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent( - "$ curl 'http://localhost/foo' -i -X GET" + " -H 'Content-Type: application/json' -H 'a: alpha'")); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X GET" + " -H 'Content-Type: application/json' -H 'a: alpha'")); } - @Test - public void requestWithHeadersMultiline() throws IOException { + @RenderedSnippetTest + void requestWithHeadersMultiline(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new CurlRequestSnippet(CliDocumentation.multiLineFormat()) - .document(this.operationBuilder.request("http://localhost/foo") + .document(operationBuilder.request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha") .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n" + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n" + " -H 'Content-Type: application/json' \\%n" + " -H 'a: alpha'"))); } - @Test - public void requestWithCookies() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void requestWithCookies(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .cookie("name1", "value1") .cookie("name2", "value2") .build()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo' -i -X GET" + " --cookie 'name1=value1;name2=value2'")); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X GET" + " --cookie 'name1=value1;name2=value2'")); } - @Test - public void multipartPostWithNoSubmittedFileName() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") + @RenderedSnippetTest + void multipartPostWithNoSubmittedFileName(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/upload") .method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("metadata", "{\"description\": \"foo\"}".getBytes()) .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'metadata={\"description\": \"foo\"}'"; - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); + assertThat(snippets.curlRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content(expectedContent)); } - @Test - public void multipartPostWithContentType() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") + @RenderedSnippetTest + void multipartPostWithContentType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/upload") .method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) @@ -307,12 +248,13 @@ public void multipartPostWithContentType() throws IOException { .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png;type=image/png'"; - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); + assertThat(snippets.curlRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content(expectedContent)); } - @Test - public void multipartPost() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") + @RenderedSnippetTest + void multipartPost(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/upload") .method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) @@ -320,93 +262,38 @@ public void multipartPost() throws IOException { .build()); String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png'"; - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); - } - - @Test - public void multipartPostWithParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]) - .submittedFileName("documents/images/example.png") - .and() - .param("a", "apple", "avocado") - .param("b", "banana") - .build()); - String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " - + "'Content-Type: multipart/form-data' -F " - + "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " + "-F 'b=banana'"; - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); - } - - @Test - public void multipartPostWithOverlappingPartsAndParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]) - .submittedFileName("documents/images/example.png") - .and() - .part("a", "apple".getBytes()) - .and() - .param("a", "apple") - .build()); - String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " - + "'Content-Type: multipart/form-data' -F 'image=@documents/images/example.png' -F 'a=apple'"; - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent)); + assertThat(snippets.curlRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content(expectedContent)); } - @Test - public void basicAuthCredentialsAreSuppliedUsingUserOption() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) + @RenderedSnippetTest + void basicAuthCredentialsAreSuppliedUsingUserOption(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:secret".getBytes())) .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET")); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET")); } - @Test - public void customAttributes() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void customAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new CurlRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .header(HttpHeaders.HOST, "api.example.com") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha") .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'" + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'" + " -H 'Content-Type: application/json' -H 'a: alpha'")); } - @Test - public void postWithContentAndParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .param("a", "alpha") - .method("POST") - .param("b", "bravo") - .content("Some content") - .build()); - assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") - .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X POST -d 'Some content'")); - } - - @Test - public void deleteWithParameters() throws IOException { - new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("DELETE") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X DELETE")); - } - - @Test - public void deleteWithQueryString() throws IOException { + @RenderedSnippetTest + void deleteWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new CurlRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); - assertThat(this.generatedSnippets.curlRequest()) - .is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X DELETE")); + .document(operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); + assertThat(snippets.curlRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X DELETE")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java index 26887ca11..89500ef06 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -17,16 +17,13 @@ package org.springframework.restdocs.cli; import java.io.IOException; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import java.util.Base64; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.util.Base64Utils; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; import static org.assertj.core.api.Assertions.assertThat; @@ -41,377 +38,257 @@ * @author Raman Gupta * @author Tomasz Kopczynski */ -@RunWith(Parameterized.class) -public class HttpieRequestSnippetTests extends AbstractSnippetTests { +class HttpieRequestSnippetTests { private CommandFormatter commandFormatter = CliDocumentation.singleLineFormat(); - public HttpieRequestSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } - - @Test - public void getRequest() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'")); - } - - @Test - public void getRequestWithParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha'")); - } - - @Test - public void nonGetRequest() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo'")); - } - - @Test - public void requestWithContent() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").content("content").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ echo 'content' | http GET 'http://localhost/foo'")); - } - - @Test - public void getRequestWithQueryString() throws IOException { + @RenderedSnippetTest + void getRequest(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'")); + .document(operationBuilder.request("http://localhost/foo").build()); + assertThat(snippets.httpieRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content("$ http GET 'http://localhost/foo'")); } - @Test - public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document( - this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'")); - } - - @Test - public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { + @RenderedSnippetTest + void nonGetRequest(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); + .document(operationBuilder.request("http://localhost/foo").method("POST").build()); + assertThat(snippets.httpieRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content("$ http POST 'http://localhost/foo'")); } - @Test - public void getRequestWithDisjointQueryStringAndParameters() throws IOException { + @RenderedSnippetTest + void requestWithContent(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); + .document(operationBuilder.request("http://localhost/foo").content("content").build()); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ echo 'content' | http GET 'http://localhost/foo'")); } - @Test - public void getRequestWithQueryStringWithNoValue() throws IOException { + @RenderedSnippetTest + void getRequestWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'")); + .document(operationBuilder.request("http://localhost/foo?param=value").build()); + assertThat(snippets.httpieRequest()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguage("bash").content("$ http GET 'http://localhost/foo?param=value'")); } - @Test - public void postRequestWithQueryString() throws IOException { + @RenderedSnippetTest + void getRequestWithQueryStringWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param=value'")); + .document(operationBuilder.request("http://localhost/foo?param").build()); + assertThat(snippets.httpieRequest()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguage("bash").content("$ http GET 'http://localhost/foo?param'")); } - @Test - public void postRequestWithQueryStringWithNoValue() throws IOException { + @RenderedSnippetTest + void postRequestWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param'")); + .document(operationBuilder.request("http://localhost/foo?param=value").method("POST").build()); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http POST 'http://localhost/foo?param=value'")); } - @Test - public void postRequestWithOneParameter() throws IOException { + @RenderedSnippetTest + void postRequestWithQueryStringWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'")); + .document(operationBuilder.request("http://localhost/foo?param").method("POST").build()); + assertThat(snippets.httpieRequest()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguage("bash").content("$ http POST 'http://localhost/foo?param'")); } - @Test - public void postRequestWithOneParameterWithNoValue() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1='")); - } - - @Test - public void postRequestWithMultipleParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void postRequestWithOneParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .method("POST") - .param("k1", "v1", "v1-bis") - .param("k2", "v2") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .content("k1=v1") .build()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http --form POST 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); - } - - @Test - public void postRequestWithUrlEncodedParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'")); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --form POST 'http://localhost/foo' 'k1=v1'")); } - @Test - public void postRequestWithDisjointQueryStringAndParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .method("POST") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); - } - - @Test - public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") - .method("POST") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'")); + @RenderedSnippetTest + void postRequestWithOneParameterWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .content("k1") + .build()); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --form POST 'http://localhost/foo' 'k1='")); } - @Test - public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .method("POST") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); + @RenderedSnippetTest + void postRequestWithMultipleParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .content("k1=v1&k1=v1-bis&k2=v2") + .build()); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --form POST 'http://localhost/foo' 'k1=v1' 'k1=v1-bis' 'k2=v2'")); } - @Test - public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void postRequestWithUrlEncodedParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .method("POST") - .content("a=alpha&b=bravo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param("a", "alpha") - .param("b", "bravo") + .content("k1=a%26b") .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' " - + "'Content-Type:application/x-www-form-urlencoded'")); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --form POST 'http://localhost/foo' 'k1=a&b'")); } - @Test - public void putRequestWithOneParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'")); + @RenderedSnippetTest + void putRequestWithOneParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .method("PUT") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .content("k1=v1") + .build()); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --form PUT 'http://localhost/foo' 'k1=v1'")); } - @Test - public void putRequestWithMultipleParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void putRequestWithMultipleParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .method("PUT") - .param("k1", "v1") - .param("k1", "v1-bis") - .param("k2", "v2") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .content("k1=v1&k1=v1-bis&k2=v2") .build()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http --form PUT 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --form PUT 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); } - @Test - public void putRequestWithUrlEncodedParameter() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'")); + @RenderedSnippetTest + void putRequestWithUrlEncodedParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .method("PUT") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .content("k1=a%26b") + .build()); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --form PUT 'http://localhost/foo' 'k1=a&b'")); } - @Test - public void requestWithHeaders() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void requestWithHeaders(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha") .build()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http GET 'http://localhost/foo'" + " 'Content-Type:application/json' 'a:alpha'")); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content(("$ http GET 'http://localhost/foo'" + " 'Content-Type:application/json' 'a:alpha'"))); } - @Test - public void requestWithHeadersMultiline() throws IOException { + @RenderedSnippetTest + void requestWithHeadersMultiline(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new HttpieRequestSnippet(CliDocumentation.multiLineFormat()) - .document(this.operationBuilder.request("http://localhost/foo") + .document(operationBuilder.request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha") .build()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(String.format( - "$ http GET 'http://localhost/foo' \\%n" + " 'Content-Type:application/json' \\%n 'a:alpha'"))); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content(String.format("$ http GET 'http://localhost/foo' \\%n" + + " 'Content-Type:application/json' \\%n 'a:alpha'"))); } - @Test - public void requestWithCookies() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void requestWithCookies(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .cookie("name1", "value1") .cookie("name2", "value2") .build()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ http GET 'http://localhost/foo'" + " 'Cookie:name1=value1' 'Cookie:name2=value2'")); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content(("$ http GET 'http://localhost/foo'" + " 'Cookie:name1=value1' 'Cookie:name2=value2'"))); } - @Test - public void multipartPostWithNoSubmittedFileName() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("metadata", "{\"description\": \"foo\"}".getBytes()) - .build()); + @RenderedSnippetTest + void multipartPostWithNoSubmittedFileName(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("metadata", "{\"description\": \"foo\"}".getBytes()) + .build()); String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'metadata'='{\"description\": \"foo\"}'"; - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); + assertThat(snippets.httpieRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content(expectedContent)); } - @Test - public void multipartPostWithContentType() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]) - .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) - .submittedFileName("documents/images/example.png") - .build()); + @RenderedSnippetTest + void multipartPostWithContentType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) + .submittedFileName("documents/images/example.png") + .build()); // httpie does not yet support manually set content type by part String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png'"; - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); + assertThat(snippets.httpieRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content(expectedContent)); } - @Test - public void multipartPost() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]) - .submittedFileName("documents/images/example.png") - .build()); + @RenderedSnippetTest + void multipartPost(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/upload") + .method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .part("image", new byte[0]) + .submittedFileName("documents/images/example.png") + .build()); String expectedContent = "$ http --multipart POST 'http://localhost/upload'" + " 'image'@'documents/images/example.png'"; - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); - } - - @Test - public void multipartPostWithParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]) - .submittedFileName("documents/images/example.png") - .and() - .param("a", "apple", "avocado") - .param("b", "banana") - .build()); - String expectedContent = "$ http --multipart POST 'http://localhost/upload'" - + " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" + " 'b=banana'"; - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); + assertThat(snippets.httpieRequest()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash").content(expectedContent)); } - @Test - public void multipartPostWithOverlappingPartsAndParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", new byte[0]) - .submittedFileName("documents/images/example.png") - .and() - .part("a", "apple".getBytes()) - .and() - .param("a", "apple") - .build()); - String expectedContent = "$ http --multipart POST 'http://localhost/upload'" - + " 'image'@'documents/images/example.png' 'a'='apple'"; - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent)); - } - - @Test - public void basicAuthCredentialsAreSuppliedUsingAuthOption() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) + @RenderedSnippetTest + void basicAuthCredentialsAreSuppliedUsingAuthOption(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") + .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:secret".getBytes())) .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'")); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http --auth 'user:secret' GET 'http://localhost/foo'")); } - @Test - public void customAttributes() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void customAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpieRequestSnippet(this.commandFormatter).document(operationBuilder.request("http://localhost/foo") .header(HttpHeaders.HOST, "api.example.com") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha") .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'" + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http GET 'http://localhost/foo' 'Host:api.example.com'" + " 'Content-Type:application/json' 'a:alpha'")); } - @Test - public void postWithContentAndParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("POST") - .param("a", "alpha") - .param("b", "bravo") - .content("Some content") - .build()); - assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") - .withContent("$ echo 'Some content' | http POST " + "'http://localhost/foo?a=alpha&b=bravo'")); - } - - @Test - public void deleteWithParameters() throws IOException { - new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo") - .method("DELETE") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http DELETE 'http://localhost/foo?a=alpha&b=bravo'")); - } - - @Test - public void deleteWithQueryString() throws IOException { + @RenderedSnippetTest + void deleteWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpieRequestSnippet(this.commandFormatter) - .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); - assertThat(this.generatedSnippets.httpieRequest()) - .is(codeBlock("bash").withContent("$ http DELETE 'http://localhost/foo?a=alpha&b=bravo'")); + .document(operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); + assertThat(snippets.httpieRequest()).isCodeBlock((codeBlock) -> codeBlock.withLanguage("bash") + .content("$ http DELETE 'http://localhost/foo?a=alpha&b=bravo'")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java index 06c30145b..aa6c68141 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -23,7 +23,7 @@ import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -63,13 +63,13 @@ * @author Andy Wilkinson * @author Filip Hrisafov */ -public class RestDocumentationConfigurerTests { +class RestDocumentationConfigurerTests { private final TestRestDocumentationConfigurer configurer = new TestRestDocumentationConfigurer(); @SuppressWarnings("unchecked") @Test - public void defaultConfiguration() { + void defaultConfiguration() { Map configuration = new HashMap<>(); this.configurer.apply(configuration, createContext()); assertThat(configuration).containsKey(TemplateEngine.class.getName()); @@ -102,7 +102,7 @@ public void defaultConfiguration() { } @Test - public void customTemplateEngine() { + void customTemplateEngine() { Map configuration = new HashMap<>(); TemplateEngine templateEngine = mock(TemplateEngine.class); this.configurer.templateEngine(templateEngine).apply(configuration, createContext()); @@ -110,7 +110,7 @@ public void customTemplateEngine() { } @Test - public void customWriterResolver() { + void customWriterResolver() { Map configuration = new HashMap<>(); WriterResolver writerResolver = mock(WriterResolver.class); this.configurer.writerResolver(writerResolver).apply(configuration, createContext()); @@ -118,7 +118,7 @@ public void customWriterResolver() { } @Test - public void customDefaultSnippets() { + void customDefaultSnippets() { Map configuration = new HashMap<>(); this.configurer.snippets().withDefaults(CliDocumentation.curlRequest()).apply(configuration, createContext()); assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); @@ -133,7 +133,7 @@ public void customDefaultSnippets() { @SuppressWarnings("unchecked") @Test - public void additionalDefaultSnippets() { + void additionalDefaultSnippets() { Map configuration = new HashMap<>(); Snippet snippet = mock(Snippet.class); this.configurer.snippets().withAdditionalDefaults(snippet).apply(configuration, createContext()); @@ -148,7 +148,7 @@ public void additionalDefaultSnippets() { } @Test - public void customSnippetEncoding() { + void customSnippetEncoding() { Map configuration = new HashMap<>(); this.configurer.snippets().withEncoding("ISO-8859-1"); this.configurer.apply(configuration, createContext()); @@ -162,7 +162,7 @@ public void customSnippetEncoding() { } @Test - public void customTemplateFormat() { + void customTemplateFormat() { Map configuration = new HashMap<>(); this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown()).apply(configuration, createContext()); assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); @@ -174,7 +174,7 @@ public void customTemplateFormat() { @SuppressWarnings("unchecked") @Test - public void asciidoctorTableCellContentLambaIsInstalledWhenUsingAsciidoctorTemplateFormat() { + void asciidoctorTableCellContentLambaIsInstalledWhenUsingAsciidoctorTemplateFormat() { Map configuration = new HashMap<>(); this.configurer.apply(configuration, createContext()); TemplateEngine templateEngine = (TemplateEngine) configuration.get(TemplateEngine.class.getName()); @@ -187,7 +187,7 @@ public void asciidoctorTableCellContentLambaIsInstalledWhenUsingAsciidoctorTempl @SuppressWarnings("unchecked") @Test - public void asciidoctorTableCellContentLambaIsNotInstalledWhenUsingNonAsciidoctorTemplateFormat() { + void asciidoctorTableCellContentLambaIsNotInstalledWhenUsingNonAsciidoctorTemplateFormat() { Map configuration = new HashMap<>(); this.configurer.snippetConfigurer.withTemplateFormat(TemplateFormats.markdown()); this.configurer.apply(configuration, createContext()); @@ -199,10 +199,10 @@ public void asciidoctorTableCellContentLambaIsNotInstalledWhenUsingNonAsciidocto } @Test - public void customDefaultOperationRequestPreprocessor() { + void customDefaultOperationRequestPreprocessor() { Map configuration = new HashMap<>(); this.configurer.operationPreprocessors() - .withRequestDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) + .withRequestDefaults(Preprocessors.prettyPrint(), Preprocessors.modifyHeaders().remove("Foo")) .apply(configuration, createContext()); OperationRequestPreprocessor preprocessor = (OperationRequestPreprocessor) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); @@ -210,21 +210,21 @@ public void customDefaultOperationRequestPreprocessor() { headers.add("Foo", "value"); OperationRequest request = new OperationRequestFactory().create(URI.create("http://localhost:8080"), HttpMethod.GET, null, headers, null, Collections.emptyList()); - assertThat(preprocessor.preprocess(request).getHeaders()).doesNotContainKey("Foo"); + assertThat(preprocessor.preprocess(request).getHeaders().headerNames()).doesNotContain("Foo"); } @Test - public void customDefaultOperationResponsePreprocessor() { + void customDefaultOperationResponsePreprocessor() { Map configuration = new HashMap<>(); this.configurer.operationPreprocessors() - .withResponseDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo")) + .withResponseDefaults(Preprocessors.prettyPrint(), Preprocessors.modifyHeaders().remove("Foo")) .apply(configuration, createContext()); OperationResponsePreprocessor preprocessor = (OperationResponsePreprocessor) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); HttpHeaders headers = new HttpHeaders(); headers.add("Foo", "value"); - OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK.value(), headers, null); - assertThat(preprocessor.preprocess(response).getHeaders()).doesNotContainKey("Foo"); + OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK, headers, null); + assertThat(preprocessor.preprocess(response).getHeaders().headerNames()).doesNotContain("Foo"); } private RestDocumentationContext createContext() { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java index a60f0b135..c5425c38c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @@ -30,7 +30,7 @@ * * @author Andy Wilkinson */ -public class ConstraintDescriptionsTests { +class ConstraintDescriptionsTests { private final ConstraintResolver constraintResolver = mock(ConstraintResolver.class); @@ -41,7 +41,7 @@ public class ConstraintDescriptionsTests { this.constraintResolver, this.constraintDescriptionResolver); @Test - public void descriptionsForConstraints() { + void descriptionsForConstraints() { Constraint constraint1 = new Constraint("constraint1", Collections.emptyMap()); Constraint constraint2 = new Constraint("constraint2", Collections.emptyMap()); given(this.constraintResolver.resolveForProperty("foo", Constrained.class)) @@ -52,13 +52,13 @@ public void descriptionsForConstraints() { } @Test - public void emptyListOfDescriptionsWhenThereAreNoConstraints() { + void emptyListOfDescriptionsWhenThereAreNoConstraints() { given(this.constraintResolver.resolveForProperty("foo", Constrained.class)) .willReturn(Collections.emptyList()); assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size()).isEqualTo(0); } - private static class Constrained { + private static final class Constrained { } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java index 0f249638b..7a977a9a3 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -21,34 +21,36 @@ import java.net.URL; import java.util.Collections; import java.util.Date; +import java.util.HashSet; import java.util.List; import java.util.ListResourceBundle; import java.util.ResourceBundle; +import java.util.Set; import javax.money.MonetaryAmount; -import javax.validation.constraints.AssertFalse; -import javax.validation.constraints.AssertTrue; -import javax.validation.constraints.DecimalMax; -import javax.validation.constraints.DecimalMin; -import javax.validation.constraints.Digits; -import javax.validation.constraints.Email; -import javax.validation.constraints.Future; -import javax.validation.constraints.FutureOrPresent; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.Negative; -import javax.validation.constraints.NegativeOrZero; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Null; -import javax.validation.constraints.Past; -import javax.validation.constraints.PastOrPresent; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Positive; -import javax.validation.constraints.PositiveOrZero; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.AssertFalse; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.DecimalMax; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.Digits; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.Future; +import jakarta.validation.constraints.FutureOrPresent; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Negative; +import jakarta.validation.constraints.NegativeOrZero; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Null; +import jakarta.validation.constraints.Past; +import jakarta.validation.constraints.PastOrPresent; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.PositiveOrZero; +import jakarta.validation.constraints.Size; import org.hibernate.validator.constraints.CodePointLength; import org.hibernate.validator.constraints.CreditCardNumber; import org.hibernate.validator.constraints.Currency; @@ -58,11 +60,14 @@ import org.hibernate.validator.constraints.Mod10Check; import org.hibernate.validator.constraints.Mod11Check; import org.hibernate.validator.constraints.Range; -import org.hibernate.validator.constraints.SafeHtml; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -72,199 +77,183 @@ * * @author Andy Wilkinson */ -public class ResourceBundleConstraintDescriptionResolverTests { +class ResourceBundleConstraintDescriptionResolverTests { private final ResourceBundleConstraintDescriptionResolver resolver = new ResourceBundleConstraintDescriptionResolver(); @Test - public void defaultMessageAssertFalse() { + void defaultMessageAssertFalse() { assertThat(constraintDescriptionForField("assertFalse")).isEqualTo("Must be false"); } @Test - public void defaultMessageAssertTrue() { + void defaultMessageAssertTrue() { assertThat(constraintDescriptionForField("assertTrue")).isEqualTo("Must be true"); } @Test - public void defaultMessageCodePointLength() { + void defaultMessageCodePointLength() { assertThat(constraintDescriptionForField("codePointLength")) .isEqualTo("Code point length must be between 2 and 5 inclusive"); } @Test - public void defaultMessageCurrency() { + void defaultMessageCurrency() { assertThat(constraintDescriptionForField("currency")) .isEqualTo("Must be in an accepted currency unit (GBP, USD)"); } @Test - public void defaultMessageDecimalMax() { + void defaultMessageDecimalMax() { assertThat(constraintDescriptionForField("decimalMax")).isEqualTo("Must be at most 9.875"); } @Test - public void defaultMessageDecimalMin() { + void defaultMessageDecimalMin() { assertThat(constraintDescriptionForField("decimalMin")).isEqualTo("Must be at least 1.5"); } @Test - public void defaultMessageDigits() { + void defaultMessageDigits() { assertThat(constraintDescriptionForField("digits")) .isEqualTo("Must have at most 2 integral digits and 5 fractional digits"); } @Test - public void defaultMessageFuture() { + void defaultMessageFuture() { assertThat(constraintDescriptionForField("future")).isEqualTo("Must be in the future"); } @Test - public void defaultMessageFutureOrPresent() { + void defaultMessageFutureOrPresent() { assertThat(constraintDescriptionForField("futureOrPresent")).isEqualTo("Must be in the future or the present"); } @Test - public void defaultMessageMax() { + void defaultMessageMax() { assertThat(constraintDescriptionForField("max")).isEqualTo("Must be at most 10"); } @Test - public void defaultMessageMin() { + void defaultMessageMin() { assertThat(constraintDescriptionForField("min")).isEqualTo("Must be at least 10"); } @Test - public void defaultMessageNotNull() { + void defaultMessageNotNull() { assertThat(constraintDescriptionForField("notNull")).isEqualTo("Must not be null"); } @Test - public void defaultMessageNull() { + void defaultMessageNull() { assertThat(constraintDescriptionForField("nul")).isEqualTo("Must be null"); } @Test - public void defaultMessagePast() { + void defaultMessagePast() { assertThat(constraintDescriptionForField("past")).isEqualTo("Must be in the past"); } @Test - public void defaultMessagePastOrPresent() { + void defaultMessagePastOrPresent() { assertThat(constraintDescriptionForField("pastOrPresent")).isEqualTo("Must be in the past or the present"); } @Test - public void defaultMessagePattern() { + void defaultMessagePattern() { assertThat(constraintDescriptionForField("pattern")) .isEqualTo("Must match the regular expression `[A-Z][a-z]+`"); } @Test - public void defaultMessageSize() { + void defaultMessageSize() { assertThat(constraintDescriptionForField("size")).isEqualTo("Size must be between 2 and 10 inclusive"); } @Test - public void defaultMessageCreditCardNumber() { + void defaultMessageCreditCardNumber() { assertThat(constraintDescriptionForField("creditCardNumber")) .isEqualTo("Must be a well-formed credit card number"); } @Test - public void defaultMessageEan() { + void defaultMessageEan() { assertThat(constraintDescriptionForField("ean")).isEqualTo("Must be a well-formed EAN13 number"); } @Test - public void defaultMessageEmail() { + void defaultMessageEmail() { assertThat(constraintDescriptionForField("email")).isEqualTo("Must be a well-formed email address"); } @Test - public void defaultMessageEmailHibernateValidator() { - assertThat(constraintDescriptionForField("emailHibernateValidator")) - .isEqualTo("Must be a well-formed email address"); - } - - @Test - public void defaultMessageLength() { + void defaultMessageLength() { assertThat(constraintDescriptionForField("length")).isEqualTo("Length must be between 2 and 10 inclusive"); } @Test - public void defaultMessageLuhnCheck() { + void defaultMessageLuhnCheck() { assertThat(constraintDescriptionForField("luhnCheck")) .isEqualTo("Must pass the Luhn Modulo 10 checksum algorithm"); } @Test - public void defaultMessageMod10Check() { + void defaultMessageMod10Check() { assertThat(constraintDescriptionForField("mod10Check")).isEqualTo("Must pass the Mod10 checksum algorithm"); } @Test - public void defaultMessageMod11Check() { + void defaultMessageMod11Check() { assertThat(constraintDescriptionForField("mod11Check")).isEqualTo("Must pass the Mod11 checksum algorithm"); } @Test - public void defaultMessageNegative() { + void defaultMessageNegative() { assertThat(constraintDescriptionForField("negative")).isEqualTo("Must be negative"); } @Test - public void defaultMessageNegativeOrZero() { + void defaultMessageNegativeOrZero() { assertThat(constraintDescriptionForField("negativeOrZero")).isEqualTo("Must be negative or zero"); } @Test - public void defaultMessageNotBlank() { + void defaultMessageNotBlank() { assertThat(constraintDescriptionForField("notBlank")).isEqualTo("Must not be blank"); } @Test - public void defaultMessageNotBlankHibernateValidator() { - assertThat(constraintDescriptionForField("notBlankHibernateValidator")).isEqualTo("Must not be blank"); - } - - @Test - public void defaultMessageNotEmpty() { + void defaultMessageNotEmpty() { assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty"); } @Test - public void defaultMessageNotEmptyHibernateValidator() { + void defaultMessageNotEmptyHibernateValidator() { assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty"); } @Test - public void defaultMessagePositive() { + void defaultMessagePositive() { assertThat(constraintDescriptionForField("positive")).isEqualTo("Must be positive"); } @Test - public void defaultMessagePositiveOrZero() { + void defaultMessagePositiveOrZero() { assertThat(constraintDescriptionForField("positiveOrZero")).isEqualTo("Must be positive or zero"); } @Test - public void defaultMessageRange() { + void defaultMessageRange() { assertThat(constraintDescriptionForField("range")).isEqualTo("Must be at least 10 and at most 100"); } @Test - public void defaultMessageSafeHtml() { - assertThat(constraintDescriptionForField("safeHtml")).isEqualTo("Must be safe HTML"); - } - - @Test - public void defaultMessageUrl() { + void defaultMessageUrl() { assertThat(constraintDescriptionForField("url")).isEqualTo("Must be a well-formed URL"); } @Test - public void customMessage() { + void customMessage() { Thread.currentThread().setContextClassLoader(new ClassLoader() { @Override @@ -290,7 +279,7 @@ public URL getResource(String name) { } @Test - public void customResourceBundle() { + void customResourceBundle() { ResourceBundle bundle = new ListResourceBundle() { @Override @@ -304,6 +293,29 @@ protected Object[][] getContents() { assertThat(description).isEqualTo("Not null"); } + @Test + void allBeanValidationConstraintsAreTested() throws Exception { + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + Resource[] resources = resolver.getResources("jakarta/validation/constraints/*.class"); + Set> beanValidationConstraints = new HashSet<>(); + for (Resource resource : resources) { + String className = ClassUtils.convertResourcePathToClassName(((ClassPathResource) resource).getPath()); + if (className.endsWith(".class")) { + className = className.substring(0, className.length() - 6); + } + Class type = Class.forName(className); + if (type.isAnnotation() && type.isAnnotationPresent(jakarta.validation.Constraint.class)) { + beanValidationConstraints.add(type); + } + } + ReflectionUtils.doWithFields(Constrained.class, (field) -> { + for (Annotation annotation : field.getAnnotations()) { + beanValidationConstraints.remove(annotation.annotationType()); + } + }); + assertThat(beanValidationConstraints).isEmpty(); + } + private String constraintDescriptionForField(String name) { return this.resolver.resolveDescription(getConstraintFromField(name)); } @@ -316,7 +328,7 @@ private Constraint getConstraintFromField(String name) { AnnotationUtils.getAnnotationAttributes(annotations[0])); } - private static class Constrained { + private static final class Constrained { @AssertFalse private boolean assertFalse; @@ -378,10 +390,6 @@ private static class Constrained { @Email private String email; - @SuppressWarnings("deprecation") - @org.hibernate.validator.constraints.Email - private String emailHibernateValidator; - @Length(min = 2, max = 10) private String length; @@ -403,17 +411,9 @@ private static class Constrained { @NotBlank private String notBlank; - @SuppressWarnings("deprecation") - @org.hibernate.validator.constraints.NotBlank - private String notBlankHibernateValidator; - @NotEmpty private String notEmpty; - @SuppressWarnings("deprecation") - @org.hibernate.validator.constraints.NotEmpty - private String notEmptyHibernateValidator; - @Positive private int positive; @@ -423,9 +423,6 @@ private static class Constrained { @Range(min = 10, max = 100) private int range; - @SafeHtml - private String safeHtml; - @org.hibernate.validator.constraints.URL private String url; diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java index 1106f842f..203817f81 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -26,17 +26,16 @@ import java.util.Map; import java.util.Map.Entry; -import javax.validation.Payload; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Null; -import javax.validation.constraints.Size; - +import jakarta.validation.Payload; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Null; +import jakarta.validation.constraints.Size; import org.assertj.core.api.Condition; import org.assertj.core.description.TextDescription; import org.hibernate.validator.constraints.CompositionType; import org.hibernate.validator.constraints.ConstraintComposition; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -45,19 +44,19 @@ * * @author Andy Wilkinson */ -public class ValidatorConstraintResolverTests { +class ValidatorConstraintResolverTests { private final ValidatorConstraintResolver resolver = new ValidatorConstraintResolver(); @Test - public void singleFieldConstraint() { + void singleFieldConstraint() { List constraints = this.resolver.resolveForProperty("single", ConstrainedFields.class); assertThat(constraints).hasSize(1); assertThat(constraints.get(0).getName()).isEqualTo(NotNull.class.getName()); } @Test - public void multipleFieldConstraints() { + void multipleFieldConstraints() { List constraints = this.resolver.resolveForProperty("multiple", ConstrainedFields.class); assertThat(constraints).hasSize(2); assertThat(constraints.get(0)).is(constraint(NotNull.class)); @@ -65,13 +64,13 @@ public void multipleFieldConstraints() { } @Test - public void noFieldConstraints() { + void noFieldConstraints() { List constraints = this.resolver.resolveForProperty("none", ConstrainedFields.class); assertThat(constraints).hasSize(0); } @Test - public void compositeConstraint() { + void compositeConstraint() { List constraints = this.resolver.resolveForProperty("composite", ConstrainedFields.class); assertThat(constraints).hasSize(1); } @@ -80,7 +79,7 @@ private ConstraintCondition constraint(final Class annotat return new ConstraintCondition(annotation); } - private static class ConstrainedFields { + private static final class ConstrainedFields { @NotNull private String single; @@ -102,7 +101,7 @@ private static class ConstrainedFields { @NotBlank @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) - @javax.validation.Constraint(validatedBy = {}) + @jakarta.validation.Constraint(validatedBy = {}) private @interface CompositeConstraint { String message() default "Must be null or not blank"; diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cookies/RequestCookiesSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cookies/RequestCookiesSnippetTests.java new file mode 100644 index 000000000..febac6e00 --- /dev/null +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cookies/RequestCookiesSnippetTests.java @@ -0,0 +1,179 @@ +/* + * Copyright 2014-2025 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.restdocs.cookies; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; + +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.springframework.restdocs.cookies.CookieDocumentation.cookieWithName; +import static org.springframework.restdocs.snippet.Attributes.attributes; +import static org.springframework.restdocs.snippet.Attributes.key; + +/** + * Tests for {@link RequestCookiesSnippet}. + * + * @author Clyde Stubbs + * @author Andy Wilkinson + */ +class RequestCookiesSnippetTests { + + @RenderedSnippetTest + void requestWithCookies(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new RequestCookiesSnippet( + Arrays.asList(cookieWithName("tz").description("one"), cookieWithName("logged_in").description("two"))) + .document(operationBuilder.request("http://localhost") + .cookie("tz", "Europe%2FLondon") + .cookie("logged_in", "true") + .build()); + assertThat(snippets.requestCookies()) + .isTable((table) -> table.withHeader("Name", "Description").row("`tz`", "one").row("`logged_in`", "two")); + } + + @RenderedSnippetTest + void ignoredRequestCookie(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new RequestCookiesSnippet( + Arrays.asList(cookieWithName("tz").ignored(), cookieWithName("logged_in").description("two"))) + .document(operationBuilder.request("http://localhost") + .cookie("tz", "Europe%2FLondon") + .cookie("logged_in", "true") + .build()); + assertThat(snippets.requestCookies()) + .isTable((table) -> table.withHeader("Name", "Description").row("`logged_in`", "two")); + } + + @RenderedSnippetTest + void allUndocumentedCookiesCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new RequestCookiesSnippet( + Arrays.asList(cookieWithName("tz").description("one"), cookieWithName("logged_in").description("two")), + true) + .document(operationBuilder.request("http://localhost") + .cookie("tz", "Europe%2FLondon") + .cookie("logged_in", "true") + .cookie("user_session", "abcd1234efgh5678") + .build()); + assertThat(snippets.requestCookies()) + .isTable((table) -> table.withHeader("Name", "Description").row("`tz`", "one").row("`logged_in`", "two")); + } + + @RenderedSnippetTest + void missingOptionalCookie(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new RequestCookiesSnippet(Arrays.asList(cookieWithName("tz").description("one").optional(), + cookieWithName("logged_in").description("two"))) + .document(operationBuilder.request("http://localhost").cookie("logged_in", "true").build()); + assertThat(snippets.requestCookies()) + .isTable((table) -> table.withHeader("Name", "Description").row("`tz`", "one").row("`logged_in`", "two")); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-cookies", template = "request-cookies-with-title") + void requestCookiesWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new RequestCookiesSnippet(Collections.singletonList(cookieWithName("tz").description("one")), + attributes(key("title").value("Custom title"))) + .document(operationBuilder.request("http://localhost").cookie("tz", "Europe%2FLondon").build()); + assertThat(snippets.requestCookies()).contains("Custom title"); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-cookies", template = "request-cookies-with-extra-column") + void requestCookiesWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new RequestCookiesSnippet( + Arrays.asList(cookieWithName("tz").description("one").attributes(key("foo").value("alpha")), + cookieWithName("logged_in").description("two").attributes(key("foo").value("bravo")))) + .document(operationBuilder.request("http://localhost") + .cookie("tz", "Europe%2FLondon") + .cookie("logged_in", "true") + .build()); + assertThat(snippets.requestCookies()).isTable((table) -> table.withHeader("Name", "Description", "Foo") + .row("tz", "one", "alpha") + .row("logged_in", "two", "bravo")); + } + + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new RequestCookiesSnippet( + Arrays.asList(cookieWithName("tz").description("one"), cookieWithName("logged_in").description("two"))) + .and(cookieWithName("user_session").description("three")) + .document(operationBuilder.request("http://localhost") + .cookie("tz", "Europe%2FLondon") + .cookie("logged_in", "true") + .cookie("user_session", "abcd1234efgh5678") + .build()); + assertThat(snippets.requestCookies()).isTable((table) -> table.withHeader("Name", "Description") + .row("`tz`", "one") + .row("`logged_in`", "two") + .row("`user_session`", "three")); + } + + @RenderedSnippetTest + void additionalDescriptorsWithRelaxedRequestCookies(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new RequestCookiesSnippet( + Arrays.asList(cookieWithName("tz").description("one"), cookieWithName("logged_in").description("two")), + true) + .and(cookieWithName("user_session").description("three")) + .document(operationBuilder.request("http://localhost") + .cookie("tz", "Europe%2FLondon") + .cookie("logged_in", "true") + .cookie("user_session", "abcd1234efgh5678") + .cookie("color_theme", "light") + .build()); + assertThat(snippets.requestCookies()).isTable((table) -> table.withHeader("Name", "Description") + .row("`tz`", "one") + .row("`logged_in`", "two") + .row("`user_session`", "three")); + } + + @RenderedSnippetTest + void tableCellContentIsEscapedWhenNecessary(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new RequestCookiesSnippet(Collections.singletonList(cookieWithName("Foo|Bar").description("one|two"))) + .document(operationBuilder.request("http://localhost").cookie("Foo|Bar", "baz").build()); + assertThat(snippets.requestCookies()) + .isTable((table) -> table.withHeader("Name", "Description").row("`Foo|Bar`", "one|two")); + } + + @SnippetTest + void missingRequestCookie(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestCookiesSnippet( + Collections.singletonList(CookieDocumentation.cookieWithName("JSESSIONID").description("one"))) + .document(operationBuilder.request("http://localhost").build())) + .withMessage("Cookies with the following names were not found in the request: [JSESSIONID]"); + } + + @SnippetTest + void undocumentedRequestCookie(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestCookiesSnippet(Collections.emptyList()).document( + operationBuilder.request("http://localhost").cookie("JSESSIONID", "1234abcd5678efgh").build())) + .withMessageEndingWith("Cookies with the following names were not documented: [JSESSIONID]"); + } + +} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cookies/ResponseCookiesSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cookies/ResponseCookiesSnippetTests.java new file mode 100644 index 000000000..2d7883e45 --- /dev/null +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cookies/ResponseCookiesSnippetTests.java @@ -0,0 +1,162 @@ +/* + * Copyright 2014-2025 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.restdocs.cookies; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; + +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.restdocs.cookies.CookieDocumentation.cookieWithName; +import static org.springframework.restdocs.snippet.Attributes.attributes; +import static org.springframework.restdocs.snippet.Attributes.key; + +/** + * Tests for {@link ResponseCookiesSnippet}. + * + * @author Clyde Stubbs + * @author Andy Wilkinson + */ +class ResponseCookiesSnippetTests { + + @RenderedSnippetTest + void responseWithCookies(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new ResponseCookiesSnippet(Arrays.asList(cookieWithName("has_recent_activity").description("one"), + cookieWithName("user_session").description("two"))) + .document(operationBuilder.response() + .cookie("has_recent_activity", "true") + .cookie("user_session", "1234abcd5678efgh") + .build()); + assertThat(snippets.responseCookies()).isTable((table) -> table.withHeader("Name", "Description") + .row("`has_recent_activity`", "one") + .row("`user_session`", "two")); + } + + @RenderedSnippetTest + void ignoredResponseCookie(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new ResponseCookiesSnippet(Arrays.asList(cookieWithName("has_recent_activity").ignored(), + cookieWithName("user_session").description("two"))) + .document(operationBuilder.response() + .cookie("has_recent_activity", "true") + .cookie("user_session", "1234abcd5678efgh") + .build()); + assertThat(snippets.responseCookies()) + .isTable((table) -> table.withHeader("Name", "Description").row("`user_session`", "two")); + } + + @RenderedSnippetTest + void allUndocumentedResponseCookiesCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseCookiesSnippet(Arrays.asList(cookieWithName("has_recent_activity").description("one"), + cookieWithName("user_session").description("two")), true) + .document(operationBuilder.response() + .cookie("has_recent_activity", "true") + .cookie("user_session", "1234abcd5678efgh") + .cookie("some_cookie", "value") + .build()); + assertThat(snippets.responseCookies()).isTable((table) -> table.withHeader("Name", "Description") + .row("`has_recent_activity`", "one") + .row("`user_session`", "two")); + } + + @RenderedSnippetTest + void missingOptionalResponseCookie(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseCookiesSnippet(Arrays.asList(cookieWithName("has_recent_activity").description("one").optional(), + cookieWithName("user_session").description("two"))) + .document(operationBuilder.response().cookie("user_session", "1234abcd5678efgh").build()); + assertThat(snippets.responseCookies()).isTable((table) -> table.withHeader("Name", "Description") + .row("`has_recent_activity`", "one") + .row("`user_session`", "two")); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "response-cookies", template = "response-cookies-with-title") + void responseCookiesWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseCookiesSnippet(Collections.singletonList(cookieWithName("has_recent_activity").description("one")), + attributes(key("title").value("Custom title"))) + .document(operationBuilder.response().cookie("has_recent_activity", "true").build()); + assertThat(snippets.responseCookies()).contains("Custom title"); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "response-cookies", template = "response-cookies-with-extra-column") + void responseCookiesWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseCookiesSnippet(Arrays.asList( + cookieWithName("has_recent_activity").description("one").attributes(key("foo").value("alpha")), + cookieWithName("user_session").description("two").attributes(key("foo").value("bravo")), + cookieWithName("color_theme").description("three").attributes(key("foo").value("charlie")))) + .document(operationBuilder.response() + .cookie("has_recent_activity", "true") + .cookie("user_session", "1234abcd5678efgh") + .cookie("color_theme", "high_contrast") + .build()); + assertThat(snippets.responseCookies()).isTable((table) -> table.withHeader("Name", "Description", "Foo") + .row("has_recent_activity", "one", "alpha") + .row("user_session", "two", "bravo") + .row("color_theme", "three", "charlie")); + } + + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + CookieDocumentation + .responseCookies(cookieWithName("has_recent_activity").description("one"), + cookieWithName("user_session").description("two")) + .and(cookieWithName("color_theme").description("three")) + .document(operationBuilder.response() + .cookie("has_recent_activity", "true") + .cookie("user_session", "1234abcd5678efgh") + .cookie("color_theme", "light") + .build()); + assertThat(snippets.responseCookies()).isTable((table) -> table.withHeader("Name", "Description") + .row("`has_recent_activity`", "one") + .row("`user_session`", "two") + .row("`color_theme`", "three")); + } + + @RenderedSnippetTest + void additionalDescriptorsWithRelaxedResponseCookies(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + CookieDocumentation.relaxedResponseCookies(cookieWithName("has_recent_activity").description("one")) + .and(cookieWithName("color_theme").description("two")) + .document(operationBuilder.response() + .cookie("has_recent_activity", "true") + .cookie("user_session", "1234abcd5678efgh") + .cookie("color_theme", "light") + .build()); + assertThat(snippets.responseCookies()).isTable((table) -> table.withHeader("Name", "Description") + .row("`has_recent_activity`", "one") + .row("`color_theme`", "two")); + } + + @RenderedSnippetTest + void tableCellContentIsEscapedWhenNecessary(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseCookiesSnippet(Collections.singletonList(cookieWithName("Foo|Bar").description("one|two"))) + .document(operationBuilder.response().cookie("Foo|Bar", "baz").build()); + assertThat(snippets.responseCookies()) + .isTable((table) -> table.withHeader("Name", "Description").row("`Foo|Bar`", "one|two")); + } + +} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java deleted file mode 100644 index a980632c2..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.headers; - -import java.util.Arrays; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; - -/** - * Tests for failures when rendering {@link RequestHeadersSnippet} due to missing or - * undocumented headers. - * - * @author Andy Wilkinson - */ -public class RequestHeadersSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void missingRequestHeader() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Headers with the following names were not found in the request: [Accept]"); - } - - @Test - public void undocumentedRequestHeaderAndMissingRequestHeader() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) - .document(this.operationBuilder.request("http://localhost").header("X-Test", "test").build())) - .withMessageEndingWith("Headers with the following names were not found in the request: [Accept]"); - - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java index edb90cb58..51f16ccc3 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -19,18 +19,15 @@ import java.io.IOException; import java.util.Arrays; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; @@ -41,19 +38,15 @@ * @author Andreas Evers * @author Andy Wilkinson */ -public class RequestHeadersSnippetTests extends AbstractSnippetTests { - - public RequestHeadersSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +class RequestHeadersSnippetTests { - @Test - public void requestWithHeaders() throws IOException { + @RenderedSnippetTest + void requestWithHeaders(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"), headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"), headerWithName("Accept-Language").description("four"), headerWithName("Cache-Control").description("five"), headerWithName("Connection").description("six"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .header("X-Test", "test") .header("Accept", "*/*") .header("Accept-Encoding", "gzip, deflate") @@ -61,79 +54,69 @@ public void requestWithHeaders() throws IOException { .header("Cache-Control", "max-age=0") .header("Connection", "keep-alive") .build()); - assertThat(this.generatedSnippets.requestHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") - .row("`Accept`", "two") - .row("`Accept-Encoding`", "three") - .row("`Accept-Language`", "four") - .row("`Cache-Control`", "five") - .row("`Connection`", "six")); + assertThat(snippets.requestHeaders()).isTable((table) -> table.withHeader("Name", "Description") + .row("`X-Test`", "one") + .row("`Accept`", "two") + .row("`Accept-Encoding`", "three") + .row("`Accept-Language`", "four") + .row("`Cache-Control`", "five") + .row("`Connection`", "six")); } - @Test - public void caseInsensitiveRequestHeaders() throws IOException { + @RenderedSnippetTest + void caseInsensitiveRequestHeaders(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.request("/").header("X-test", "test").build()); - assertThat(this.generatedSnippets.requestHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + .document(operationBuilder.request("/").header("X-test", "test").build()); + assertThat(snippets.requestHeaders()) + .isTable((table) -> table.withHeader("Name", "Description").row("`X-Test`", "one")); } - @Test - public void undocumentedRequestHeader() throws IOException { - new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .header("X-Test", "test") - .header("Accept", "*/*") - .build()); - assertThat(this.generatedSnippets.requestHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + @RenderedSnippetTest + void undocumentedRequestHeader(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))).document( + operationBuilder.request("http://localhost").header("X-Test", "test").header("Accept", "*/*").build()); + assertThat(snippets.requestHeaders()) + .isTable((table) -> table.withHeader("Name", "Description").row("`X-Test`", "one")); } - @Test - public void requestHeadersWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-headers")) - .willReturn(snippetResource("request-headers-with-title")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-headers", template = "request-headers-with-title") + void requestHeadersWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .header("X-Test", "test") - .build()); - assertThat(this.generatedSnippets.requestHeaders()).contains("Custom title"); + .document(operationBuilder.request("http://localhost").header("X-Test", "test").build()); + assertThat(snippets.requestHeaders()).contains("Custom title"); } - @Test - public void requestHeadersWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-headers")) - .willReturn(snippetResource("request-headers-with-extra-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-headers", template = "request-headers-with-extra-column") + void requestHeadersWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")), headerWithName("Accept-Encoding").description("two").attributes(key("foo").value("bravo")), headerWithName("Accept").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") + .document(operationBuilder.request("http://localhost") .header("X-Test", "test") .header("Accept-Encoding", "gzip, deflate") .header("Accept", "*/*") .build()); - assertThat(this.generatedSnippets.requestHeaders()).is(// - tableWithHeader("Name", "Description", "Foo").row("X-Test", "one", "alpha") - .row("Accept-Encoding", "two", "bravo") - .row("Accept", "three", "charlie")); + assertThat(snippets.requestHeaders()).isTable((table) -> table.withHeader("Name", "Description", "Foo") + .row("X-Test", "one", "alpha") + .row("Accept-Encoding", "two", "bravo") + .row("Accept", "three", "charlie")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { HeaderDocumentation .requestHeaders(headerWithName("X-Test").description("one"), headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"), headerWithName("Accept-Language").description("four")) .and(headerWithName("Cache-Control").description("five"), headerWithName("Connection").description("six")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .header("X-Test", "test") .header("Accept", "*/*") .header("Accept-Encoding", "gzip, deflate") @@ -141,28 +124,39 @@ public void additionalDescriptors() throws IOException { .header("Cache-Control", "max-age=0") .header("Connection", "keep-alive") .build()); - assertThat(this.generatedSnippets.requestHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") - .row("`Accept`", "two") - .row("`Accept-Encoding`", "three") - .row("`Accept-Language`", "four") - .row("`Cache-Control`", "five") - .row("`Connection`", "six")); + assertThat(snippets.requestHeaders()).isTable((table) -> table.withHeader("Name", "Description") + .row("`X-Test`", "one") + .row("`Accept`", "two") + .row("`Accept-Encoding`", "three") + .row("`Accept-Language`", "four") + .row("`Cache-Control`", "five") + .row("`Connection`", "six")); } - @Test - public void tableCellContentIsEscapedWhenNecessary() throws IOException { + @RenderedSnippetTest + void tableCellContentIsEscapedWhenNecessary(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) - .document(this.operationBuilder.request("http://localhost").header("Foo|Bar", "baz").build()); - assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .document(operationBuilder.request("http://localhost").header("Foo|Bar", "baz").build()); + assertThat(snippets.requestHeaders()) + .isTable((table) -> table.withHeader("Name", "Description").row("`Foo|Bar`", "one|two")); } - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); + @SnippetTest + void missingRequestHeader(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) + .document(operationBuilder.request("http://localhost").build())) + .withMessage("Headers with the following names were not found in the request: [Accept]"); + } + + @SnippetTest + void undocumentedRequestHeaderAndMissingRequestHeader(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one"))) + .document(operationBuilder.request("http://localhost").header("X-Test", "test").build())) + .withMessageEndingWith("Headers with the following names were not found in the request: [Accept]"); + } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java deleted file mode 100644 index 6efbe91d5..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.headers; - -import java.util.Arrays; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; - -/** - * Tests for failures when rendering {@link ResponseHeadersSnippet} due to missing or - * undocumented headers. - * - * @author Andy Wilkinson - */ -public class ResponseHeadersSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void missingResponseHeader() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy( - () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) - .document(this.operationBuilder.response().build())) - .withMessage("Headers with the following names were not found" + " in the response: [Content-Type]"); - } - - @Test - public void undocumentedResponseHeaderAndMissingResponseHeader() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy( - () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) - .document(this.operationBuilder.response().header("X-Test", "test").build())) - .withMessageEndingWith("Headers with the following names were not found in the response: [Content-Type]"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java index 4427d6c34..484ee4cbc 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -19,18 +19,15 @@ import java.io.IOException; import java.util.Arrays; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; @@ -41,119 +38,120 @@ * @author Andreas Evers * @author Andy Wilkinson */ -public class ResponseHeadersSnippetTests extends AbstractSnippetTests { - - public ResponseHeadersSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +class ResponseHeadersSnippetTests { - @Test - public void responseWithHeaders() throws IOException { + @RenderedSnippetTest + void responseWithHeaders(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"), headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three"), headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six"))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .header("X-Test", "test") .header("Content-Type", "application/json") .header("Etag", "lskjadldj3ii32l2ij23") .header("Cache-Control", "max-age=0") .header("Vary", "User-Agent") .build()); - assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") - .row("`Content-Type`", "two") - .row("`Etag`", "three") - .row("`Cache-Control`", "five") - .row("`Vary`", "six")); + assertThat(snippets.responseHeaders()).isTable((table) -> table.withHeader("Name", "Description") + .row("`X-Test`", "one") + .row("`Content-Type`", "two") + .row("`Etag`", "three") + .row("`Cache-Control`", "five") + .row("`Vary`", "six")); } - @Test - public void caseInsensitiveResponseHeaders() throws IOException { + @RenderedSnippetTest + void caseInsensitiveResponseHeaders(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.response().header("X-test", "test").build()); - assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + .document(operationBuilder.response().header("X-test", "test").build()); + assertThat(snippets.responseHeaders()) + .isTable((table) -> table.withHeader("Name", "Description").row("`X-Test`", "one")); } - @Test - public void undocumentedResponseHeader() throws IOException { + @RenderedSnippetTest + void undocumentedResponseHeader(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))) - .document(this.operationBuilder.response().header("X-Test", "test").header("Content-Type", "*/*").build()); - assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); + .document(operationBuilder.response().header("X-Test", "test").header("Content-Type", "*/*").build()); + assertThat(snippets.responseHeaders()) + .isTable((table) -> table.withHeader("Name", "Description").row("`X-Test`", "one")); } - @Test - public void responseHeadersWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-headers")) - .willReturn(snippetResource("response-headers-with-title")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "response-headers", template = "response-headers-with-title") + void responseHeadersWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response() - .header("X-Test", "test") - .build()); - assertThat(this.generatedSnippets.responseHeaders()).contains("Custom title"); + .document(operationBuilder.response().header("X-Test", "test").build()); + assertThat(snippets.responseHeaders()).contains("Custom title"); } - @Test - public void responseHeadersWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-headers")) - .willReturn(snippetResource("response-headers-with-extra-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "response-headers", template = "response-headers-with-extra-column") + void responseHeadersWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")), headerWithName("Content-Type").description("two").attributes(key("foo").value("bravo")), headerWithName("Etag").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response() + .document(operationBuilder.response() .header("X-Test", "test") .header("Content-Type", "application/json") .header("Etag", "lskjadldj3ii32l2ij23") .build()); - assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description", "Foo").row("X-Test", "one", "alpha") - .row("Content-Type", "two", "bravo") - .row("Etag", "three", "charlie")); + assertThat(snippets.responseHeaders()).isTable((table) -> table.withHeader("Name", "Description", "Foo") + .row("X-Test", "one", "alpha") + .row("Content-Type", "two", "bravo") + .row("Etag", "three", "charlie")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { HeaderDocumentation .responseHeaders(headerWithName("X-Test").description("one"), headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three")) .and(headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six")) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .header("X-Test", "test") .header("Content-Type", "application/json") .header("Etag", "lskjadldj3ii32l2ij23") .header("Cache-Control", "max-age=0") .header("Vary", "User-Agent") .build()); - assertThat(this.generatedSnippets.responseHeaders()) - .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") - .row("`Content-Type`", "two") - .row("`Etag`", "three") - .row("`Cache-Control`", "five") - .row("`Vary`", "six")); + assertThat(snippets.responseHeaders()).isTable((table) -> table.withHeader("Name", "Description") + .row("`X-Test`", "one") + .row("`Content-Type`", "two") + .row("`Etag`", "three") + .row("`Cache-Control`", "five") + .row("`Vary`", "six")); } - @Test - public void tableCellContentIsEscapedWhenNecessary() throws IOException { + @RenderedSnippetTest + void tableCellContentIsEscapedWhenNecessary(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) - .document(this.operationBuilder.response().header("Foo|Bar", "baz").build()); - assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .document(operationBuilder.response().header("Foo|Bar", "baz").build()); + assertThat(snippets.responseHeaders()) + .isTable((table) -> table.withHeader("Name", "Description").row("`Foo|Bar`", "one|two")); + } + + @SnippetTest + void missingResponseHeader(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy( + () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) + .document(operationBuilder.response().build())) + .withMessage("Headers with the following names were not found" + " in the response: [Content-Type]"); } - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); + @SnippetTest + void undocumentedResponseHeaderAndMissingResponseHeader(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy( + () -> new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one"))) + .document(operationBuilder.response().header("X-Test", "test").build())) + .withMessageEndingWith("Headers with the following names were not found in the response: [Content-Type]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java index 38a727ac3..a37e3fd3c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,20 +18,14 @@ import java.io.IOException; -import org.junit.Test; - import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; @@ -41,336 +35,177 @@ * @author Andy Wilkinson * @author Jonathan Pearlin */ -public class HttpRequestSnippetTests extends AbstractSnippetTests { +class HttpRequestSnippetTests { private static final String BOUNDARY = "6o2knFse3p53ty9dmcQvWAIx1zInP11uCfbm"; - public HttpRequestSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } - - @Test - public void getRequest() throws IOException { + @RenderedSnippetTest + void getRequest(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost")); + .document(operationBuilder.request("http://localhost/foo").header("Alpha", "a").build()); + assertThat(snippets.httpRequest()) + .isHttpRequest((request) -> request.get("/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost")); } - @Test - public void getRequestWithParameters() throws IOException { - new HttpRequestSnippet().document( - this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").param("b", "bravo").build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?b=bravo").header("Alpha", "a") - .header(HttpHeaders.HOST, "localhost")); + @RenderedSnippetTest + void getRequestWithQueryParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpRequestSnippet() + .document(operationBuilder.request("http://localhost/foo?b=bravo").header("Alpha", "a").build()); + assertThat(snippets.httpRequest()).isHttpRequest( + (request) -> request.get("/foo?b=bravo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost")); } - @Test - public void getRequestWithPort() throws IOException { + @RenderedSnippetTest + void getRequestWithPort(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost:8080/foo").header("Alpha", "a").build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost:8080")); + .document(operationBuilder.request("http://localhost:8080/foo").header("Alpha", "a").build()); + assertThat(snippets.httpRequest()).isHttpRequest( + (request) -> request.get("/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost:8080")); } - @Test - public void getRequestWithCookies() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + @RenderedSnippetTest + void getRequestWithCookies(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/foo") .cookie("name1", "value1") .cookie("name2", "value2") .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "localhost") - .header(HttpHeaders.COOKIE, "name1=value1") - .header(HttpHeaders.COOKIE, "name2=value2")); - } - - @Test - public void getRequestWithQueryString() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar=baz").build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?bar=baz").header(HttpHeaders.HOST, "localhost")); - } - - @Test - public void getRequestWithQueryStringWithNoValue() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar").build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST, "localhost")); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.get("/foo") + .header(HttpHeaders.HOST, "localhost") + .header(HttpHeaders.COOKIE, "name1=value1; name2=value2")); } - @Test - public void getWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); + @RenderedSnippetTest + void getRequestWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/foo?bar=baz").build()); + assertThat(snippets.httpRequest()) + .isHttpRequest((request) -> request.get("/foo?bar=baz").header(HttpHeaders.HOST, "localhost")); } - @Test - public void getWithTotallyOverlappingQueryStringAndParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); + @RenderedSnippetTest + void getRequestWithQueryStringWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/foo?bar").build()); + assertThat(snippets.httpRequest()) + .isHttpRequest((request) -> request.get("/foo?bar").header(HttpHeaders.HOST, "localhost")); } - @Test - public void postRequestWithContent() throws IOException { + @RenderedSnippetTest + void postRequestWithContent(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { String content = "Hello, world"; new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo").method("POST").content(content).build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") - .content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - } - - @Test - public void postRequestWithContentAndParameters() throws IOException { - String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .method("POST") - .param("a", "alpha") - .content(content) - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - - } - - @Test - public void postRequestWithContentAndDisjointQueryStringAndParameters() throws IOException { - String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo") - .method("POST") - .param("a", "alpha") - .content(content) - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - } - - @Test - public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters() throws IOException { - String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo") - .method("POST") - .param("a", "alpha") - .param("b", "bravo") + .document(operationBuilder.request("http://localhost/foo").method("POST").content(content).build()); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.post("/foo") + .header(HttpHeaders.HOST, "localhost") .content(content) - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } - @Test - public void postRequestWithContentAndTotallyOverlappingQueryStringAndParameters() throws IOException { + @RenderedSnippetTest + void postRequestWithContentAndQueryParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { String content = "Hello, world"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo&a=alpha") - .method("POST") - .param("a", "alpha") - .param("b", "bravo") - .content(content) - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost") - .content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - } - - @Test - public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { - String content = "a=alpha&b=bravo"; - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .method("POST") - .content("a=alpha&b=bravo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) + new HttpRequestSnippet() + .document(operationBuilder.request("http://localhost/foo?a=alpha").method("POST").content(content).build()); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.post("/foo?a=alpha") .header(HttpHeaders.HOST, "localhost") .content(content) .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + } - @Test - public void postRequestWithCharset() throws IOException { + @RenderedSnippetTest + void postRequestWithCharset(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/foo") .method("POST") .header("Content-Type", "text/plain;charset=UTF-8") .content(contentBytes) .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo").header("Content-Type", "text/plain;charset=UTF-8") - .header(HttpHeaders.HOST, "localhost") - .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length) - .content(japaneseContent)); - } - - @Test - public void postRequestWithParameter() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .method("POST") - .param("b&r", "baz") - .param("a", "alpha") - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded") - .content("b%26r=baz&a=alpha")); - } - - @Test - public void postRequestWithParameterWithNoValue() throws IOException { - new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo").method("POST").param("bar").build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded") - .content("bar=")); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.post("/foo") + .header("Content-Type", "text/plain;charset=UTF-8") + .header(HttpHeaders.HOST, "localhost") + .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length) + .content(japaneseContent)); } - @Test - public void putRequestWithContent() throws IOException { + @RenderedSnippetTest + void putRequestWithContent(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { String content = "Hello, world"; new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo").method("PUT").content(content).build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost") - .content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - } - - @Test - public void putRequestWithParameter() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .method("PUT") - .param("b&r", "baz") - .param("a", "alpha") - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded") - .content("b%26r=baz&a=alpha")); - } - - @Test - public void putRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") - .method("PUT") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.PUT, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost")); + .document(operationBuilder.request("http://localhost/foo").method("PUT").content(content).build()); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.put("/foo") + .header(HttpHeaders.HOST, "localhost") + .content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } - @Test - public void multipartPost() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + @RenderedSnippetTest + void multipartPost(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/upload") .method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", "<< data >>".getBytes()) .build()); String expectedContent = createPart( String.format("Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>")); - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost") - .content(expectedContent)); - } - - @Test - public void multipartPostWithFilename() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") - .method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .part("image", "<< data >>".getBytes()) - .submittedFileName("image.png") - .build()); - String expectedContent = createPart(String - .format("Content-Disposition: " + "form-data; " + "name=image; filename=image.png%n%n<< data >>")); - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.post("/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost") .content(expectedContent)); } - @Test - public void multipartPostWithParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") - .method("POST") + @RenderedSnippetTest + void multipartPut(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/upload") + .method("PUT") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .param("a", "apple", "avocado") - .param("b", "banana") .part("image", "<< data >>".getBytes()) .build()); - String param1Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%napple"), false); - String param2Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%navocado"), false); - String param3Part = createPart(String.format("Content-Disposition: form-data; " + "name=b%n%nbanana"), false); - String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); - String expectedContent = param1Part + param2Part + param3Part + filePart; - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + String expectedContent = createPart( + String.format("Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>")); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.put("/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost") .content(expectedContent)); } - @Test - public void multipartPostWithOverlappingPartsAndParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") - .method("POST") + @RenderedSnippetTest + void multipartPatch(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/upload") + .method("PATCH") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .param("a", "apple") - .part("a", "apple".getBytes()) - .and() .part("image", "<< data >>".getBytes()) .build()); - String paramPart = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%napple"), false); - String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); - String expectedContent = paramPart + filePart; - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + String expectedContent = createPart( + String.format("Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>")); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.patch("/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost") .content(expectedContent)); } - @Test - public void multipartPostWithParameterWithNoValue() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + @RenderedSnippetTest + void multipartPostWithFilename(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/upload") .method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .param("a") .part("image", "<< data >>".getBytes()) + .submittedFileName("image.png") .build()); - String paramPart = createPart(String.format("Content-Disposition: form-data; " + "name=a%n"), false); - String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); - String expectedContent = paramPart + filePart; - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + String expectedContent = createPart(String + .format("Content-Disposition: " + "form-data; " + "name=image; filename=image.png%n%n<< data >>")); + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.post("/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost") .content(expectedContent)); } - @Test - public void multipartPostWithContentType() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload") + @RenderedSnippetTest + void multipartPostWithContentType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpRequestSnippet().document(operationBuilder.request("http://localhost/upload") .method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", "<< data >>".getBytes()) @@ -378,49 +213,35 @@ public void multipartPostWithContentType() throws IOException { .build()); String expectedContent = createPart(String .format("Content-Disposition: form-data; name=image%nContent-Type: " + "image/png%n%n<< data >>")); - assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload") + assertThat(snippets.httpRequest()).isHttpRequest((request) -> request.post("/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost") .content(expectedContent)); } - @Test - public void getRequestWithCustomHost() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .header(HttpHeaders.HOST, "api.example.com") - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "api.example.com")); - } - - @Test - public void requestWithCustomSnippetAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("http-request")).willReturn(snippetResource("http-request-with-title")); - new HttpRequestSnippet(attributes(key("title").value("Title for the request"))).document( - this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost/foo") - .build()); - assertThat(this.generatedSnippets.httpRequest()).contains("Title for the request"); + @RenderedSnippetTest + void getRequestWithCustomHost(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpRequestSnippet().document( + operationBuilder.request("http://localhost/foo").header(HttpHeaders.HOST, "api.example.com").build()); + assertThat(snippets.httpRequest()) + .isHttpRequest((request) -> request.get("/foo").header(HttpHeaders.HOST, "api.example.com")); } - @Test - public void deleteWithParameters() throws IOException { - new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo") - .method("DELETE") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.DELETE, "/foo?a=alpha&b=bravo").header("Host", "localhost")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "http-request", template = "http-request-with-title") + void requestWithCustomSnippetAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpRequestSnippet(attributes(key("title").value("Title for the request"))) + .document(operationBuilder.request("http://localhost/foo").build()); + assertThat(snippets.httpRequest()).contains("Title for the request"); } - @Test - public void deleteWithQueryString() throws IOException { + @RenderedSnippetTest + void deleteWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new HttpRequestSnippet() - .document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); - assertThat(this.generatedSnippets.httpRequest()) - .is(httpRequest(RequestMethod.DELETE, "/foo?a=alpha&b=bravo").header("Host", "localhost")); + .document(operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("DELETE").build()); + assertThat(snippets.httpRequest()) + .isHttpRequest((request) -> request.delete("/foo?a=alpha&b=bravo").header("Host", "localhost")); } private String createPart(String content) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java index e18a02915..0ce5785ea 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,20 +18,16 @@ import java.io.IOException; -import org.junit.Test; - import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.MediaType; -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; @@ -41,72 +37,66 @@ * @author Andy Wilkinson * @author Jonathan Pearlin */ -public class HttpResponseSnippetTests extends AbstractSnippetTests { - - public HttpResponseSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +class HttpResponseSnippetTests { - @Test - public void basicResponse() throws IOException { - new HttpResponseSnippet().document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK)); + @RenderedSnippetTest + void basicResponse(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpResponseSnippet().document(operationBuilder.build()); + assertThat(snippets.httpResponse()).isHttpResponse((response) -> response.ok()); } - @Test - public void nonOkResponse() throws IOException { - new HttpResponseSnippet() - .document(this.operationBuilder.response().status(HttpStatus.BAD_REQUEST.value()).build()); - assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.BAD_REQUEST)); + @RenderedSnippetTest + void nonOkResponse(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpResponseSnippet().document(operationBuilder.response().status(HttpStatus.BAD_REQUEST).build()); + assertThat(snippets.httpResponse()).isHttpResponse((response) -> response.badRequest()); } - @Test - public void responseWithHeaders() throws IOException { - new HttpResponseSnippet().document(this.operationBuilder.response() + @RenderedSnippetTest + void responseWithHeaders(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpResponseSnippet().document(operationBuilder.response() .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha") .build()); - assertThat(this.generatedSnippets.httpResponse()) - .is(httpResponse(HttpStatus.OK).header("Content-Type", "application/json").header("a", "alpha")); + assertThat(snippets.httpResponse()).isHttpResponse( + (response) -> response.ok().header("Content-Type", "application/json").header("a", "alpha")); } - @Test - public void responseWithContent() throws IOException { + @RenderedSnippetTest + void responseWithContent(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { String content = "content"; - new HttpResponseSnippet().document(this.operationBuilder.response().content(content).build()); - assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK).content(content) + new HttpResponseSnippet().document(operationBuilder.response().content(content).build()); + assertThat(snippets.httpResponse()).isHttpResponse((response) -> response.ok() + .content(content) .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } - @Test - public void responseWithCharset() throws IOException { + @RenderedSnippetTest + void responseWithCharset(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); - new HttpResponseSnippet().document(this.operationBuilder.response() + new HttpResponseSnippet().document(operationBuilder.response() .header("Content-Type", "text/plain;charset=UTF-8") .content(contentBytes) .build()); - assertThat(this.generatedSnippets.httpResponse()) - .is(httpResponse(HttpStatus.OK).header("Content-Type", "text/plain;charset=UTF-8") - .content(japaneseContent) - .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); + assertThat(snippets.httpResponse()).isHttpResponse((response) -> response.ok() + .header("Content-Type", "text/plain;charset=UTF-8") + .content(japaneseContent) + .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); } - @Test - public void responseWithCustomSnippetAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("http-response")) - .willReturn(snippetResource("http-response-with-title")); - new HttpResponseSnippet(attributes(key("title").value("Title for the response"))).document( - this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); - assertThat(this.generatedSnippets.httpResponse()).contains("Title for the response"); + @RenderedSnippetTest + @SnippetTemplate(snippet = "http-response", template = "http-response-with-title") + void responseWithCustomSnippetAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new HttpResponseSnippet(attributes(key("title").value("Title for the response"))) + .document(operationBuilder.build()); + assertThat(snippets.httpResponse()).contains("Title for the response"); } - @Test - public void responseWithCustomStatus() throws IOException { - new HttpResponseSnippet().document(this.operationBuilder.response().status(215).build()); - assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(215)); + @RenderedSnippetTest + void responseWithCustomStatus(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new HttpResponseSnippet().document(operationBuilder.response().status(HttpStatusCode.valueOf(215)).build()); + assertThat(snippets.httpResponse()).isHttpResponse(((response) -> response.status(215))); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java index daad791ec..eb5875f8b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/ContentTypeLinkExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,11 +18,10 @@ import java.io.IOException; import java.util.HashMap; +import java.util.List; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -30,6 +29,8 @@ import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -38,42 +39,58 @@ * * @author Andy Wilkinson */ -public class ContentTypeLinkExtractorTests { +class ContentTypeLinkExtractorTests { private final OperationResponseFactory responseFactory = new OperationResponseFactory(); - @Rule - public ExpectedException thrown = ExpectedException.none(); + private final String halBody = "{ \"_links\" : { \"someRel\" : { \"href\" : \"someHref\" }} }"; @Test - public void extractionFailsWithNullContentType() throws IOException { - this.thrown.expect(IllegalStateException.class); - new ContentTypeLinkExtractor() - .extractLinks(this.responseFactory.create(HttpStatus.OK.value(), new HttpHeaders(), null)); + void extractionFailsWithNullContentType() { + assertThatIllegalStateException().isThrownBy(() -> new ContentTypeLinkExtractor() + .extractLinks(this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), null))); } @Test - public void extractorCalledWithMatchingContextType() throws IOException { + void extractorCalledWithMatchingContextType() throws IOException { Map extractors = new HashMap<>(); LinkExtractor extractor = mock(LinkExtractor.class); extractors.put(MediaType.APPLICATION_JSON, extractor); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); - OperationResponse response = this.responseFactory.create(HttpStatus.OK.value(), httpHeaders, null); + OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null); new ContentTypeLinkExtractor(extractors).extractLinks(response); verify(extractor).extractLinks(response); } @Test - public void extractorCalledWithCompatibleContextType() throws IOException { + void extractorCalledWithCompatibleContextType() throws IOException { Map extractors = new HashMap<>(); LinkExtractor extractor = mock(LinkExtractor.class); extractors.put(MediaType.APPLICATION_JSON, extractor); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.parseMediaType("application/json;foo=bar")); - OperationResponse response = this.responseFactory.create(HttpStatus.OK.value(), httpHeaders, null); + OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null); new ContentTypeLinkExtractor(extractors).extractLinks(response); verify(extractor).extractLinks(response); } + @Test + void extractsLinksFromVndHalMediaType() throws IOException { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.parseMediaType("application/vnd.hal+json")); + OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, this.halBody.getBytes()); + Map> links = new ContentTypeLinkExtractor().extractLinks(response); + assertThat(links).containsKey("someRel"); + } + + @Test + void extractsLinksFromHalFormsMediaType() throws IOException { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.parseMediaType("application/prs.hal-forms+json")); + OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, this.halBody.getBytes()); + Map> links = new ContentTypeLinkExtractor().extractLinks(response); + assertThat(links).containsKey("someRel"); + } + } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java index 8e8ce82fc..5346d512c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -24,10 +24,9 @@ import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.http.HttpStatus; import org.springframework.restdocs.operation.OperationResponse; @@ -39,13 +38,13 @@ import static org.assertj.core.api.Assertions.assertThat; /** - * Parameterized tests for {@link HalLinkExtractor} and {@link AtomLinkExtractor} with - * various payloads. + * Tests for {@link HalLinkExtractor} and {@link AtomLinkExtractor} with various payloads. * * @author Andy Wilkinson */ -@RunWith(Parameterized.class) -public class LinkExtractorsPayloadTests { +@ParameterizedClass(name = "{1}") +@MethodSource("parameters") +class LinkExtractorsPayloadTests { private final OperationResponseFactory responseFactory = new OperationResponseFactory(); @@ -53,25 +52,24 @@ public class LinkExtractorsPayloadTests { private final String linkType; - @Parameters(name = "{1}") - public static Collection data() { + static Collection parameters() { return Arrays.asList(new Object[] { new HalLinkExtractor(), "hal" }, new Object[] { new AtomLinkExtractor(), "atom" }); } - public LinkExtractorsPayloadTests(LinkExtractor linkExtractor, String linkType) { + LinkExtractorsPayloadTests(LinkExtractor linkExtractor, String linkType) { this.linkExtractor = linkExtractor; this.linkType = linkType; } @Test - public void singleLink() throws IOException { + void singleLink() throws IOException { Map> links = this.linkExtractor.extractLinks(createResponse("single-link")); assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha")), links); } @Test - public void multipleLinksWithDifferentRels() throws IOException { + void multipleLinksWithDifferentRels() throws IOException { Map> links = this.linkExtractor .extractLinks(createResponse("multiple-links-different-rels")); assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha"), @@ -79,20 +77,20 @@ public void multipleLinksWithDifferentRels() throws IOException { } @Test - public void multipleLinksWithSameRels() throws IOException { + void multipleLinksWithSameRels() throws IOException { Map> links = this.linkExtractor.extractLinks(createResponse("multiple-links-same-rels")); assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com/one", "Alpha one"), new Link("alpha", "https://alpha.example.com/two")), links); } @Test - public void noLinks() throws IOException { + void noLinks() throws IOException { Map> links = this.linkExtractor.extractLinks(createResponse("no-links")); assertLinks(Collections.emptyList(), links); } @Test - public void linksInTheWrongFormat() throws IOException { + void linksInTheWrongFormat() throws IOException { Map> links = this.linkExtractor.extractLinks(createResponse("wrong-format")); assertLinks(Collections.emptyList(), links); } @@ -106,7 +104,7 @@ private void assertLinks(List expectedLinks, Map> actua } private OperationResponse createResponse(String contentName) throws IOException { - return this.responseFactory.create(HttpStatus.OK.value(), null, + return this.responseFactory.create(HttpStatus.OK, null, FileCopyUtils.copyToByteArray(getPayloadFile(contentName))); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java deleted file mode 100644 index d62a1d80a..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.hypermedia; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -/** - * Tests for failures when rendering {@link LinksSnippet} due to missing or undocumented - * links. - * - * @author Andy Wilkinson - */ -public class LinksSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void undocumentedLink() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), - Collections.emptyList()) - .document(this.operationBuilder.build())) - .withMessage("Links with the following relations were not documented: [foo]"); - } - - @Test - public void missingLink() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor(), - Arrays.asList(new LinkDescriptor("foo").description("bar"))) - .document(this.operationBuilder.build())) - .withMessage("Links with the following relations were not found in the response: [foo]"); - } - - @Test - public void undocumentedLinkAndMissingLink() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha")), - Arrays.asList(new LinkDescriptor("foo").description("bar"))) - .document(this.operationBuilder.build())) - .withMessage("Links with the following relations were not documented: [a]. Links with the following" - + " relations were not found in the response: [foo]"); - } - - @Test - public void linkWithNoDescription() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), - Arrays.asList(new LinkDescriptor("foo"))) - .document(this.operationBuilder.build())) - .withMessage("No description was provided for the link with rel 'foo' and no title was available" - + " from the link in the payload"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java index b71ab843e..7782ce42f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,19 +18,17 @@ import java.io.IOException; import java.util.Arrays; +import java.util.Collections; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; @@ -39,115 +37,145 @@ * * @author Andy Wilkinson */ -public class LinksSnippetTests extends AbstractSnippetTests { - - public LinksSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +class LinksSnippetTests { - @Test - public void ignoredLink() throws IOException { + @RenderedSnippetTest + void ignoredLink(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").ignored(), new LinkDescriptor("b").description("Link b"))) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`b`", "Link b")); } - @Test - public void allUndocumentedLinksCanBeIgnored() throws IOException { + @RenderedSnippetTest + void allUndocumentedLinksCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("b").description("Link b")), true) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`b`", "Link b")); } - @Test - public void presentOptionalLink() throws IOException { + @RenderedSnippetTest + void presentOptionalLink(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "blah")), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`foo`", "bar")); } - @Test - public void missingOptionalLink() throws IOException { + @RenderedSnippetTest + void missingOptionalLink(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`foo`", "bar")); } - @Test - public void documentedLinks() throws IOException { + @RenderedSnippetTest + void documentedLinks(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b").description("two"))) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); } - @Test - public void linkDescriptionFromTitleInPayload() throws IOException { + @RenderedSnippetTest + void linkDescriptionFromTitleInPayload(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha", "Link a"), new Link("b", "bravo", "Link b")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b"))) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "Link b")); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`a`", "one").row("`b`", "Link b")); } - @Test - public void linksWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("links")).willReturn(snippetResource("links-with-title")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "links", template = "links-with-title") + void linksWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b").description("two")), attributes(key("title").value("Title for the links"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); - assertThat(this.generatedSnippets.links()).contains("Title for the links"); + .document(operationBuilder.build()); + assertThat(snippets.links()).contains("Title for the links"); } - @Test - public void linksWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("links")).willReturn(snippetResource("links-with-extra-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "links", template = "links-with-extra-column") + void linksWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").description("one").attributes(key("foo").value("alpha")), new LinkDescriptor("b").description("two").attributes(key("foo").value("bravo")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); + .document(operationBuilder.build()); + assertThat(snippets.links()).isTable((table) -> table.withHeader("Relation", "Description", "Foo") + .row("a", "one", "alpha") + .row("b", "two", "bravo")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { HypermediaDocumentation .links(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), new LinkDescriptor("a").description("one")) .and(new LinkDescriptor("b").description("two")) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()) - .is(tableWithHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`a`", "one").row("`b`", "two")); } - @Test - public void tableCellContentIsEscapedWhenNecessary() throws IOException { + @RenderedSnippetTest + void tableCellContentIsEscapedWhenNecessary(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new LinksSnippet(new StubLinkExtractor().withLinks(new Link("Foo|Bar", "foo")), Arrays.asList(new LinkDescriptor("Foo|Bar").description("one|two"))) - .document(this.operationBuilder.build()); - assertThat(this.generatedSnippets.links()).is(tableWithHeader("Relation", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .document(operationBuilder.build()); + assertThat(snippets.links()) + .isTable((table) -> table.withHeader("Relation", "Description").row("`Foo|Bar`", "one|two")); + } + + @SnippetTest + void undocumentedLink(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), + Collections.emptyList()) + .document(operationBuilder.build())) + .withMessage("Links with the following relations were not documented: [foo]"); + } + + @SnippetTest + void missingLink(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor(), + Arrays.asList(new LinkDescriptor("foo").description("bar"))) + .document(operationBuilder.build())) + .withMessage("Links with the following relations were not found in the response: [foo]"); + } + + @SnippetTest + void undocumentedLinkAndMissingLink(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha")), + Arrays.asList(new LinkDescriptor("foo").description("bar"))) + .document(operationBuilder.build())) + .withMessage("Links with the following relations were not documented: [a]. Links with the following" + + " relations were not found in the response: [foo]"); } - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); + @SnippetTest + void linkWithNoDescription(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")), + Arrays.asList(new LinkDescriptor("foo"))) + .document(operationBuilder.build())) + .withMessage("No description was provided for the link with rel 'foo' and no title was available" + + " from the link in the payload"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/ParametersTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/ParametersTests.java deleted file mode 100644 index a6fefcd85..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/ParametersTests.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2014-2018 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.restdocs.operation; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link Parameters}. - * - * @author Andy Wilkinson - */ -public class ParametersTests { - - private final Parameters parameters = new Parameters(); - - @Test - public void queryStringForNoParameters() { - assertThat(this.parameters.toQueryString()).isEqualTo(""); - } - - @Test - public void queryStringForSingleParameter() { - this.parameters.add("a", "b"); - assertThat(this.parameters.toQueryString()).isEqualTo("a=b"); - } - - @Test - public void queryStringForSingleParameterWithMultipleValues() { - this.parameters.add("a", "b"); - this.parameters.add("a", "c"); - assertThat(this.parameters.toQueryString()).isEqualTo("a=b&a=c"); - } - - @Test - public void queryStringForMutipleParameters() { - this.parameters.add("a", "alpha"); - this.parameters.add("b", "bravo"); - assertThat(this.parameters.toQueryString()).isEqualTo("a=alpha&b=bravo"); - } - - @Test - public void queryStringForParameterWithEmptyValue() { - this.parameters.add("a", ""); - assertThat(this.parameters.toQueryString()).isEqualTo("a="); - } - - @Test - public void queryStringForParameterWithNullValue() { - this.parameters.add("a", null); - assertThat(this.parameters.toQueryString()).isEqualTo("a="); - } - - @Test - public void queryStringForParameterThatRequiresEncoding() { - this.parameters.add("a", "alpha&bravo"); - assertThat(this.parameters.toQueryString()).isEqualTo("a=alpha%26bravo"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java deleted file mode 100644 index 28ca0d2fe..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.operation; - -import java.net.URI; -import java.util.Arrays; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Tests for {@link QueryStringParser}. - * - * @author Andy Wilkinson - */ -public class QueryStringParserTests { - - private final QueryStringParser queryStringParser = new QueryStringParser(); - - @Test - public void noParameters() { - Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost")); - assertThat(parameters.size()).isEqualTo(0); - } - - @Test - public void singleParameter() { - Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=alpha")); - assertThat(parameters.size()).isEqualTo(1); - assertThat(parameters).containsEntry("a", Arrays.asList("alpha")); - } - - @Test - public void multipleParameters() { - Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=alpha&b=bravo&c=charlie")); - assertThat(parameters.size()).isEqualTo(3); - assertThat(parameters).containsEntry("a", Arrays.asList("alpha")); - assertThat(parameters).containsEntry("b", Arrays.asList("bravo")); - assertThat(parameters).containsEntry("c", Arrays.asList("charlie")); - } - - @Test - public void multipleParametersWithSameKey() { - Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=apple&a=avocado")); - assertThat(parameters.size()).isEqualTo(1); - assertThat(parameters).containsEntry("a", Arrays.asList("apple", "avocado")); - } - - @Test - public void encoded() { - Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=al%26%3Dpha")); - assertThat(parameters.size()).isEqualTo(1); - assertThat(parameters).containsEntry("a", Arrays.asList("al&=pha")); - } - - @Test - public void malformedParameter() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.queryStringParser.parse(URI.create("http://localhost?a=apple=avocado"))) - .withMessage("The parameter 'a=apple=avocado' is malformed"); - } - - @Test - public void emptyParameter() { - Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=")); - assertThat(parameters.size()).isEqualTo(1); - assertThat(parameters).containsEntry("a", Arrays.asList("")); - } - - @Test - public void emptyAndNotEmptyParameter() { - Parameters parameters = this.queryStringParser.parse(URI.create("http://localhost?a=&a=alpha")); - assertThat(parameters.size()).isEqualTo(1); - assertThat(parameters).containsEntry("a", Arrays.asList("", "alpha")); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java index 57b54c98a..107a4d0d4 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -19,7 +19,7 @@ import java.net.URI; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -30,7 +30,6 @@ import org.springframework.restdocs.operation.OperationRequestPart; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; -import org.springframework.restdocs.operation.Parameters; import static org.assertj.core.api.Assertions.assertThat; @@ -40,7 +39,7 @@ * @author Andy Wilkinson * */ -public class ContentModifyingOperationPreprocessorTests { +class ContentModifyingOperationPreprocessorTests { private final OperationRequestFactory requestFactory = new OperationRequestFactory(); @@ -57,28 +56,27 @@ public byte[] modifyContent(byte[] originalContent, MediaType mediaType) { }); @Test - public void modifyRequestContent() { + void modifyRequestContent() { OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - "content".getBytes(), new HttpHeaders(), new Parameters(), - Collections.emptyList()); + "content".getBytes(), new HttpHeaders(), Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes()); } @Test - public void modifyResponseContent() { - OperationResponse response = this.responseFactory.create(HttpStatus.OK.value(), new HttpHeaders(), + void modifyResponseContent() { + OperationResponse response = this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), "content".getBytes()); OperationResponse preprocessed = this.preprocessor.preprocess(response); assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes()); } @Test - public void contentLengthIsUpdated() { + void contentLengthIsUpdated() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentLength(7); OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - "content".getBytes(), httpHeaders, new Parameters(), Collections.emptyList()); + "content".getBytes(), httpHeaders, Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); assertThat(preprocessed.getHeaders().getContentLength()).isEqualTo(8L); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java index b9f398448..a395d6402 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,7 +18,7 @@ import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.operation.OperationRequest; @@ -31,10 +31,10 @@ * * @author Andy Wilkinson */ -public class DelegatingOperationRequestPreprocessorTests { +class DelegatingOperationRequestPreprocessorTests { @Test - public void delegationOccurs() { + void delegationOccurs() { OperationRequest originalRequest = mock(OperationRequest.class); OperationPreprocessor preprocessor1 = mock(OperationPreprocessor.class); OperationRequest preprocessedRequest1 = mock(OperationRequest.class); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java index 2a2bb506f..513eeb869 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,7 +18,7 @@ import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.operation.OperationResponse; @@ -31,10 +31,10 @@ * * @author Andy Wilkinson */ -public class DelegatingOperationResponsePreprocessorTests { +class DelegatingOperationResponsePreprocessorTests { @Test - public void delegationOccurs() { + void delegationOccurs() { OperationResponse originalResponse = mock(OperationResponse.class); OperationPreprocessor preprocessor1 = mock(OperationPreprocessor.class); OperationResponse preprocessedResponse1 = mock(OperationResponse.class); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java deleted file mode 100644 index 87f5e8c0c..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2014-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.restdocs.operation.preprocess; - -import java.net.URI; -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Test; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.restdocs.operation.OperationRequest; -import org.springframework.restdocs.operation.OperationRequestFactory; -import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.OperationResponse; -import org.springframework.restdocs.operation.OperationResponseFactory; -import org.springframework.restdocs.operation.Parameters; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link HeaderRemovingOperationPreprocessorTests}. - * - * @author Andy Wilkinson - * @author Roland Huss - */ -public class HeaderRemovingOperationPreprocessorTests { - - private final OperationRequestFactory requestFactory = new OperationRequestFactory(); - - private final OperationResponseFactory responseFactory = new OperationResponseFactory(); - - private final HeaderRemovingOperationPreprocessor preprocessor = new HeaderRemovingOperationPreprocessor( - new ExactMatchHeaderFilter("b")); - - @Test - public void modifyRequestHeaders() { - OperationRequest request = this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, - new byte[0], getHttpHeaders(), new Parameters(), Collections.emptyList()); - OperationRequest preprocessed = this.preprocessor.preprocess(request); - assertThat(preprocessed.getHeaders().size()).isEqualTo(2); - assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); - assertThat(preprocessed.getHeaders()).containsEntry("Host", Arrays.asList("localhost")); - } - - @Test - public void modifyResponseHeaders() { - OperationResponse response = createResponse(); - OperationResponse preprocessed = this.preprocessor.preprocess(response); - assertThat(preprocessed.getHeaders().size()).isEqualTo(1); - assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); - } - - @Test - public void modifyWithPattern() { - OperationResponse response = createResponse("content-length", "1234"); - HeaderRemovingOperationPreprocessor processor = new HeaderRemovingOperationPreprocessor( - new PatternMatchHeaderFilter("co.*le(.)gth]")); - OperationResponse preprocessed = processor.preprocess(response); - assertThat(preprocessed.getHeaders().size()).isEqualTo(2); - assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); - assertThat(preprocessed.getHeaders()).containsEntry("b", Arrays.asList("bravo", "banana")); - } - - @Test - public void removeAllHeaders() { - HeaderRemovingOperationPreprocessor processor = new HeaderRemovingOperationPreprocessor( - new PatternMatchHeaderFilter(".*")); - OperationResponse preprocessed = processor.preprocess(createResponse()); - assertThat(preprocessed.getHeaders().size()).isEqualTo(0); - } - - private OperationResponse createResponse(String... extraHeaders) { - return this.responseFactory.create(HttpStatus.OK.value(), getHttpHeaders(extraHeaders), new byte[0]); - } - - private HttpHeaders getHttpHeaders(String... extraHeaders) { - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add("a", "alpha"); - httpHeaders.add("b", "bravo"); - httpHeaders.add("b", "banana"); - for (int i = 0; i < extraHeaders.length; i += 2) { - httpHeaders.add(extraHeaders[i], extraHeaders[i + 1]); - } - return httpHeaders; - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeadersModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeadersModifyingOperationPreprocessorTests.java new file mode 100644 index 000000000..b68b27ff9 --- /dev/null +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeadersModifyingOperationPreprocessorTests.java @@ -0,0 +1,178 @@ +/* + * Copyright 2014-2025 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.restdocs.operation.preprocess; + +import java.net.URI; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + +import org.junit.jupiter.api.Test; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.restdocs.operation.OperationRequest; +import org.springframework.restdocs.operation.OperationRequestFactory; +import org.springframework.restdocs.operation.OperationResponse; +import org.springframework.restdocs.operation.OperationResponseFactory; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; + +/** + * Tests for {@link HeadersModifyingOperationPreprocessor}. + * + * @author Jihoon Cha + * @author Andy Wilkinson + */ +class HeadersModifyingOperationPreprocessorTests { + + private final HeadersModifyingOperationPreprocessor preprocessor = new HeadersModifyingOperationPreprocessor(); + + @Test + void addNewHeader() { + this.preprocessor.add("a", "alpha"); + assertThat(this.preprocessor.preprocess(createRequest()).getHeaders().get("a")) + .isEqualTo(Arrays.asList("alpha")); + assertThat(this.preprocessor.preprocess(createResponse()).getHeaders().get("a")) + .isEqualTo(Arrays.asList("alpha")); + } + + @Test + void addValueToExistingHeader() { + this.preprocessor.add("a", "alpha"); + assertThat(this.preprocessor.preprocess(createRequest((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerSet()).contains(entry("a", Arrays.asList("apple", "alpha"))); + assertThat(this.preprocessor.preprocess(createResponse((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerSet()).contains(entry("a", Arrays.asList("apple", "alpha"))); + } + + @Test + void setNewHeader() { + this.preprocessor.set("a", "alpha", "avocado"); + assertThat(this.preprocessor.preprocess(createRequest()).getHeaders().headerSet()) + .contains(entry("a", Arrays.asList("alpha", "avocado"))); + assertThat(this.preprocessor.preprocess(createResponse()).getHeaders().headerSet()) + .contains(entry("a", Arrays.asList("alpha", "avocado"))); + } + + @Test + void setExistingHeader() { + this.preprocessor.set("a", "alpha", "avocado"); + assertThat(this.preprocessor.preprocess(createRequest((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerSet()).contains(entry("a", Arrays.asList("alpha", "avocado"))); + assertThat(this.preprocessor.preprocess(createResponse((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerSet()).contains(entry("a", Arrays.asList("alpha", "avocado"))); + } + + @Test + void removeNonExistentHeader() { + this.preprocessor.remove("a"); + assertThat(this.preprocessor.preprocess(createRequest()).getHeaders().headerNames()).doesNotContain("a"); + assertThat(this.preprocessor.preprocess(createResponse()).getHeaders().headerNames()).doesNotContain("a"); + } + + @Test + void removeHeader() { + this.preprocessor.remove("a"); + assertThat(this.preprocessor.preprocess(createRequest((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerNames()).doesNotContain("a"); + assertThat(this.preprocessor.preprocess(createResponse((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerNames()).doesNotContain("a"); + } + + @Test + void removeHeaderValueForNonExistentHeader() { + this.preprocessor.remove("a", "apple"); + assertThat(this.preprocessor.preprocess(createRequest()).getHeaders().headerNames()).doesNotContain("a"); + assertThat(this.preprocessor.preprocess(createResponse()).getHeaders().headerNames()).doesNotContain("a"); + } + + @Test + void removeHeaderValueWithMultipleValues() { + this.preprocessor.remove("a", "apple"); + assertThat( + this.preprocessor.preprocess(createRequest((headers) -> headers.addAll("a", List.of("apple", "alpha")))) + .getHeaders() + .headerSet()) + .contains(entry("a", Arrays.asList("alpha"))); + assertThat(this.preprocessor + .preprocess(createResponse((headers) -> headers.addAll("a", List.of("apple", "alpha")))) + .getHeaders() + .headerSet()).contains(entry("a", Arrays.asList("alpha"))); + } + + @Test + void removeHeaderValueWithSingleValueRemovesEntryEntirely() { + this.preprocessor.remove("a", "apple"); + assertThat(this.preprocessor.preprocess(createRequest((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerNames()).doesNotContain("a"); + assertThat(this.preprocessor.preprocess(createResponse((headers) -> headers.add("a", "apple"))) + .getHeaders() + .headerNames()).doesNotContain("a"); + } + + @Test + void removeHeadersByNamePattern() { + Consumer headersCustomizer = (headers) -> { + headers.add("apple", "apple"); + headers.add("alpha", "alpha"); + headers.add("avocado", "avocado"); + headers.add("bravo", "bravo"); + }; + this.preprocessor.removeMatching("^a.*"); + assertThat(this.preprocessor.preprocess(createRequest(headersCustomizer)).getHeaders().headerNames()) + .containsOnly("Host", "bravo"); + assertThat(this.preprocessor.preprocess(createResponse(headersCustomizer)).getHeaders().headerNames()) + .containsOnly("bravo"); + } + + private OperationRequest createRequest() { + return createRequest(null); + } + + private OperationRequest createRequest(Consumer headersCustomizer) { + HttpHeaders headers = new HttpHeaders(); + if (headersCustomizer != null) { + headersCustomizer.accept(headers); + } + return new OperationRequestFactory().create(URI.create("http://localhost:8080"), HttpMethod.GET, new byte[0], + headers, Collections.emptyList()); + } + + private OperationResponse createResponse() { + return createResponse(null); + } + + private OperationResponse createResponse(Consumer headersCustomizer) { + HttpHeaders headers = new HttpHeaders(); + if (headersCustomizer != null) { + headersCustomizer.accept(headers); + } + return new OperationResponseFactory().create(HttpStatus.OK, headers, new byte[0]); + } + +} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java index ad13b2551..7fe262d13 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -26,7 +26,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.hypermedia.Link; @@ -38,7 +38,7 @@ * @author Andy Wilkinson * */ -public class LinkMaskingContentModifierTests { +class LinkMaskingContentModifierTests { private final ContentModifier contentModifier = new LinkMaskingContentModifier(); @@ -47,38 +47,38 @@ public class LinkMaskingContentModifierTests { private final Link[] maskedLinks = new Link[] { new Link("a", "..."), new Link("b", "...") }; @Test - public void halLinksAreMasked() throws Exception { + void halLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null)) .isEqualTo(halPayloadWithLinks(this.maskedLinks)); } @Test - public void formattedHalLinksAreMasked() throws Exception { + void formattedHalLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(formattedHalPayloadWithLinks(this.links), null)) .isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks)); } @Test - public void atomLinksAreMasked() throws Exception { + void atomLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(atomPayloadWithLinks(this.links), null)) .isEqualTo(atomPayloadWithLinks(this.maskedLinks)); } @Test - public void formattedAtomLinksAreMasked() throws Exception { + void formattedAtomLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(formattedAtomPayloadWithLinks(this.links), null)) .isEqualTo(formattedAtomPayloadWithLinks(this.maskedLinks)); } @Test - public void maskCanBeCustomized() throws Exception { + void maskCanBeCustomized() throws Exception { assertThat( new LinkMaskingContentModifier("custom").modifyContent(formattedAtomPayloadWithLinks(this.links), null)) .isEqualTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), new Link("b", "custom"))); } @Test - public void maskCanUseUtf8Characters() throws Exception { + void maskCanUseUtf8Characters() throws Exception { String ellipsis = "\u2026"; assertThat( new LinkMaskingContentModifier(ellipsis).modifyContent(formattedHalPayloadWithLinks(this.links), null)) diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java deleted file mode 100644 index e0a45414b..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.operation.preprocess; - -import java.net.URI; -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Test; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.restdocs.operation.OperationRequest; -import org.springframework.restdocs.operation.OperationRequestFactory; -import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.Parameters; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link ParametersModifyingOperationPreprocessor}. - * - * @author Andy Wilkinson - */ -public class ParametersModifyingOperationPreprocessorTests { - - private final ParametersModifyingOperationPreprocessor preprocessor = new ParametersModifyingOperationPreprocessor(); - - @Test - public void addNewParameter() { - Parameters parameters = new Parameters(); - OperationRequest request = this.preprocessor.add("a", "alpha").preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?a=alpha")); - } - - @Test - public void addValueToExistingParameter() { - Parameters parameters = new Parameters(); - parameters.add("a", "apple"); - OperationRequest request = this.preprocessor.add("a", "alpha").preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("apple", "alpha")); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?a=apple&a=alpha")); - } - - @Test - public void setNewParameter() { - Parameters parameters = new Parameters(); - OperationRequest request = this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "avocado")); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?a=alpha&a=avocado")); - } - - @Test - public void setExistingParameter() { - Parameters parameters = new Parameters(); - parameters.add("a", "apple"); - OperationRequest request = this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "avocado")); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?a=alpha&a=avocado")); - } - - @Test - public void removeNonExistentParameter() { - Parameters parameters = new Parameters(); - OperationRequest request = this.preprocessor.remove("a").preprocess(createGetRequest(parameters)); - assertThat(request.getParameters().size()).isEqualTo(0); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080")); - } - - @Test - public void removeParameter() { - Parameters parameters = new Parameters(); - parameters.add("a", "apple"); - OperationRequest request = this.preprocessor.remove("a").preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).isEmpty(); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080")); - } - - @Test - public void removeParameterValueForNonExistentParameter() { - Parameters parameters = new Parameters(); - OperationRequest request = this.preprocessor.remove("a", "apple").preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).isEmpty(); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080")); - } - - @Test - public void removeParameterValueWithMultipleValues() { - Parameters parameters = new Parameters(); - parameters.add("a", "apple"); - parameters.add("a", "alpha"); - parameters.add("b", "bravo"); - OperationRequest request = this.preprocessor.remove("a", "apple").preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?a=alpha&b=bravo")); - } - - @Test - public void removeParameterValueWithSingleValueRemovesEntryEntirely() { - Parameters parameters = new Parameters(); - parameters.add("a", "apple"); - parameters.add("b", "bravo"); - OperationRequest request = this.preprocessor.remove("a", "apple").preprocess(createGetRequest(parameters)); - assertThat(request.getParameters()).doesNotContainKey("a"); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080?b=bravo")); - } - - @Test - public void whenParametersOfANonGetRequestAreModifiedThenTheQueryStringIsUnaffected() { - Parameters parameters = new Parameters(); - parameters.add("a", "apple"); - parameters.add("b", "bravo"); - OperationRequest request = this.preprocessor.remove("a", "apple").preprocess(createPostRequest(parameters)); - assertThat(request.getParameters()).doesNotContainKey("a"); - assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080")); - } - - private OperationRequest createGetRequest(Parameters parameters) { - return new OperationRequestFactory().create( - URI.create("http://localhost:8080" + (parameters.isEmpty() ? "" : "?" + parameters.toQueryString())), - HttpMethod.GET, new byte[0], new HttpHeaders(), parameters, - Collections.emptyList()); - } - - private OperationRequest createPostRequest(Parameters parameters) { - return new OperationRequestFactory().create(URI.create("http://localhost:8080"), HttpMethod.POST, new byte[0], - new HttpHeaders(), parameters, Collections.emptyList()); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java index 838a045e3..61c24b77b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -20,7 +20,7 @@ import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; @@ -31,10 +31,10 @@ * * @author Andy Wilkinson */ -public class PatternReplacingContentModifierTests { +class PatternReplacingContentModifierTests { @Test - public void patternsAreReplaced() { + void patternsAreReplaced() { Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", Pattern.CASE_INSENSITIVE); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); @@ -44,7 +44,7 @@ public void patternsAreReplaced() { } @Test - public void contentThatDoesNotMatchIsUnchanged() { + void contentThatDoesNotMatchIsUnchanged() { Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", Pattern.CASE_INSENSITIVE); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); @@ -53,7 +53,7 @@ public void contentThatDoesNotMatchIsUnchanged() { } @Test - public void encodingIsPreservedUsingCharsetFromContentType() { + void encodingIsPreservedUsingCharsetFromContentType() { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; Pattern pattern = Pattern.compile("[0-9]+"); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>"); @@ -63,7 +63,7 @@ public void encodingIsPreservedUsingCharsetFromContentType() { } @Test - public void encodingIsPreservedUsingFallbackCharset() { + void encodingIsPreservedUsingFallbackCharset() { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; Pattern pattern = Pattern.compile("[0-9]+"); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier(pattern, "<>", diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java index 386624a6f..a0c28376a 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -20,10 +20,11 @@ import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.restdocs.testfixtures.OutputCaptureRule; +import org.springframework.restdocs.testfixtures.jupiter.CapturedOutput; +import org.springframework.restdocs.testfixtures.jupiter.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -33,19 +34,17 @@ * @author Andy Wilkinson * */ -public class PrettyPrintingContentModifierTests { - - @Rule - public OutputCaptureRule outputCapture = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class PrettyPrintingContentModifierTests { @Test - public void prettyPrintJson() { + void prettyPrintJson() { assertThat(new PrettyPrintingContentModifier().modifyContent("{\"a\":5}".getBytes(), null)) .isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes()); } @Test - public void prettyPrintXml() { + void prettyPrintXml() { assertThat(new PrettyPrintingContentModifier() .modifyContent("".getBytes(), null)) .isEqualTo(String @@ -55,28 +54,28 @@ public void prettyPrintXml() { } @Test - public void empytContentIsHandledGracefully() { + void empytContentIsHandledGracefully() { assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null)).isEqualTo("".getBytes()); } @Test - public void nonJsonAndNonXmlContentIsHandledGracefully() { + void nonJsonAndNonXmlContentIsHandledGracefully(CapturedOutput output) { String content = "abcdefg"; assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), null)) .isEqualTo(content.getBytes()); - assertThat(this.outputCapture).isEmpty(); + assertThat(output).isEmpty(); } @Test - public void nonJsonContentThatInitiallyLooksLikeJsonIsHandledGracefully() { + void nonJsonContentThatInitiallyLooksLikeJsonIsHandledGracefully(CapturedOutput output) { String content = "\"abc\",\"def\""; assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), null)) .isEqualTo(content.getBytes()); - assertThat(this.outputCapture).isEmpty(); + assertThat(output).isEmpty(); } @Test - public void encodingIsPreserved() throws Exception { + void encodingIsPreserved() throws Exception { Map input = new HashMap<>(); input.put("japanese", "\u30b3\u30f3\u30c6\u30f3\u30c4"); ObjectMapper objectMapper = new ObjectMapper(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java index 37fed8a93..0c5724eb7 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -21,7 +21,7 @@ import java.util.Collections; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -32,7 +32,6 @@ import org.springframework.restdocs.operation.OperationRequestPartFactory; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; import static org.assertj.core.api.Assertions.assertThat; @@ -42,7 +41,7 @@ * * @author Andy Wilkinson */ -public class UriModifyingOperationPreprocessorTests { +class UriModifyingOperationPreprocessorTests { private final OperationRequestFactory requestFactory = new OperationRequestFactory(); @@ -51,14 +50,14 @@ public class UriModifyingOperationPreprocessorTests { private final UriModifyingOperationPreprocessor preprocessor = new UriModifyingOperationPreprocessor(); @Test - public void requestUriSchemeCanBeModified() { + void requestUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("http://localhost:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345")); } @Test - public void requestUriHostCanBeModified() { + void requestUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("https://api.foo.com:12345")); assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:12345")); @@ -66,7 +65,7 @@ public void requestUriHostCanBeModified() { } @Test - public void requestUriPortCanBeModified() { + void requestUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("https://api.example.com:12345")); @@ -75,7 +74,7 @@ public void requestUriPortCanBeModified() { } @Test - public void requestUriPortCanBeRemoved() { + void requestUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("https://api.example.com:12345")); @@ -84,7 +83,7 @@ public void requestUriPortCanBeRemoved() { } @Test - public void requestUriPathIsPreserved() { + void requestUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); @@ -92,7 +91,7 @@ public void requestUriPathIsPreserved() { } @Test - public void requestUriQueryIsPreserved() { + void requestUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); @@ -100,7 +99,7 @@ public void requestUriQueryIsPreserved() { } @Test - public void requestUriAnchorIsPreserved() { + void requestUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); @@ -108,7 +107,7 @@ public void requestUriAnchorIsPreserved() { } @Test - public void requestContentUriSchemeCanBeModified() { + void requestContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'https://localhost:12345' should be used. foo:bar will be unaffected")); @@ -117,7 +116,7 @@ public void requestContentUriSchemeCanBeModified() { } @Test - public void requestContentUriHostCanBeModified() { + void requestContentUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'https://localhost:12345' should be used. foo:bar will be unaffected")); @@ -126,7 +125,7 @@ public void requestContentUriHostCanBeModified() { } @Test - public void requestContentHostOfUriWithoutPortCanBeModified() { + void requestContentHostOfUriWithoutPortCanBeModified() { this.preprocessor.host("api.example.com"); OperationRequest processed = this.preprocessor.preprocess( createRequestWithContent("The uri 'https://localhost' should be used. foo:bar will be unaffected")); @@ -135,7 +134,7 @@ public void requestContentHostOfUriWithoutPortCanBeModified() { } @Test - public void requestContentUriPortCanBeAdded() { + void requestContentUriPortCanBeAdded() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor.preprocess( createRequestWithContent("The uri 'http://localhost' should be used. foo:bar will be unaffected")); @@ -144,7 +143,7 @@ public void requestContentUriPortCanBeAdded() { } @Test - public void requestContentUriPortCanBeModified() { + void requestContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used. foo:bar will be unaffected")); @@ -153,7 +152,7 @@ public void requestContentUriPortCanBeModified() { } @Test - public void requestContentUriPortCanBeRemoved() { + void requestContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used. foo:bar will be unaffected")); @@ -162,7 +161,7 @@ public void requestContentUriPortCanBeRemoved() { } @Test - public void multipleRequestContentUrisCanBeModified() { + void multipleRequestContentUrisCanBeModified() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); @@ -171,7 +170,7 @@ public void multipleRequestContentUrisCanBeModified() { } @Test - public void requestContentUriPathIsPreserved() { + void requestContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); @@ -179,7 +178,7 @@ public void requestContentUriPathIsPreserved() { } @Test - public void requestContentUriQueryIsPreserved() { + void requestContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); @@ -187,7 +186,7 @@ public void requestContentUriQueryIsPreserved() { } @Test - public void requestContentUriAnchorIsPreserved() { + void requestContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used")); @@ -195,7 +194,7 @@ public void requestContentUriAnchorIsPreserved() { } @Test - public void responseContentUriSchemeCanBeModified() { + void responseContentUriSchemeCanBeModified() { this.preprocessor.scheme("https"); OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); @@ -203,7 +202,7 @@ public void responseContentUriSchemeCanBeModified() { } @Test - public void responseContentUriHostCanBeModified() { + void responseContentUriHostCanBeModified() { this.preprocessor.host("api.example.com"); OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent("The uri 'https://localhost:12345' should be used")); @@ -212,7 +211,7 @@ public void responseContentUriHostCanBeModified() { } @Test - public void responseContentUriPortCanBeModified() { + void responseContentUriPortCanBeModified() { this.preprocessor.port(23456); OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); @@ -220,7 +219,7 @@ public void responseContentUriPortCanBeModified() { } @Test - public void responseContentUriPortCanBeRemoved() { + void responseContentUriPortCanBeRemoved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); @@ -228,7 +227,7 @@ public void responseContentUriPortCanBeRemoved() { } @Test - public void multipleResponseContentUrisCanBeModified() { + void multipleResponseContentUrisCanBeModified() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor.preprocess(createResponseWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); @@ -237,7 +236,7 @@ public void multipleResponseContentUrisCanBeModified() { } @Test - public void responseContentUriPathIsPreserved() { + void responseContentUriPathIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); @@ -245,7 +244,7 @@ public void responseContentUriPathIsPreserved() { } @Test - public void responseContentUriQueryIsPreserved() { + void responseContentUriQueryIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); @@ -253,7 +252,7 @@ public void responseContentUriQueryIsPreserved() { } @Test - public void responseContentUriAnchorIsPreserved() { + void responseContentUriAnchorIsPreserved() { this.preprocessor.removePort(); OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used")); @@ -261,7 +260,7 @@ public void responseContentUriAnchorIsPreserved() { } @Test - public void urisInRequestHeadersCanBeModified() { + void urisInRequestHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") .preprocess(createRequestWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); @@ -269,14 +268,14 @@ public void urisInRequestHeadersCanBeModified() { } @Test - public void urisInResponseHeadersCanBeModified() { + void urisInResponseHeadersCanBeModified() { OperationResponse processed = this.preprocessor.host("api.example.com") .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); } @Test - public void urisInRequestPartHeadersCanBeModified() { + void urisInRequestPartHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) @@ -284,7 +283,7 @@ public void urisInRequestPartHeadersCanBeModified() { } @Test - public void urisInRequestPartContentCanBeModified() { + void urisInRequestPartContentCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") .preprocess(createRequestWithPartWithContent("The uri 'https://localhost:12345' should be used")); assertThat(new String(processed.getParts().iterator().next().getContent())) @@ -292,7 +291,7 @@ public void urisInRequestPartContentCanBeModified() { } @Test - public void modifiedUriDoesNotGetDoubleEncoded() { + void modifiedUriDoesNotGetDoubleEncoded() { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); @@ -301,54 +300,53 @@ public void modifiedUriDoesNotGetDoubleEncoded() { } @Test - public void resultingRequestHasCookiesFromOriginalRequst() { + void resultingRequestHasCookiesFromOriginalRequst() { List cookies = Arrays.asList(new RequestCookie("a", "alpha")); OperationRequest request = this.requestFactory.create(URI.create("http://localhost:12345"), HttpMethod.GET, - new byte[0], new HttpHeaders(), new Parameters(), Collections.emptyList(), - cookies); + new byte[0], new HttpHeaders(), Collections.emptyList(), cookies); OperationRequest processed = this.preprocessor.preprocess(request); assertThat(processed.getCookies().size()).isEqualTo(1); } private OperationRequest createRequestWithUri(String uri) { return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0], new HttpHeaders(), - new Parameters(), Collections.emptyList()); + Collections.emptyList()); } private OperationRequest createRequestWithContent(String content) { return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, content.getBytes(), - new HttpHeaders(), new Parameters(), Collections.emptyList()); + new HttpHeaders(), Collections.emptyList()); } private OperationRequest createRequestWithHeader(String name, String value) { HttpHeaders headers = new HttpHeaders(); headers.add(name, value); return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], headers, - new Parameters(), Collections.emptyList()); + Collections.emptyList()); } private OperationRequest createRequestWithPartWithHeader(String name, String value) { HttpHeaders headers = new HttpHeaders(); headers.add(name, value); return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), + new HttpHeaders(), Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", new byte[0], headers))); } private OperationRequest createRequestWithPartWithContent(String content) { return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), Arrays.asList(new OperationRequestPartFactory().create("part", - "fileName", content.getBytes(), new HttpHeaders()))); + new HttpHeaders(), Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", + content.getBytes(), new HttpHeaders()))); } private OperationResponse createResponseWithContent(String content) { - return this.responseFactory.create(HttpStatus.OK.value(), new HttpHeaders(), content.getBytes()); + return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), content.getBytes()); } private OperationResponse createResponseWithHeader(String name, String value) { HttpHeaders headers = new HttpHeaders(); headers.add(name, value); - return this.responseFactory.create(HttpStatus.OK.value(), headers, new byte[0]); + return this.responseFactory.create(HttpStatus.OK, headers, new byte[0]); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java index 8c1144d55..ce0945462 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -19,21 +19,13 @@ import java.io.IOException; import java.util.Arrays; -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.core.io.FileSystemResource; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import org.springframework.restdocs.testfixtures.GeneratedSnippets; -import org.springframework.restdocs.testfixtures.OperationBuilder; -import org.springframework.restdocs.testfixtures.SnippetConditions; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest.Format; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; /** @@ -41,33 +33,17 @@ * * @author Andy Wilkinson */ -public class AsciidoctorRequestFieldsSnippetTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Rule - public GeneratedSnippets generatedSnippets = new GeneratedSnippets(TemplateFormats.asciidoctor()); - - @Test - public void requestFieldsWithListDescription() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-fields")) - .willReturn(snippetResource("request-fields-with-list-description")); - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description(Arrays.asList("one", "two")))).document( - this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .content("{\"a\": \"foo\"}") - .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(SnippetConditions.tableWithHeader(TemplateFormats.asciidoctor(), "Path", "Type", "Description") - // - .row("a", "String", String.format(" - one%n - two")) - .configuration("[cols=\"1,1,1a\"]")); - } - - private FileSystemResource snippetResource(String name) { - return new FileSystemResource("src/test/resources/custom-snippet-templates/asciidoctor/" + name + ".snippet"); +class AsciidoctorRequestFieldsSnippetTests { + + @RenderedSnippetTest(format = Format.ASCIIDOCTOR) + @SnippetTemplate(snippet = "request-fields", template = "request-fields-with-list-description") + void requestFieldsWithListDescription(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description(Arrays.asList("one", "two")))) + .document(operationBuilder.request("http://localhost").content("{\"a\": \"foo\"}").build()); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("a", "String", String.format(" - one%n - two")) + .configuration("[cols=\"1,1,1a\"]")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java index 569261597..a5d0b958c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -25,13 +25,12 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** @@ -39,14 +38,11 @@ * * @author Andy Wilkinson */ -public class FieldPathPayloadSubsectionExtractorTests { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +class FieldPathPayloadSubsectionExtractorTests { @Test @SuppressWarnings("unchecked") - public void extractMapSubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { + void extractMapSubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.b") .extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); @@ -56,8 +52,7 @@ public void extractMapSubsectionOfJsonMap() throws JsonParseException, JsonMappi @Test @SuppressWarnings("unchecked") - public void extractSingleElementArraySubsectionOfJsonMap() - throws JsonParseException, JsonMappingException, IOException { + void extractSingleElementArraySubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[]") .extractSubsection("{\"a\":[{\"b\":5}]}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); @@ -67,8 +62,7 @@ public void extractSingleElementArraySubsectionOfJsonMap() @Test @SuppressWarnings("unchecked") - public void extractMultiElementArraySubsectionOfJsonMap() - throws JsonParseException, JsonMappingException, IOException { + void extractMultiElementArraySubsectionOfJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a") .extractSubsection("{\"a\":[{\"b\":5},{\"b\":4}]}".getBytes(), MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); @@ -78,7 +72,7 @@ public void extractMultiElementArraySubsectionOfJsonMap() @Test @SuppressWarnings("unchecked") - public void extractMapSubsectionFromSingleElementArrayInAJsonMap() + void extractMapSubsectionFromSingleElementArrayInAJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b") .extractSubsection("{\"a\":[{\"b\":{\"c\":5}}]}".getBytes(), MediaType.APPLICATION_JSON); @@ -89,7 +83,7 @@ public void extractMapSubsectionFromSingleElementArrayInAJsonMap() @Test @SuppressWarnings("unchecked") - public void extractMapSubsectionWithCommonStructureFromMultiElementArrayInAJsonMap() + void extractMapSubsectionWithCommonStructureFromMultiElementArrayInAJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b") .extractSubsection("{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6}}]}".getBytes(), MediaType.APPLICATION_JSON); @@ -99,33 +93,33 @@ public void extractMapSubsectionWithCommonStructureFromMultiElementArrayInAJsonM } @Test - public void extractMapSubsectionWithVaryingStructureFromMultiElementArrayInAJsonMap() { - this.thrown.expect(PayloadHandlingException.class); - this.thrown.expectMessage("The following non-optional uncommon paths were found: [a.[].b.d]"); - new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection( - "{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": 7}}]}".getBytes(), MediaType.APPLICATION_JSON); + void extractMapSubsectionWithVaryingStructureFromMultiElementArrayInAJsonMap() { + assertThatExceptionOfType(PayloadHandlingException.class) + .isThrownBy(() -> new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection( + "{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": 7}}]}".getBytes(), MediaType.APPLICATION_JSON)) + .withMessageContaining("The following non-optional uncommon paths were found: [a.[].b.d]"); } @Test - public void extractMapSubsectionWithVaryingStructureFromInconsistentJsonMap() { - this.thrown.expect(PayloadHandlingException.class); - this.thrown.expectMessage("The following non-optional uncommon paths were found: [*.d, *.d.e, *.d.f]"); - new FieldPathPayloadSubsectionExtractor("*.d").extractSubsection( - "{\"a\":{\"b\":1},\"c\":{\"d\":{\"e\":1,\"f\":2}}}".getBytes(), MediaType.APPLICATION_JSON); + void extractMapSubsectionWithVaryingStructureFromInconsistentJsonMap() { + assertThatExceptionOfType(PayloadHandlingException.class) + .isThrownBy(() -> new FieldPathPayloadSubsectionExtractor("*.d").extractSubsection( + "{\"a\":{\"b\":1},\"c\":{\"d\":{\"e\":1,\"f\":2}}}".getBytes(), MediaType.APPLICATION_JSON)) + .withMessageContaining("The following non-optional uncommon paths were found: [*.d, *.d.e, *.d.f]"); } @Test - public void extractMapSubsectionWithVaryingStructureFromInconsistentJsonMapWhereAllSubsectionFieldsAreOptional() { - this.thrown.expect(PayloadHandlingException.class); - this.thrown.expectMessage("The following non-optional uncommon paths were found: [*.d]"); - new FieldPathPayloadSubsectionExtractor("*.d").extractSubsection( - "{\"a\":{\"b\":1},\"c\":{\"d\":{\"e\":1,\"f\":2}}}".getBytes(), MediaType.APPLICATION_JSON, - Arrays.asList(new FieldDescriptor("e").optional(), new FieldDescriptor("f").optional())); + void extractMapSubsectionWithVaryingStructureFromInconsistentJsonMapWhereAllSubsectionFieldsAreOptional() { + assertThatExceptionOfType(PayloadHandlingException.class) + .isThrownBy(() -> new FieldPathPayloadSubsectionExtractor("*.d").extractSubsection( + "{\"a\":{\"b\":1},\"c\":{\"d\":{\"e\":1,\"f\":2}}}".getBytes(), MediaType.APPLICATION_JSON, + Arrays.asList(new FieldDescriptor("e").optional(), new FieldDescriptor("f").optional()))) + .withMessageContaining("The following non-optional uncommon paths were found: [*.d]"); } @Test @SuppressWarnings("unchecked") - public void extractMapSubsectionWithVaryingStructureDueToOptionalFieldsFromMultiElementArrayInAJsonMap() + void extractMapSubsectionWithVaryingStructureDueToOptionalFieldsFromMultiElementArrayInAJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection( "{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": 7}}]}".getBytes(), MediaType.APPLICATION_JSON, @@ -137,7 +131,7 @@ public void extractMapSubsectionWithVaryingStructureDueToOptionalFieldsFromMulti @Test @SuppressWarnings("unchecked") - public void extractMapSubsectionWithVaryingStructureDueToOptionalParentFieldsFromMultiElementArrayInAJsonMap() + void extractMapSubsectionWithVaryingStructureDueToOptionalParentFieldsFromMultiElementArrayInAJsonMap() throws JsonParseException, JsonMappingException, IOException { byte[] extractedPayload = new FieldPathPayloadSubsectionExtractor("a.[].b").extractSubsection( "{\"a\":[{\"b\":{\"c\":5}},{\"b\":{\"c\":6, \"d\": { \"e\": 7}}}]}".getBytes(), @@ -148,7 +142,7 @@ public void extractMapSubsectionWithVaryingStructureDueToOptionalParentFieldsFro } @Test - public void extractedSubsectionIsPrettyPrintedWhenInputIsPrettyPrinted() + void extractedSubsectionIsPrettyPrintedWhenInputIsPrettyPrinted() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException { ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); byte[] prettyPrintedPayload = objectMapper @@ -161,7 +155,7 @@ public void extractedSubsectionIsPrettyPrintedWhenInputIsPrettyPrinted() } @Test - public void extractedSubsectionIsNotPrettyPrintedWhenInputIsNotPrettyPrinted() + void extractedSubsectionIsNotPrettyPrintedWhenInputIsNotPrettyPrinted() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); byte[] payload = objectMapper @@ -173,7 +167,7 @@ public void extractedSubsectionIsNotPrettyPrintedWhenInputIsNotPrettyPrinted() } @Test - public void extractNonExistentSubsection() { + void extractNonExistentSubsection() { assertThatThrownBy(() -> new FieldPathPayloadSubsectionExtractor("a.c") .extractSubsection("{\"a\":{\"b\":{\"c\":5}}}".getBytes(), MediaType.APPLICATION_JSON)) .isInstanceOf(PayloadHandlingException.class) @@ -181,7 +175,7 @@ public void extractNonExistentSubsection() { } @Test - public void extractEmptyArraySubsection() { + void extractEmptyArraySubsection() { assertThatThrownBy(() -> new FieldPathPayloadSubsectionExtractor("a") .extractSubsection("{\"a\":[]}}".getBytes(), MediaType.APPLICATION_JSON)) .isInstanceOf(PayloadHandlingException.class) diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java index 080495ff0..da5b1e902 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldTypeResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,13 +18,12 @@ import java.util.Collections; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link FieldTypeResolver}. @@ -33,30 +32,6 @@ */ public class FieldTypeResolverTests { - @Rule - public ExpectedException thrownException = ExpectedException.none(); - - @Test - @Deprecated - public void whenForContentCalledWithJsonContentThenReturnsJsonFieldTypeResolver() { - assertThat(FieldTypeResolver.forContent("{\"field\": \"value\"}".getBytes(), MediaType.APPLICATION_JSON)) - .isInstanceOf(JsonContentHandler.class); - } - - @Test - @Deprecated - public void whenForContentCalledWithXmlContentThenReturnsXmlContentHandler() { - assertThat(FieldTypeResolver.forContent("5".getBytes(), MediaType.APPLICATION_XML)) - .isInstanceOf(XmlContentHandler.class); - } - - @Test - @Deprecated - public void whenForContentIsCalledWithInvalidContentThenExceptionIsThrown() { - this.thrownException.expect(PayloadHandlingException.class); - FieldTypeResolver.forContent("some".getBytes(), MediaType.APPLICATION_XML); - } - @Test public void whenForContentWithDescriptorsCalledWithJsonContentThenReturnsJsonFieldTypeResolver() { assertThat(FieldTypeResolver.forContentWithDescriptors("{\"field\": \"value\"}".getBytes(), @@ -73,9 +48,8 @@ public void whenForContentWithDescriptorsCalledWithXmlContentThenReturnsXmlConte @Test public void whenForContentWithDescriptorsIsCalledWithInvalidContentThenExceptionIsThrown() { - this.thrownException.expect(PayloadHandlingException.class); - FieldTypeResolver.forContentWithDescriptors("some".getBytes(), MediaType.APPLICATION_XML, - Collections.emptyList()); + assertThatExceptionOfType(PayloadHandlingException.class).isThrownBy(() -> FieldTypeResolver + .forContentWithDescriptors("some".getBytes(), MediaType.APPLICATION_XML, Collections.emptyList())); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java index 5a93f5010..43f0100af 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -20,11 +20,10 @@ import java.util.Collections; import java.util.List; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link JsonContentHandler}. @@ -32,36 +31,34 @@ * @author Andy Wilkinson * @author Mathias Düsterhöft */ -public class JsonContentHandlerTests { - - @Rule - public ExpectedException thrown = ExpectedException.none(); +class JsonContentHandlerTests { @Test - public void typeForFieldWithNullValueMustMatch() { - this.thrown.expect(FieldTypesDoNotMatchException.class); + void typeForFieldWithNullValueMustMatch() { FieldDescriptor descriptor = new FieldDescriptor("a").type(JsonFieldType.STRING); - new JsonContentHandler("{\"a\": null}".getBytes(), Arrays.asList(descriptor)).resolveFieldType(descriptor); + assertThatExceptionOfType(FieldTypesDoNotMatchException.class) + .isThrownBy(() -> new JsonContentHandler("{\"a\": null}".getBytes(), Arrays.asList(descriptor)) + .resolveFieldType(descriptor)); } @Test - public void typeForFieldWithNotNullAndThenNullValueMustMatch() { - this.thrown.expect(FieldTypesDoNotMatchException.class); + void typeForFieldWithNotNullAndThenNullValueMustMatch() { FieldDescriptor descriptor = new FieldDescriptor("a[].id").type(JsonFieldType.STRING); - new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}".getBytes(), Arrays.asList(descriptor)) - .resolveFieldType(descriptor); + assertThatExceptionOfType(FieldTypesDoNotMatchException.class).isThrownBy( + () -> new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}".getBytes(), Arrays.asList(descriptor)) + .resolveFieldType(descriptor)); } @Test - public void typeForFieldWithNullAndThenNotNullValueMustMatch() { - this.thrown.expect(FieldTypesDoNotMatchException.class); + void typeForFieldWithNullAndThenNotNullValueMustMatch() { FieldDescriptor descriptor = new FieldDescriptor("a.[].id").type(JsonFieldType.STRING); - new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes(), Arrays.asList(descriptor)) - .resolveFieldType(descriptor); + assertThatExceptionOfType(FieldTypesDoNotMatchException.class).isThrownBy( + () -> new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes(), Arrays.asList(descriptor)) + .resolveFieldType(descriptor)); } @Test - public void typeForOptionalFieldWithNumberAndThenNullValueIsNumber() { + void typeForOptionalFieldWithNumberAndThenNullValueIsNumber() { FieldDescriptor descriptor = new FieldDescriptor("a[].id").optional(); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes(), Arrays.asList(descriptor)) @@ -70,7 +67,7 @@ public void typeForOptionalFieldWithNumberAndThenNullValueIsNumber() { } @Test - public void typeForOptionalFieldWithNullAndThenNumberIsNumber() { + void typeForOptionalFieldWithNullAndThenNumberIsNumber() { FieldDescriptor descriptor = new FieldDescriptor("a[].id").optional(); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes(), Arrays.asList(descriptor)) @@ -79,7 +76,7 @@ public void typeForOptionalFieldWithNullAndThenNumberIsNumber() { } @Test - public void typeForFieldWithNumberAndThenNullValueIsVaries() { + void typeForFieldWithNumberAndThenNullValueIsVaries() { FieldDescriptor descriptor = new FieldDescriptor("a[].id"); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes(), Arrays.asList(descriptor)) @@ -88,7 +85,7 @@ public void typeForFieldWithNumberAndThenNullValueIsVaries() { } @Test - public void typeForFieldWithNullAndThenNumberIsVaries() { + void typeForFieldWithNullAndThenNumberIsVaries() { FieldDescriptor descriptor = new FieldDescriptor("a[].id"); Object fieldType = new JsonContentHandler("{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes(), Arrays.asList(descriptor)) @@ -97,7 +94,7 @@ public void typeForFieldWithNullAndThenNumberIsVaries() { } @Test - public void typeForOptionalFieldWithNullValueCanBeProvidedExplicitly() { + void typeForOptionalFieldWithNullValueCanBeProvidedExplicitly() { FieldDescriptor descriptor = new FieldDescriptor("a").type(JsonFieldType.STRING).optional(); Object fieldType = new JsonContentHandler("{\"a\": null}".getBytes(), Arrays.asList(descriptor)) .resolveFieldType(descriptor); @@ -105,7 +102,7 @@ public void typeForOptionalFieldWithNullValueCanBeProvidedExplicitly() { } @Test - public void typeForFieldWithSometimesPresentOptionalAncestorCanBeProvidedExplicitly() { + void typeForFieldWithSometimesPresentOptionalAncestorCanBeProvidedExplicitly() { FieldDescriptor descriptor = new FieldDescriptor("a.[].b.c").type(JsonFieldType.NUMBER); FieldDescriptor ancestor = new FieldDescriptor("a.[].b").optional(); Object fieldType = new JsonContentHandler("{\"a\":[ { \"d\": 4}, {\"b\":{\"c\":5}, \"d\": 4}]}".getBytes(), @@ -115,13 +112,13 @@ public void typeForFieldWithSometimesPresentOptionalAncestorCanBeProvidedExplici } @Test - public void failsFastWithNonJsonContent() { - this.thrown.expect(PayloadHandlingException.class); - new JsonContentHandler("Non-JSON content".getBytes(), Collections.emptyList()); + void failsFastWithNonJsonContent() { + assertThatExceptionOfType(PayloadHandlingException.class) + .isThrownBy(() -> new JsonContentHandler("Non-JSON content".getBytes(), Collections.emptyList())); } @Test - public void describedFieldThatIsNotPresentIsConsideredMissing() { + void describedFieldThatIsNotPresentIsConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c")); List missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes(), @@ -132,7 +129,7 @@ public void describedFieldThatIsNotPresentIsConsideredMissing() { } @Test - public void describedOptionalFieldThatIsNotPresentIsNotConsideredMissing() { + void describedOptionalFieldThatIsNotPresentIsNotConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c").optional()); List missingFields = new JsonContentHandler("{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes(), @@ -142,7 +139,7 @@ public void describedOptionalFieldThatIsNotPresentIsNotConsideredMissing() { } @Test - public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsPresentIsConsideredMissing() { + void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsPresentIsConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), new FieldDescriptor("a.c")); List missingFields = new JsonContentHandler("{\"a\":\"alpha\",\"b\":\"bravo\"}".getBytes(), @@ -153,7 +150,7 @@ public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsPresen } @Test - public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsNotPresentIsNotConsideredMissing() { + void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsNotPresentIsNotConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), new FieldDescriptor("a.c")); List missingFields = new JsonContentHandler("{\"b\":\"bravo\"}".getBytes(), descriptors) @@ -162,7 +159,7 @@ public void describedFieldThatIsNotPresentNestedBeneathOptionalFieldThatIsNotPre } @Test - public void describedFieldThatIsNotPresentNestedBeneathOptionalArrayThatIsEmptyIsNotConsideredMissing() { + void describedFieldThatIsNotPresentNestedBeneathOptionalArrayThatIsEmptyIsNotConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("outer"), new FieldDescriptor("outer[]").optional(), new FieldDescriptor("outer[].inner")); List missingFields = new JsonContentHandler("{\"outer\":[]}".getBytes(), descriptors) @@ -171,7 +168,7 @@ public void describedFieldThatIsNotPresentNestedBeneathOptionalArrayThatIsEmptyI } @Test - public void describedSometimesPresentFieldThatIsChildOfSometimesPresentOptionalArrayIsNotConsideredMissing() { + void describedSometimesPresentFieldThatIsChildOfSometimesPresentOptionalArrayIsNotConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a.[].c").optional(), new FieldDescriptor("a.[].c.d")); List missingFields = new JsonContentHandler( @@ -181,7 +178,7 @@ public void describedSometimesPresentFieldThatIsChildOfSometimesPresentOptionalA } @Test - public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatIsEmptyIsNotConsideredMissing() { + void describedMissingFieldThatIsChildOfNestedOptionalArrayThatIsEmptyIsNotConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a.[].b").optional(), new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c")); List missingFields = new JsonContentHandler("{\"a\":[{\"b\":[]}]}".getBytes(), descriptors) @@ -190,7 +187,7 @@ public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatIsEmptyIsNo } @Test - public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatContainsAnObjectIsConsideredMissing() { + void describedMissingFieldThatIsChildOfNestedOptionalArrayThatContainsAnObjectIsConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a.[].b").optional(), new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c")); List missingFields = new JsonContentHandler("{\"a\":[{\"b\":[{}]}]}".getBytes(), descriptors) @@ -200,7 +197,7 @@ public void describedMissingFieldThatIsChildOfNestedOptionalArrayThatContainsAnO } @Test - public void describedMissingFieldThatIsChildOfOptionalObjectThatIsNullIsNotConsideredMissing() { + void describedMissingFieldThatIsChildOfOptionalObjectThatIsNullIsNotConsideredMissing() { List descriptors = Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("a.b")); List missingFields = new JsonContentHandler("{\"a\":null}".getBytes(), descriptors) diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java index b350235dd..69324c659 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -16,7 +16,7 @@ package org.springframework.restdocs.payload; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.payload.JsonFieldPath.PathType; @@ -28,131 +28,131 @@ * @author Andy Wilkinson * @author Jeremy Rickard */ -public class JsonFieldPathTests { +class JsonFieldPathTests { @Test - public void pathTypeOfSingleFieldIsSingle() { + void pathTypeOfSingleFieldIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a"); assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test - public void pathTypeOfSingleNestedFieldIsSingle() { + void pathTypeOfSingleNestedFieldIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a.b"); assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test - public void pathTypeOfTopLevelArrayIsSingle() { + void pathTypeOfTopLevelArrayIsSingle() { JsonFieldPath path = JsonFieldPath.compile("[]"); assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test - public void pathTypeOfFieldBeneathTopLevelArrayIsMulti() { + void pathTypeOfFieldBeneathTopLevelArrayIsMulti() { JsonFieldPath path = JsonFieldPath.compile("[]a"); assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test - public void pathTypeOfSingleNestedArrayIsSingle() { + void pathTypeOfSingleNestedArrayIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a[]"); assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test - public void pathTypeOfArrayBeneathNestedFieldsIsSingle() { + void pathTypeOfArrayBeneathNestedFieldsIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a.b[]"); assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test - public void pathTypeOfArrayOfArraysIsMulti() { + void pathTypeOfArrayOfArraysIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a[][]"); assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test - public void pathTypeOfFieldBeneathAnArrayIsMulti() { + void pathTypeOfFieldBeneathAnArrayIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a[].b"); assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test - public void pathTypeOfFieldBeneathTopLevelWildcardIsMulti() { + void pathTypeOfFieldBeneathTopLevelWildcardIsMulti() { JsonFieldPath path = JsonFieldPath.compile("*.a"); assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test - public void pathTypeOfFieldBeneathNestedWildcardIsMulti() { + void pathTypeOfFieldBeneathNestedWildcardIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a.*.b"); assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test - public void pathTypeOfLeafWidlcardIsMulti() { + void pathTypeOfLeafWidlcardIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a.*"); assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test - public void compilationOfSingleElementPath() { + void compilationOfSingleElementPath() { assertThat(JsonFieldPath.compile("a").getSegments()).containsExactly("a"); } @Test - public void compilationOfMultipleElementPath() { + void compilationOfMultipleElementPath() { assertThat(JsonFieldPath.compile("a.b.c").getSegments()).containsExactly("a", "b", "c"); } @Test - public void compilationOfPathWithArraysWithNoDotSeparators() { + void compilationOfPathWithArraysWithNoDotSeparators() { assertThat(JsonFieldPath.compile("a[]b[]c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test - public void compilationOfPathWithArraysWithPreAndPostDotSeparators() { + void compilationOfPathWithArraysWithPreAndPostDotSeparators() { assertThat(JsonFieldPath.compile("a.[].b.[].c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test - public void compilationOfPathWithArraysWithPreDotSeparators() { + void compilationOfPathWithArraysWithPreDotSeparators() { assertThat(JsonFieldPath.compile("a.[]b.[]c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test - public void compilationOfPathWithArraysWithPostDotSeparators() { + void compilationOfPathWithArraysWithPostDotSeparators() { assertThat(JsonFieldPath.compile("a[].b[].c").getSegments()).containsExactly("a", "[]", "b", "[]", "c"); } @Test - public void compilationOfPathStartingWithAnArray() { + void compilationOfPathStartingWithAnArray() { assertThat(JsonFieldPath.compile("[]a.b.c").getSegments()).containsExactly("[]", "a", "b", "c"); } @Test - public void compilationOfMultipleElementPathWithBrackets() { + void compilationOfMultipleElementPathWithBrackets() { assertThat(JsonFieldPath.compile("['a']['b']['c']").getSegments()).containsExactly("a", "b", "c"); } @Test - public void compilationOfMultipleElementPathWithAndWithoutBrackets() { + void compilationOfMultipleElementPathWithAndWithoutBrackets() { assertThat(JsonFieldPath.compile("['a'][].b['c']").getSegments()).containsExactly("a", "[]", "b", "c"); } @Test - public void compilationOfMultipleElementPathWithAndWithoutBracketsAndEmbeddedDots() { + void compilationOfMultipleElementPathWithAndWithoutBracketsAndEmbeddedDots() { assertThat(JsonFieldPath.compile("['a.key'][].b['c']").getSegments()).containsExactly("a.key", "[]", "b", "c"); } @Test - public void compilationOfPathWithAWildcard() { + void compilationOfPathWithAWildcard() { assertThat(JsonFieldPath.compile("a.b.*.c").getSegments()).containsExactly("a", "b", "*", "c"); } @Test - public void compilationOfPathWithAWildcardInBrackets() { + void compilationOfPathWithAWildcardInBrackets() { assertThat(JsonFieldPath.compile("a.b.['*'].c").getSegments()).containsExactly("a", "b", "*", "c"); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java index 10b8d9a9f..2e770649c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -20,7 +20,7 @@ import java.util.Arrays; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.payload.JsonFieldProcessor.ExtractedField; @@ -31,10 +31,10 @@ * * @author Andy Wilkinson */ -public class JsonFieldPathsTests { +class JsonFieldPathsTests { @Test - public void noUncommonPathsForSingleItem() { + void noUncommonPathsForSingleItem() { assertThat( JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3}, {\"c\": null}]}"))) .getUncommon()) @@ -42,20 +42,20 @@ public void noUncommonPathsForSingleItem() { } @Test - public void noUncommonPathsForMultipleIdenticalItems() { + void noUncommonPathsForMultipleIdenticalItems() { Object item = json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"); assertThat(JsonFieldPaths.from(Arrays.asList(item, item)).getUncommon()).isEmpty(); } @Test - public void noUncommonPathsForMultipleMatchingItemsWithDifferentScalarValues() { + void noUncommonPathsForMultipleMatchingItemsWithDifferentScalarValues() { assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": [ { \"c\": 2}, {\"c\": 3} ]}"), json("{\"a\": 4, \"b\": [ { \"c\": 5}, {\"c\": 6} ]}"))) .getUncommon()).isEmpty(); } @Test - public void missingEntryInMapIsIdentifiedAsUncommon() { + void missingEntryInMapIsIdentifiedAsUncommon() { assertThat( JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1}"), json("{\"a\": 1}"), json("{\"a\": 1, \"b\": 2}"))) .getUncommon()) @@ -63,21 +63,21 @@ public void missingEntryInMapIsIdentifiedAsUncommon() { } @Test - public void missingEntryInNestedMapIsIdentifiedAsUncommon() { + void missingEntryInNestedMapIsIdentifiedAsUncommon() { assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"c\": 1, \"d\": 2}}"))) .getUncommon()).containsExactly("b.d"); } @Test - public void missingEntriesInNestedMapAreIdentifiedAsUncommon() { + void missingEntriesInNestedMapAreIdentifiedAsUncommon() { assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"d\": 2}}"))) .getUncommon()).containsExactly("b.c", "b.d"); } @Test - public void absentItemFromFieldExtractionCausesAllPresentFieldsToBeIdentifiedAsUncommon() { + void absentItemFromFieldExtractionCausesAllPresentFieldsToBeIdentifiedAsUncommon() { assertThat(JsonFieldPaths .from(Arrays.asList(ExtractedField.ABSENT, json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"c\": 1}}"), json("{\"a\": 1, \"b\": {\"d\": 2}}"))) @@ -85,14 +85,14 @@ public void absentItemFromFieldExtractionCausesAllPresentFieldsToBeIdentifiedAsU } @Test - public void missingEntryBeneathArrayIsIdentifiedAsUncommon() { + void missingEntryBeneathArrayIsIdentifiedAsUncommon() { assertThat(JsonFieldPaths .from(Arrays.asList(json("[{\"b\": 1}]"), json("[{\"b\": 1}]"), json("[{\"b\": 1, \"c\": 2}]"))) .getUncommon()).containsExactly("[].c"); } @Test - public void missingEntryBeneathNestedArrayIsIdentifiedAsUncommon() { + void missingEntryBeneathNestedArrayIsIdentifiedAsUncommon() { assertThat(JsonFieldPaths.from(Arrays.asList(json("{\"a\": [{\"b\": 1}]}"), json("{\"a\": [{\"b\": 1}]}"), json("{\"a\": [{\"b\": 1, \"c\": 2}]}"))) .getUncommon()).containsExactly("a.[].c"); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java index 4c2c45516..b87099857 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -26,7 +26,7 @@ import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.payload.JsonFieldProcessor.ExtractedField; @@ -37,19 +37,19 @@ * * @author Andy Wilkinson */ -public class JsonFieldProcessorTests { +class JsonFieldProcessorTests { private final JsonFieldProcessor fieldProcessor = new JsonFieldProcessor(); @Test - public void extractTopLevelMapEntry() { + void extractTopLevelMapEntry() { Map payload = new HashMap<>(); payload.put("a", "alpha"); assertThat(this.fieldProcessor.extract("a", payload).getValue()).isEqualTo("alpha"); } @Test - public void extractNestedMapEntry() { + void extractNestedMapEntry() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -58,7 +58,7 @@ public void extractNestedMapEntry() { } @Test - public void extractTopLevelArray() { + void extractTopLevelArray() { List> payload = new ArrayList<>(); Map bravo = new HashMap<>(); bravo.put("b", "bravo"); @@ -68,7 +68,7 @@ public void extractTopLevelArray() { } @Test - public void extractArray() { + void extractArray() { Map payload = new HashMap<>(); Map bravo = new HashMap<>(); bravo.put("b", "bravo"); @@ -78,7 +78,7 @@ public void extractArray() { } @Test - public void extractArrayContents() { + void extractArrayContents() { Map payload = new HashMap<>(); Map bravo = new HashMap<>(); bravo.put("b", "bravo"); @@ -88,7 +88,7 @@ public void extractArrayContents() { } @Test - public void extractFromItemsInArray() { + void extractFromItemsInArray() { Map payload = new HashMap<>(); Map entry = new HashMap<>(); entry.put("b", "bravo"); @@ -98,7 +98,7 @@ public void extractFromItemsInArray() { } @Test - public void extractOccasionallyAbsentFieldFromItemsInArray() { + void extractOccasionallyAbsentFieldFromItemsInArray() { Map payload = new HashMap<>(); Map entry = new HashMap<>(); entry.put("b", "bravo"); @@ -109,7 +109,7 @@ public void extractOccasionallyAbsentFieldFromItemsInArray() { } @Test - public void extractOccasionallyNullFieldFromItemsInArray() { + void extractOccasionallyNullFieldFromItemsInArray() { Map payload = new HashMap<>(); Map nonNullField = new HashMap<>(); nonNullField.put("b", "bravo"); @@ -121,7 +121,7 @@ public void extractOccasionallyNullFieldFromItemsInArray() { } @Test - public void extractNestedArray() { + void extractNestedArray() { Map payload = new HashMap<>(); Map entry1 = createEntry("id:1"); Map entry2 = createEntry("id:2"); @@ -133,7 +133,7 @@ public void extractNestedArray() { } @Test - public void extractFromItemsInNestedArray() { + void extractFromItemsInNestedArray() { Map payload = new HashMap<>(); Map entry1 = createEntry("id:1"); Map entry2 = createEntry("id:2"); @@ -144,7 +144,7 @@ public void extractFromItemsInNestedArray() { } @Test - public void extractArraysFromItemsInNestedArray() { + void extractArraysFromItemsInNestedArray() { Map payload = new HashMap<>(); Map entry1 = createEntry("ids", Arrays.asList(1, 2)); Map entry2 = createEntry("ids", Arrays.asList(3)); @@ -156,27 +156,27 @@ public void extractArraysFromItemsInNestedArray() { } @Test - public void nonExistentTopLevelField() { + void nonExistentTopLevelField() { assertThat(this.fieldProcessor.extract("a", Collections.emptyMap()).getValue()) .isEqualTo(ExtractedField.ABSENT); } @Test - public void nonExistentNestedField() { + void nonExistentNestedField() { HashMap payload = new HashMap<>(); - payload.put("a", new HashMap()); + payload.put("a", new HashMap<>()); assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test - public void nonExistentNestedFieldWhenParentIsNotAMap() { + void nonExistentNestedFieldWhenParentIsNotAMap() { HashMap payload = new HashMap<>(); payload.put("a", 5); assertThat(this.fieldProcessor.extract("a.b", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test - public void nonExistentFieldWhenParentIsAnArray() { + void nonExistentFieldWhenParentIsAnArray() { HashMap payload = new HashMap<>(); HashMap alpha = new HashMap<>(); alpha.put("b", Arrays.asList(new HashMap())); @@ -185,20 +185,20 @@ public void nonExistentFieldWhenParentIsAnArray() { } @Test - public void nonExistentArrayField() { + void nonExistentArrayField() { HashMap payload = new HashMap<>(); assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test - public void nonExistentArrayFieldAsTypeDoesNotMatch() { + void nonExistentArrayFieldAsTypeDoesNotMatch() { HashMap payload = new HashMap<>(); payload.put("a", 5); assertThat(this.fieldProcessor.extract("a[]", payload).getValue()).isEqualTo(ExtractedField.ABSENT); } @Test - public void nonExistentFieldBeneathAnArray() { + void nonExistentFieldBeneathAnArray() { HashMap payload = new HashMap<>(); HashMap alpha = new HashMap<>(); alpha.put("b", Arrays.asList(new HashMap())); @@ -208,7 +208,7 @@ public void nonExistentFieldBeneathAnArray() { } @Test - public void removeTopLevelMapEntry() { + void removeTopLevelMapEntry() { Map payload = new HashMap<>(); payload.put("a", "alpha"); this.fieldProcessor.remove("a", payload); @@ -216,7 +216,7 @@ public void removeTopLevelMapEntry() { } @Test - public void mapWithEntriesIsNotRemovedWhenNotAlsoRemovingDescendants() { + void mapWithEntriesIsNotRemovedWhenNotAlsoRemovingDescendants() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -226,7 +226,7 @@ public void mapWithEntriesIsNotRemovedWhenNotAlsoRemovingDescendants() { } @Test - public void removeSubsectionRemovesMapWithEntries() { + void removeSubsectionRemovesMapWithEntries() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -236,7 +236,7 @@ public void removeSubsectionRemovesMapWithEntries() { } @Test - public void removeNestedMapEntry() { + void removeNestedMapEntry() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -247,7 +247,7 @@ public void removeNestedMapEntry() { @SuppressWarnings("unchecked") @Test - public void removeItemsInArray() throws IOException { + void removeItemsInArray() throws IOException { Map payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); this.fieldProcessor.remove("a[].b", payload); @@ -256,7 +256,7 @@ public void removeItemsInArray() throws IOException { @SuppressWarnings("unchecked") @Test - public void removeItemsInNestedArray() throws IOException { + void removeItemsInNestedArray() throws IOException { Map payload = new ObjectMapper().readValue("{\"a\": [[{\"id\":1},{\"id\":2}], [{\"id\":3}]]}", Map.class); this.fieldProcessor.remove("a[][].id", payload); @@ -265,7 +265,7 @@ public void removeItemsInNestedArray() throws IOException { @SuppressWarnings("unchecked") @Test - public void removeDoesNotRemoveArrayWithMapEntries() throws IOException { + void removeDoesNotRemoveArrayWithMapEntries() throws IOException { Map payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); this.fieldProcessor.remove("a[]", payload); @@ -274,7 +274,7 @@ public void removeDoesNotRemoveArrayWithMapEntries() throws IOException { @SuppressWarnings("unchecked") @Test - public void removeDoesNotRemoveArrayWithListEntries() throws IOException { + void removeDoesNotRemoveArrayWithListEntries() throws IOException { Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class); this.fieldProcessor.remove("a[]", payload); assertThat(payload.size()).isEqualTo(1); @@ -282,7 +282,7 @@ public void removeDoesNotRemoveArrayWithListEntries() throws IOException { @SuppressWarnings("unchecked") @Test - public void removeRemovesArrayWithOnlyScalarEntries() throws IOException { + void removeRemovesArrayWithOnlyScalarEntries() throws IOException { Map payload = new ObjectMapper().readValue("{\"a\": [\"bravo\", \"charlie\"]}", Map.class); this.fieldProcessor.remove("a", payload); assertThat(payload.size()).isEqualTo(0); @@ -290,7 +290,7 @@ public void removeRemovesArrayWithOnlyScalarEntries() throws IOException { @SuppressWarnings("unchecked") @Test - public void removeSubsectionRemovesArrayWithMapEntries() throws IOException { + void removeSubsectionRemovesArrayWithMapEntries() throws IOException { Map payload = new ObjectMapper().readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); this.fieldProcessor.removeSubsection("a[]", payload); @@ -299,14 +299,14 @@ public void removeSubsectionRemovesArrayWithMapEntries() throws IOException { @SuppressWarnings("unchecked") @Test - public void removeSubsectionRemovesArrayWithListEntries() throws IOException { + void removeSubsectionRemovesArrayWithListEntries() throws IOException { Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class); this.fieldProcessor.removeSubsection("a[]", payload); assertThat(payload.size()).isEqualTo(0); } @Test - public void extractNestedEntryWithDotInKeys() { + void extractNestedEntryWithDotInKeys() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a.key", alpha); @@ -316,7 +316,7 @@ public void extractNestedEntryWithDotInKeys() { @SuppressWarnings("unchecked") @Test - public void extractNestedEntriesUsingTopLevelWildcard() { + void extractNestedEntriesUsingTopLevelWildcard() { Map payload = new LinkedHashMap<>(); Map alpha = new LinkedHashMap<>(); payload.put("a", alpha); @@ -330,7 +330,7 @@ public void extractNestedEntriesUsingTopLevelWildcard() { @SuppressWarnings("unchecked") @Test - public void extractNestedEntriesUsingMidLevelWildcard() { + void extractNestedEntriesUsingMidLevelWildcard() { Map payload = new LinkedHashMap<>(); Map alpha = new LinkedHashMap<>(); payload.put("a", alpha); @@ -344,7 +344,7 @@ public void extractNestedEntriesUsingMidLevelWildcard() { @SuppressWarnings("unchecked") @Test - public void extractUsingLeafWildcardMatchingSingleItem() { + void extractUsingLeafWildcardMatchingSingleItem() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -357,7 +357,7 @@ public void extractUsingLeafWildcardMatchingSingleItem() { @SuppressWarnings("unchecked") @Test - public void extractUsingLeafWildcardMatchingMultipleItems() { + void extractUsingLeafWildcardMatchingMultipleItems() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -368,7 +368,7 @@ public void extractUsingLeafWildcardMatchingMultipleItems() { } @Test - public void removeUsingLeafWildcard() { + void removeUsingLeafWildcard() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -379,7 +379,7 @@ public void removeUsingLeafWildcard() { } @Test - public void removeUsingTopLevelWildcard() { + void removeUsingTopLevelWildcard() { Map payload = new HashMap<>(); Map alpha = new HashMap<>(); payload.put("a", alpha); @@ -390,7 +390,7 @@ public void removeUsingTopLevelWildcard() { } @Test - public void removeUsingMidLevelWildcard() { + void removeUsingMidLevelWildcard() { Map payload = new LinkedHashMap<>(); Map alpha = new LinkedHashMap<>(); payload.put("a", alpha); @@ -407,28 +407,28 @@ public void removeUsingMidLevelWildcard() { } @Test - public void hasFieldIsTrueForNonNullFieldInMap() { + void hasFieldIsTrueForNonNullFieldInMap() { Map payload = new HashMap<>(); payload.put("a", "alpha"); assertThat(this.fieldProcessor.hasField("a", payload)).isTrue(); } @Test - public void hasFieldIsTrueForNullFieldInMap() { + void hasFieldIsTrueForNullFieldInMap() { Map payload = new HashMap<>(); payload.put("a", null); assertThat(this.fieldProcessor.hasField("a", payload)).isTrue(); } @Test - public void hasFieldIsFalseForAbsentFieldInMap() { + void hasFieldIsFalseForAbsentFieldInMap() { Map payload = new HashMap<>(); payload.put("a", null); assertThat(this.fieldProcessor.hasField("b", payload)).isFalse(); } @Test - public void hasFieldIsTrueForNeverNullFieldBeneathArray() { + void hasFieldIsTrueForNeverNullFieldBeneathArray() { Map payload = new HashMap<>(); Map nested = new HashMap<>(); nested.put("b", "bravo"); @@ -437,7 +437,7 @@ public void hasFieldIsTrueForNeverNullFieldBeneathArray() { } @Test - public void hasFieldIsTrueForAlwaysNullFieldBeneathArray() { + void hasFieldIsTrueForAlwaysNullFieldBeneathArray() { Map payload = new HashMap<>(); Map nested = new HashMap<>(); nested.put("b", null); @@ -446,7 +446,7 @@ public void hasFieldIsTrueForAlwaysNullFieldBeneathArray() { } @Test - public void hasFieldIsFalseForAlwaysAbsentFieldBeneathArray() { + void hasFieldIsFalseForAlwaysAbsentFieldBeneathArray() { Map payload = new HashMap<>(); Map nested = new HashMap<>(); nested.put("b", "bravo"); @@ -455,7 +455,7 @@ public void hasFieldIsFalseForAlwaysAbsentFieldBeneathArray() { } @Test - public void hasFieldIsFalseForOccasionallyAbsentFieldBeneathArray() { + void hasFieldIsFalseForOccasionallyAbsentFieldBeneathArray() { Map payload = new HashMap<>(); Map nested = new HashMap<>(); nested.put("b", "bravo"); @@ -464,7 +464,7 @@ public void hasFieldIsFalseForOccasionallyAbsentFieldBeneathArray() { } @Test - public void hasFieldIsFalseForOccasionallyNullFieldBeneathArray() { + void hasFieldIsFalseForOccasionallyNullFieldBeneathArray() { Map payload = new HashMap<>(); Map fieldPresent = new HashMap<>(); fieldPresent.put("b", "bravo"); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java index ae6f9e5e8..4c469005b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -19,162 +19,158 @@ import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link JsonFieldTypesDiscoverer}. * * @author Andy Wilkinson */ -public class JsonFieldTypesDiscovererTests { +class JsonFieldTypesDiscovererTests { private final JsonFieldTypesDiscoverer fieldTypeDiscoverer = new JsonFieldTypesDiscoverer(); - @Rule - public ExpectedException thrownException = ExpectedException.none(); - @Test - public void arrayField() throws IOException { + void arrayField() throws IOException { assertThat(discoverFieldTypes("[]")).containsExactly(JsonFieldType.ARRAY); } @Test - public void topLevelArray() throws IOException { + void topLevelArray() throws IOException { assertThat(discoverFieldTypes("[]", "[{\"a\":\"alpha\"}]")).containsExactly(JsonFieldType.ARRAY); } @Test - public void nestedArray() throws IOException { + void nestedArray() throws IOException { assertThat(discoverFieldTypes("a[]", "{\"a\": [{\"b\":\"bravo\"}]}")).containsExactly(JsonFieldType.ARRAY); } @Test - public void arrayNestedBeneathAnArray() throws IOException { + void arrayNestedBeneathAnArray() throws IOException { assertThat(discoverFieldTypes("a[].b[]", "{\"a\": [{\"b\": [ 1, 2 ]}]}")).containsExactly(JsonFieldType.ARRAY); } @Test - public void specificFieldOfObjectInArrayNestedBeneathAnArray() throws IOException { + void specificFieldOfObjectInArrayNestedBeneathAnArray() throws IOException { assertThat(discoverFieldTypes("a[].b[].c", "{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}")) .containsExactly(JsonFieldType.NUMBER); } @Test - public void booleanField() throws IOException { + void booleanField() throws IOException { assertThat(discoverFieldTypes("true")).containsExactly(JsonFieldType.BOOLEAN); } @Test - public void objectField() throws IOException { + void objectField() throws IOException { assertThat(discoverFieldTypes("{}")).containsExactly(JsonFieldType.OBJECT); } @Test - public void nullField() throws IOException { + void nullField() throws IOException { assertThat(discoverFieldTypes("null")).containsExactly(JsonFieldType.NULL); } @Test - public void numberField() throws IOException { + void numberField() throws IOException { assertThat(discoverFieldTypes("1.2345")).containsExactly(JsonFieldType.NUMBER); } @Test - public void stringField() throws IOException { + void stringField() throws IOException { assertThat(discoverFieldTypes("\"Foo\"")).containsExactly(JsonFieldType.STRING); } @Test - public void nestedField() throws IOException { + void nestedField() throws IOException { assertThat(discoverFieldTypes("a.b.c", "{\"a\":{\"b\":{\"c\":{}}}}")).containsExactly(JsonFieldType.OBJECT); } @Test - public void multipleFieldsWithSameType() throws IOException { + void multipleFieldsWithSameType() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}]}")) .containsExactly(JsonFieldType.NUMBER); } @Test - public void multipleFieldsWithDifferentTypes() throws IOException { + void multipleFieldsWithDifferentTypes() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}]}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN); } @Test - public void multipleFieldsWithDifferentTypesAndSometimesAbsent() throws IOException { + void multipleFieldsWithDifferentTypesAndSometimesAbsent() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}, {}]}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL); } @Test - public void multipleFieldsWhenSometimesAbsent() throws IOException { + void multipleFieldsWhenSometimesAbsent() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}, {}]}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.NULL); } @Test - public void multipleFieldsWhenSometimesNull() throws IOException { + void multipleFieldsWhenSometimesNull() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":2}, {\"id\":null}]}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.NULL); } @Test - public void multipleFieldsWithDifferentTypesAndSometimesNull() throws IOException { + void multipleFieldsWithDifferentTypesAndSometimesNull() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":1},{\"id\":true}, {\"id\":null}]}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.BOOLEAN, JsonFieldType.NULL); } @Test - public void multipleFieldsWhenEitherNullOrAbsent() throws IOException { + void multipleFieldsWhenEitherNullOrAbsent() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{},{\"id\":null}]}")) .containsExactlyInAnyOrder(JsonFieldType.NULL); } @Test - public void multipleFieldsThatAreAllNull() throws IOException { + void multipleFieldsThatAreAllNull() throws IOException { assertThat(discoverFieldTypes("a[].id", "{\"a\":[{\"id\":null},{\"id\":null}]}")) .containsExactlyInAnyOrder(JsonFieldType.NULL); } @Test - public void nonExistentSingleFieldProducesFieldDoesNotExistException() throws IOException { - this.thrownException.expect(FieldDoesNotExistException.class); - this.thrownException.expectMessage("The payload does not contain a field with the path 'a.b'"); - discoverFieldTypes("a.b", "{\"a\":{}}"); + void nonExistentSingleFieldProducesFieldDoesNotExistException() { + assertThatExceptionOfType(FieldDoesNotExistException.class) + .isThrownBy(() -> discoverFieldTypes("a.b", "{\"a\":{}}")) + .withMessage("The payload does not contain a field with the path 'a.b'"); } @Test - public void nonExistentMultipleFieldsProducesFieldDoesNotExistException() throws IOException { - this.thrownException.expect(FieldDoesNotExistException.class); - this.thrownException.expectMessage("The payload does not contain a field with the path 'a[].b'"); - discoverFieldTypes("a[].b", "{\"a\":[{\"c\":1},{\"c\":2}]}"); + void nonExistentMultipleFieldsProducesFieldDoesNotExistException() { + assertThatExceptionOfType(FieldDoesNotExistException.class) + .isThrownBy(() -> discoverFieldTypes("a[].b", "{\"a\":[{\"c\":1},{\"c\":2}]}")) + .withMessage("The payload does not contain a field with the path 'a[].b'"); } @Test - public void leafWildcardWithCommonType() throws IOException { + void leafWildcardWithCommonType() throws IOException { assertThat(discoverFieldTypes("a.*", "{\"a\": {\"b\": 5, \"c\": 6}}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER); } @Test - public void leafWildcardWithVaryingType() throws IOException { + void leafWildcardWithVaryingType() throws IOException { assertThat(discoverFieldTypes("a.*", "{\"a\": {\"b\": 5, \"c\": \"six\"}}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING); } @Test - public void intermediateWildcardWithCommonType() throws IOException { + void intermediateWildcardWithCommonType() throws IOException { assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER); } @Test - public void intermediateWildcardWithVaryingType() throws IOException { + void intermediateWildcardWithVaryingType() throws IOException { assertThat(discoverFieldTypes("a.*.d", "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": \"four\"}}}}")) .containsExactlyInAnyOrder(JsonFieldType.NUMBER, JsonFieldType.STRING); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java index 0828262f8..1d2a869d4 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,7 +18,7 @@ import java.util.EnumSet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -27,32 +27,32 @@ * * @author Andy Wilkinson */ -public class JsonFieldTypesTests { +class JsonFieldTypesTests { @Test - public void singleTypeCoalescesToThatType() { + void singleTypeCoalescesToThatType() { assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(false)).isEqualTo(JsonFieldType.NUMBER); } @Test - public void singleTypeCoalescesToThatTypeWhenOptional() { + void singleTypeCoalescesToThatTypeWhenOptional() { assertThat(new JsonFieldTypes(JsonFieldType.NUMBER).coalesce(true)).isEqualTo(JsonFieldType.NUMBER); } @Test - public void multipleTypesCoalescesToVaries() { + void multipleTypesCoalescesToVaries() { assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NUMBER)).coalesce(false)) .isEqualTo(JsonFieldType.VARIES); } @Test - public void nullAndNonNullTypesCoalescesToVaries() { + void nullAndNonNullTypesCoalescesToVaries() { assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(false)) .isEqualTo(JsonFieldType.VARIES); } @Test - public void nullAndNonNullTypesCoalescesToNonNullTypeWhenOptional() { + void nullAndNonNullTypesCoalescesToNonNullTypeWhenOptional() { assertThat(new JsonFieldTypes(EnumSet.of(JsonFieldType.ARRAY, JsonFieldType.NULL)).coalesce(true)) .isEqualTo(JsonFieldType.ARRAY); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java index 7c57c3c19..11b6df5fa 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -19,7 +19,7 @@ import java.util.Arrays; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.payload.PayloadDocumentation.applyPathPrefix; @@ -31,10 +31,10 @@ * * @author Andy Wilkinson */ -public class PayloadDocumentationTests { +class PayloadDocumentationTests { @Test - public void applyPathPrefixAppliesPrefixToDescriptorPaths() { + void applyPathPrefixAppliesPrefixToDescriptorPaths() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo"), fieldWithPath("charlie"))); assertThat(descriptors.size()).isEqualTo(2); @@ -42,21 +42,21 @@ public void applyPathPrefixAppliesPrefixToDescriptorPaths() { } @Test - public void applyPathPrefixCopiesIgnored() { + void applyPathPrefixCopiesIgnored() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").ignored())); assertThat(descriptors.size()).isEqualTo(1); assertThat(descriptors.get(0).isIgnored()).isTrue(); } @Test - public void applyPathPrefixCopiesOptional() { + void applyPathPrefixCopiesOptional() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").optional())); assertThat(descriptors.size()).isEqualTo(1); assertThat(descriptors.get(0).isOptional()).isTrue(); } @Test - public void applyPathPrefixCopiesDescription() { + void applyPathPrefixCopiesDescription() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").description("Some field"))); assertThat(descriptors.size()).isEqualTo(1); @@ -64,7 +64,7 @@ public void applyPathPrefixCopiesDescription() { } @Test - public void applyPathPrefixCopiesType() { + void applyPathPrefixCopiesType() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").type(JsonFieldType.OBJECT))); assertThat(descriptors.size()).isEqualTo(1); @@ -72,7 +72,7 @@ public void applyPathPrefixCopiesType() { } @Test - public void applyPathPrefixCopiesAttributes() { + void applyPathPrefixCopiesAttributes() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").attributes(key("a").value("alpha"), key("b").value("bravo")))); assertThat(descriptors.size()).isEqualTo(1); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java index 114fcfaf8..f9c94dbd9 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,17 +18,14 @@ import java.io.IOException; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestPartBody; import static org.springframework.restdocs.snippet.Attributes.attributes; @@ -39,49 +36,84 @@ * * @author Andy Wilkinson */ -public class RequestBodyPartSnippetTests extends AbstractSnippetTests { +class RequestBodyPartSnippetTests { - public RequestBodyPartSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); + @RenderedSnippetTest + void requestPartWithBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestPartBody("one") + .document(operationBuilder.request("http://localhost").part("one", "some content".getBytes()).build()); + assertThat(snippets.requestPartBody("one")) + .isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("some content")); } - @Test - public void requestPartWithBody() throws IOException { - requestPartBody("one") - .document(this.operationBuilder.request("http://localhost").part("one", "some content".getBytes()).build()); - assertThat(this.generatedSnippets.snippet("request-part-one-body")) - .is(codeBlock(null, "nowrap").withContent("some content")); + @RenderedSnippetTest + void requestPartWithNoBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestPartBody("one").document(operationBuilder.request("http://localhost").part("one", new byte[0]).build()); + assertThat(snippets.requestPartBody("one")) + .isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("")); } - @Test - public void requestPartWithNoBody() throws IOException { - requestPartBody("one") - .document(this.operationBuilder.request("http://localhost").part("one", new byte[0]).build()); - assertThat(this.generatedSnippets.snippet("request-part-one-body")) - .is(codeBlock(null, "nowrap").withContent("")); + @RenderedSnippetTest + void requestPartWithJsonMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + requestPartBody("one").document(operationBuilder.request("http://localhost") + .part("one", "".getBytes()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .build()); + assertThat(snippets.requestPartBody("one")) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("")); + } + + @RenderedSnippetTest + void requestPartWithJsonSubtypeMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + requestPartBody("one").document(operationBuilder.request("http://localhost") + .part("one", "".getBytes()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PROBLEM_JSON_VALUE) + .build()); + assertThat(snippets.requestPartBody("one")) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("")); + } + + @RenderedSnippetTest + void requestPartWithXmlMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + requestPartBody("one").document(operationBuilder.request("http://localhost") + .part("one", "".getBytes()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build()); + assertThat(snippets.requestPartBody("one")) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("xml", "nowrap").content("")); + } + + @RenderedSnippetTest + void requestPartWithXmlSubtypeMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + requestPartBody("one").document(operationBuilder.request("http://localhost") + .part("one", "".getBytes()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML_VALUE) + .build()); + assertThat(snippets.requestPartBody("one")) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("xml", "nowrap").content("")); } - @Test - public void subsectionOfRequestPartBody() throws IOException { - requestPartBody("one", beneathPath("a.b")).document(this.operationBuilder.request("http://localhost") + @RenderedSnippetTest + void subsectionOfRequestPartBody(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + requestPartBody("one", beneathPath("a.b")).document(operationBuilder.request("http://localhost") .part("one", "{\"a\":{\"b\":{\"c\":5}}}".getBytes()) .build()); - assertThat(this.generatedSnippets.snippet("request-part-one-body-beneath-a.b")) - .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); + assertThat(snippets.requestPartBody("one", "beneath-a.b")) + .isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("{\"c\":5}")); } - @Test - public void customSnippetAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-part-body")) - .willReturn(snippetResource("request-part-body-with-language")); - requestPartBody("one", attributes(key("language").value("json"))).document( - this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .part("one", "{\"a\":\"alpha\"}".getBytes()) - .build()); - assertThat(this.generatedSnippets.snippet("request-part-one-body")) - .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-part-body", template = "request-part-body-with-language") + void customSnippetAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestPartBody("one", attributes(key("language").value("json"))) + .document(operationBuilder.request("http://localhost").part("one", "{\"a\":\"alpha\"}".getBytes()).build()); + assertThat(snippets.requestPartBody("one")).isCodeBlock( + (codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java index a35d1af3e..c332fdcc7 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,17 +18,14 @@ import java.io.IOException; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestBody; import static org.springframework.restdocs.snippet.Attributes.attributes; @@ -39,45 +36,74 @@ * * @author Andy Wilkinson */ -public class RequestBodySnippetTests extends AbstractSnippetTests { +class RequestBodySnippetTests { + + @RenderedSnippetTest + void requestWithBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestBody().document(operationBuilder.request("http://localhost").content("some content").build()); + assertThat(snippets.requestBody()) + .isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("some content")); + } + + @RenderedSnippetTest + void requestWithNoBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestBody().document(operationBuilder.request("http://localhost").build()); + assertThat(snippets.requestBody()).isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("")); + } + + @RenderedSnippetTest + void requestWithJsonMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestBody().document(operationBuilder.request("http://localhost") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .build()); + assertThat(snippets.requestBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("")); + } - public RequestBodySnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); + @RenderedSnippetTest + void requestWithJsonSubtypeMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + requestBody().document(operationBuilder.request("http://localhost") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PROBLEM_JSON_VALUE) + .build()); + assertThat(snippets.requestBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("")); } - @Test - public void requestWithBody() throws IOException { - requestBody().document(this.operationBuilder.request("http://localhost").content("some content").build()); - assertThat(this.generatedSnippets.snippet("request-body")) - .is(codeBlock(null, "nowrap").withContent("some content")); + @RenderedSnippetTest + void requestWithXmlMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestBody().document(operationBuilder.request("http://localhost") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build()); + assertThat(snippets.requestBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("xml", "nowrap").content("")); } - @Test - public void requestWithNoBody() throws IOException { - requestBody().document(this.operationBuilder.request("http://localhost").build()); - assertThat(this.generatedSnippets.snippet("request-body")).is(codeBlock(null, "nowrap").withContent("")); + @RenderedSnippetTest + void requestWithXmlSubtypeMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + requestBody().document(operationBuilder.request("http://localhost") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML_VALUE) + .build()); + assertThat(snippets.requestBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("xml", "nowrap").content("")); } - @Test - public void subsectionOfRequestBody() throws IOException { + @RenderedSnippetTest + void subsectionOfRequestBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { requestBody(beneathPath("a.b")) - .document(this.operationBuilder.request("http://localhost").content("{\"a\":{\"b\":{\"c\":5}}}").build()); - assertThat(this.generatedSnippets.snippet("request-body-beneath-a.b")) - .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); + .document(operationBuilder.request("http://localhost").content("{\"a\":{\"b\":{\"c\":5}}}").build()); + assertThat(snippets.requestBody("beneath-a.b")) + .isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("{\"c\":5}")); } - @Test - public void customSnippetAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-body")) - .willReturn(snippetResource("request-body-with-language")); - requestBody(attributes(key("language").value("json"))).document( - this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .content("{\"a\":\"alpha\"}") - .build()); - assertThat(this.generatedSnippets.snippet("request-body")) - .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-body", template = "request-body-with-language") + void customSnippetAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + requestBody(attributes(key("language").value("json"))) + .document(operationBuilder.request("http://localhost").content("{\"a\":\"alpha\"}").build()); + assertThat(snippets.requestBody()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java deleted file mode 100644 index 1eb5a5b9f..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.payload; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; - -/** - * Tests for failures when rendering {@link RequestFieldsSnippet} due to missing or - * undocumented fields. - * - * @author Andy Wilkinson - */ -public class RequestFieldsSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void undocumentedRequestField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5}").build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); - } - - @Test - public void missingRequestField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("{}").build())) - .withMessage("Fields with the following paths were not found in the payload: [a.b]"); - } - - @Test - public void missingOptionalRequestFieldWithNoTypeProvided() { - assertThatExceptionOfType(FieldTypeRequiredException.class).isThrownBy( - () -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").optional())) - .document(this.operationBuilder.request("http://localhost").content("{ }").build())); - } - - @Test - public void undocumentedRequestFieldAndMissingRequestField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("{ \"a\": { \"c\": 5 }}").build())) - .withMessageStartingWith("The following parts of the payload were not documented:") - .withMessageEndingWith("Fields with the following paths were not found in the payload: [a.b]"); - } - - @Test - public void attemptToDocumentFieldsWithNoRequestBody() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Cannot document request fields as the request body is empty"); - } - - @Test - public void fieldWithExplicitTypeThatDoesNotMatchThePayload() { - assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.request("http://localhost").content("{ \"a\": 5 }").build())) - .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); - } - - @Test - public void fieldWithExplicitSpecificTypeThatActuallyVaries() { - assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.request("http://localhost") - .content("[{ \"a\": 5 },{ \"a\": \"b\" }]") - .build())) - .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); - } - - @Test - public void undocumentedXmlRequestField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); - } - - @Test - public void xmlDescendentsAreNotDocumentedByFieldDescriptor() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").type("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); - } - - @Test - public void xmlRequestFieldWithNoType() { - assertThatExceptionOfType(FieldTypeRequiredException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())); - } - - @Test - public void missingXmlRequestField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .content("") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessage("Fields with the following paths were not found in the payload: [a/b]"); - } - - @Test - public void undocumentedXmlRequestFieldAndMissingXmlRequestField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessageStartingWith("The following parts of the payload were not documented:") - .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); - } - - @Test - public void unsupportedContent() { - assertThatExceptionOfType(PayloadHandlingException.class) - .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost") - .content("Some plain text") - .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) - .build())) - .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); - } - - @Test - public void nonOptionalFieldBeneathArrayThatIsSometimesNull() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); - } - - @Test - public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java index 4d8867e34..7c6394d96 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,21 +18,19 @@ import java.io.IOException; import java.util.Arrays; - -import org.junit.Test; +import java.util.Collections; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; @@ -44,343 +42,494 @@ * Tests for {@link RequestFieldsSnippet}. * * @author Andy Wilkinson + * @author Sungjun Lee */ -public class RequestFieldsSnippetTests extends AbstractSnippetTests { - - public RequestFieldsSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +class RequestFieldsSnippetTests { - @Test - public void mapRequestWithFields() throws IOException { + @RenderedSnippetTest + void mapRequestWithFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"), fieldWithPath("a").description("three"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") - .row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } - @Test - public void mapRequestWithNullField() throws IOException { + @RenderedSnippetTest + void mapRequestWithNullField(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": null}}").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); + .document(operationBuilder.request("http://localhost").content("{\"a\": {\"b\": null}}").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); } - @Test - public void entireSubsectionsCanBeDocumented() throws IOException { + @RenderedSnippetTest + void entireSubsectionsCanBeDocumented(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").description("one"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one")); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a`", "`Object`", "one")); } - @Test - public void subsectionOfMapRequest() throws IOException { + @RenderedSnippetTest + void subsectionOfMapRequest(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { requestFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); - assertThat(this.generatedSnippets.snippet("request-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + assertThat(snippets.requestFields("beneath-a")) + .isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one") .row("`c`", "`String`", "two")); } - @Test - public void subsectionOfMapRequestWithCommonPrefix() throws IOException { + @RenderedSnippetTest + void subsectionOfMapRequestWithCommonPrefix(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { requestFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}") .build()); - assertThat(this.generatedSnippets.snippet("request-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); + assertThat(snippets.requestFields("beneath-a")) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); } - @Test - public void arrayRequestWithFields() throws IOException { + @RenderedSnippetTest + void arrayRequestWithFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("[]").description("one"), fieldWithPath("[]a.b").description("two"), fieldWithPath("[]a.c").description("three"), fieldWithPath("[]a").description("four"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`", "one") - .row("`[]a.b`", "`Number`", "two") - .row("`[]a.c`", "`String`", "three") - .row("`[]a`", "`Object`", "four")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`[]`", "`Array`", "one") + .row("`[]a.b`", "`Number`", "two") + .row("`[]a.c`", "`String`", "three") + .row("`[]a`", "`Object`", "four")); } - @Test - public void arrayRequestWithAlwaysNullField() throws IOException { + @RenderedSnippetTest + void arrayRequestWithAlwaysNullField(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); } - @Test - public void subsectionOfArrayRequest() throws IOException { + @RenderedSnippetTest + void subsectionOfArrayRequest(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { requestFields(beneathPath("[].a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("[{\"a\": {\"b\": 5, \"c\": \"charlie\"}}]") .build()); - assertThat(this.generatedSnippets.snippet("request-fields-beneath-[].a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + assertThat(snippets.requestFields("beneath-[].a")) + .isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one") .row("`c`", "`String`", "two")); } - @Test - public void ignoredRequestField() throws IOException { + @RenderedSnippetTest + void ignoredRequestField(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .document(operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } - @Test - public void entireSubsectionCanBeIgnored() throws IOException { + @RenderedSnippetTest + void entireSubsectionCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet( Arrays.asList(subsectionWithPath("a").ignored(), fieldWithPath("c").description("Field c"))) - .document( - this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}, \"c\": 4}").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "Field c")); + .document(operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}, \"c\": 4}").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`c`", "`Number`", "Field c")); } - @Test - public void allUndocumentedRequestFieldsCanBeIgnored() throws IOException { + @RenderedSnippetTest + void allUndocumentedRequestFieldsCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .document(operationBuilder.request("http://localhost").content("{\"a\": 5, \"b\": 4}").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } - @Test - public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException { + @RenderedSnippetTest + void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors(OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) .andWithPrefix("c.", fieldWithPath("d").description("Field d")) - .document(this.operationBuilder.request("http://localhost") - .content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}") - .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b") - .row("`c.d`", "`Number`", "Field d")); + .document( + operationBuilder.request("http://localhost").content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "Field b") + .row("`c.d`", "`Number`", "Field d")); } - @Test - public void missingOptionalRequestField() throws IOException { + @RenderedSnippetTest + void missingOptionalRequestField(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.request("http://localhost").content("{}").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .document(operationBuilder.request("http://localhost").content("{}").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } - @Test - public void missingIgnoredOptionalRequestFieldDoesNotRequireAType() throws IOException { + @RenderedSnippetTest + void missingIgnoredOptionalRequestFieldDoesNotRequireAType(OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional())) - .document(this.operationBuilder.request("http://localhost").content("{}").build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description")); + .document(operationBuilder.request("http://localhost").content("{}").build()); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description")); } - @Test - public void presentOptionalRequestField() throws IOException { + @RenderedSnippetTest + void presentOptionalRequestField(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document( - this.operationBuilder.request("http://localhost").content("{\"a\": { \"b\": \"bravo\"}}").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .document(operationBuilder.request("http://localhost").content("{\"a\": { \"b\": \"bravo\"}}").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } - @Test - public void requestFieldsWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-fields")) - .willReturn(snippetResource("request-fields-with-title")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-fields", template = "request-fields-with-title") + void requestFieldsWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .content("{\"a\": \"foo\"}") - .build()); - assertThat(this.generatedSnippets.requestFields()).contains("Custom title"); + .document(operationBuilder.request("http://localhost").content("{\"a\": \"foo\"}").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withTitleAndHeader("Custom title", "Path", "Type", "Description") + .row("a", "String", "one")); } - @Test - public void requestFieldsWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-fields")) - .willReturn(snippetResource("request-fields-with-extra-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-fields", template = "request-fields-with-extra-column") + void requestFieldsWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").attributes(key("foo").value("alpha")), fieldWithPath("a.c").description("two").attributes(key("foo").value("bravo")), fieldWithPath("a").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha") - .row("a.c", "String", "two", "bravo") - .row("a", "Object", "three", "charlie")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description", "Foo") + .row("a.b", "Number", "one", "alpha") + .row("a.c", "String", "two", "bravo") + .row("a", "Object", "three", "charlie")); } - @Test - public void fieldWithExplictExactlyMatchingType() throws IOException { + @RenderedSnippetTest + void fieldWithExplicitExactlyMatchingType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); + .document(operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); } - @Test - public void fieldWithExplictVariesType() throws IOException { + @RenderedSnippetTest + void fieldWithExplicitVariesType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); + .document(operationBuilder.request("http://localhost").content("{\"a\": 5 }").build()); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); } - @Test - public void applicationXmlRequestFields() throws IOException { - xmlRequestFields(MediaType.APPLICATION_XML); + @RenderedSnippetTest + void applicationXmlRequestFields(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + xmlRequestFields(MediaType.APPLICATION_XML, operationBuilder, snippets); } - @Test - public void textXmlRequestFields() throws IOException { - xmlRequestFields(MediaType.TEXT_XML); + @RenderedSnippetTest + void textXmlRequestFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + xmlRequestFields(MediaType.TEXT_XML, operationBuilder, snippets); } - @Test - public void customXmlRequestFields() throws IOException { - xmlRequestFields(MediaType.parseMediaType("application/vnd.com.example+xml")); + @RenderedSnippetTest + void customXmlRequestFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + xmlRequestFields(MediaType.parseMediaType("application/vnd.com.example+xml"), operationBuilder, snippets); } - private void xmlRequestFields(MediaType contentType) throws IOException { + private void xmlRequestFields(MediaType contentType, OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one").type("b"), fieldWithPath("a/c").description("two").type("c"), fieldWithPath("a").description("three").type("a"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("5charlie") .header(HttpHeaders.CONTENT_TYPE, contentType.toString()) .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one") - .row("`a/c`", "`c`", "two") - .row("`a`", "`a`", "three")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a/b`", "`b`", "one") + .row("`a/c`", "`c`", "two") + .row("`a`", "`a`", "three")); } - @Test - public void entireSubsectionOfXmlPayloadCanBeDocumented() throws IOException { + @RenderedSnippetTest + void entireSubsectionOfXmlPayloadCanBeDocumented(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").description("one").type("a"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("5charlie") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { PayloadDocumentation .requestFields(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two")) .and(fieldWithPath("a").description("three")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") - .row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } - @Test - public void prefixedAdditionalDescriptors() throws IOException { + @RenderedSnippetTest + void prefixedAdditionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { PayloadDocumentation.requestFields(fieldWithPath("a").description("one")) .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one") - .row("`a.b`", "`Number`", "two") - .row("`a.c`", "`String`", "three")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a`", "`Object`", "one") + .row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } - @Test - public void requestWithFieldsWithEscapedContent() throws IOException { + @RenderedSnippetTest + void requestWithFieldsWithEscapedContent(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) - .document(this.operationBuilder.request("http://localhost").content("{\"Foo|Bar\": 5}").build()); - assertThat(this.generatedSnippets.requestFields()).is(tableWithHeader("Path", "Type", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four"))); + .document(operationBuilder.request("http://localhost").content("{\"Foo|Bar\": 5}").build()); + assertThat(snippets.requestFields()).isTable( + (table) -> table.withHeader("Path", "Type", "Description").row("`Foo|Bar`", "`one|two`", "three|four")); } - @Test - public void mapRequestWithVaryingKeysMatchedUsingWildcard() throws IOException { + @RenderedSnippetTest + void mapRequestWithVaryingKeysMatchedUsingWildcard(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet(Arrays.asList(fieldWithPath("things.*.size").description("one"), fieldWithPath("things.*.type").description("two"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"}," + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`things.*.size`", "`String`", "one") - .row("`things.*.type`", "`String`", "two")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`things.*.size`", "`String`", "one") + .row("`things.*.type`", "`String`", "two")); } - @Test - public void requestWithArrayContainingFieldThatIsSometimesNull() throws IOException { + @RenderedSnippetTest + void requestWithArrayContainingFieldThatIsSometimesNull(OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("assets[].name").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"assets\": [" + "{\"name\": \"sample1\"}, " + "{\"name\": null}, " + "{\"name\": \"sample2\"}]}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); + assertThat(snippets.requestFields()).isTable( + (table) -> table.withHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); } - @Test - public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { + @RenderedSnippetTest + void optionalFieldBeneathArrayThatIsSometimesAbsent(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER).optional(), fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") .build()); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a[].b`", "`Number`", "one") - .row("`a[].c`", "`Number`", "two")); + assertThat(snippets.requestFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a[].b`", "`Number`", "one") + .row("`a[].c`", "`Number`", "two")); } - @Test - public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException { + @RenderedSnippetTest + void typeDeterminationDoesNotSetTypeOnDescriptor(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { FieldDescriptor descriptor = fieldWithPath("a.b").description("one"); new RequestFieldsSnippet(Arrays.asList(descriptor)) - .document(this.operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}}").build()); + .document(operationBuilder.request("http://localhost").content("{\"a\": {\"b\": 5}}").build()); assertThat(descriptor.getType()).isNull(); - assertThat(this.generatedSnippets.requestFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one")); - } - - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); + assertThat(snippets.requestFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one")); + } + + @SnippetTest + void undocumentedRequestField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) + .document(operationBuilder.request("http://localhost").content("{\"a\": 5}").build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); + } + + @SnippetTest + void missingRequestField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) + .document(operationBuilder.request("http://localhost").content("{}").build())) + .withMessage("Fields with the following paths were not found in the payload: [a.b]"); + } + + @SnippetTest + void missingOptionalRequestFieldWithNoTypeProvided(OperationBuilder operationBuilder) { + assertThatExceptionOfType(FieldTypeRequiredException.class).isThrownBy( + () -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").optional())) + .document(operationBuilder.request("http://localhost").content("{ }").build())); + } + + @SnippetTest + void undocumentedRequestFieldAndMissingRequestField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) + .document(operationBuilder.request("http://localhost").content("{ \"a\": { \"c\": 5 }}").build())) + .withMessageStartingWith("The following parts of the payload were not documented:") + .withMessageEndingWith("Fields with the following paths were not found in the payload: [a.b]"); + } + + @SnippetTest + void attemptToDocumentFieldsWithNoRequestBody(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(operationBuilder.request("http://localhost").build())) + .withMessage("Cannot document request fields as the request body is empty"); + } + + @SnippetTest + void fieldWithExplicitTypeThatDoesNotMatchThePayload(OperationBuilder operationBuilder) { + assertThatExceptionOfType(FieldTypesDoNotMatchException.class) + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) + .document(operationBuilder.request("http://localhost").content("{ \"a\": 5 }").build())) + .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); + } + + @SnippetTest + void fieldWithExplicitSpecificTypeThatActuallyVaries(OperationBuilder operationBuilder) { + assertThatExceptionOfType(FieldTypesDoNotMatchException.class).isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) + .document(operationBuilder.request("http://localhost").content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build())) + .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); + } + + @SnippetTest + void undocumentedXmlRequestField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) + .document(operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); + } + + @SnippetTest + void xmlDescendentsAreNotDocumentedByFieldDescriptor(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").type("a").description("one"))) + .document(operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); + } + + @SnippetTest + void xmlRequestFieldWithNoType(OperationBuilder operationBuilder) { + assertThatExceptionOfType(FieldTypeRequiredException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())); + } + + @SnippetTest + void missingXmlRequestField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) + .document(operationBuilder.request("http://localhost") + .content("") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage("Fields with the following paths were not found in the payload: [a/b]"); + } + + @SnippetTest + void undocumentedXmlRequestFieldAndMissingXmlRequestField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) + .document(operationBuilder.request("http://localhost") + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:") + .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); + } + + @SnippetTest + void unsupportedContent(OperationBuilder operationBuilder) { + assertThatExceptionOfType(PayloadHandlingException.class) + .isThrownBy(() -> new RequestFieldsSnippet(Collections.emptyList()) + .document(operationBuilder.request("http://localhost") + .content("Some plain text") + .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) + .build())) + .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); + } + + @SnippetTest + void nonOptionalFieldBeneathArrayThatIsSometimesNull(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(operationBuilder.request("http://localhost") + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); + } + + @SnippetTest + void nonOptionalFieldBeneathArrayThatIsSometimesAbsent(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(operationBuilder.request("http://localhost") + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetFailureTests.java deleted file mode 100644 index 52f1cead0..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetFailureTests.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.payload; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; - -/** - * Tests for failures when rendering {@link RequestPartFieldsSnippet} due to missing or - * undocumented fields. - * - * @author Mathieu Pousse - * @author Andy Wilkinson - */ -public class RequestPartFieldsSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void undocumentedRequestPartField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartFieldsSnippet("part", Collections.emptyList()).document( - this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); - } - - @Test - public void missingRequestPartField() { - assertThatExceptionOfType(SnippetException.class).isThrownBy(() -> new RequestPartFieldsSnippet("part", - Arrays.asList(fieldWithPath("b").description("one"))) - .document(this.operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); - } - - @Test - public void missingRequestPart() { - assertThatExceptionOfType(SnippetException.class).isThrownBy( - () -> new RequestPartFieldsSnippet("another", Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.request("http://localhost") - .part("part", "{\"a\": {\"b\": 5}}".getBytes()) - .build())) - .withMessage("A request part named 'another' was not found in the request"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java index 7967bc7d5..f4924d752 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -20,13 +20,15 @@ import java.util.Arrays; import java.util.Collections; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.operation.Operation; -import org.springframework.restdocs.templates.TemplateFormat; +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; @@ -36,86 +38,110 @@ * @author Mathieu Pousse * @author Andy Wilkinson */ -public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { - - public RequestPartFieldsSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +public class RequestPartFieldsSnippetTests { - @Test - public void mapRequestPartFields() throws IOException { + @RenderedSnippetTest + void mapRequestPartFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestPartFieldsSnippet("one", Arrays.asList(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"), fieldWithPath("a").description("three"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); - assertThat(this.generatedSnippets.requestPartFields("one")) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") - .row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); + assertThat(snippets.requestPartFields("one")).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } - @Test - public void mapRequestPartSubsectionFields() throws IOException { + @RenderedSnippetTest + void mapRequestPartSubsectionFields(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestPartFieldsSnippet("one", beneathPath("a"), Arrays.asList(fieldWithPath("b").description("one"), fieldWithPath("c").description("two"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); - assertThat(this.generatedSnippets.snippet("request-part-one-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + assertThat(snippets.requestPartFields("one", "beneath-a")) + .isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one") .row("`c`", "`String`", "two")); } - @Test - public void multipleRequestParts() throws IOException { - Operation operation = this.operationBuilder.request("http://localhost") + @RenderedSnippetTest + void multipleRequestParts(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + Operation operation = operationBuilder.request("http://localhost") .part("one", "{}".getBytes()) .and() .part("two", "{}".getBytes()) .build(); new RequestPartFieldsSnippet("one", Collections.emptyList()).document(operation); new RequestPartFieldsSnippet("two", Collections.emptyList()).document(operation); - assertThat(this.generatedSnippets.requestPartFields("one")).isNotNull(); - assertThat(this.generatedSnippets.requestPartFields("two")).isNotNull(); + assertThat(snippets.requestPartFields("one")).isNotNull(); + assertThat(snippets.requestPartFields("two")).isNotNull(); } - @Test - public void allUndocumentedRequestPartFieldsCanBeIgnored() throws IOException { - new RequestPartFieldsSnippet("one", Arrays.asList(fieldWithPath("b").description("Field b")), true) - .document(this.operationBuilder.request("http://localhost") - .part("one", "{\"a\": 5, \"b\": 4}".getBytes()) - .build()); - assertThat(this.generatedSnippets.requestPartFields("one")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + @RenderedSnippetTest + void allUndocumentedRequestPartFieldsCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new RequestPartFieldsSnippet("one", Arrays.asList(fieldWithPath("b").description("Field b")), true).document( + operationBuilder.request("http://localhost").part("one", "{\"a\": 5, \"b\": 4}".getBytes()).build()); + assertThat(snippets.requestPartFields("one")) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { PayloadDocumentation .requestPartFields("one", fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two")) .and(fieldWithPath("a").description("three")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); - assertThat(this.generatedSnippets.requestPartFields("one")) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Number`", "one") - .row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); + assertThat(snippets.requestPartFields("one")).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one") + .row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } - @Test - public void prefixedAdditionalDescriptors() throws IOException { + @RenderedSnippetTest + void prefixedAdditionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { PayloadDocumentation.requestPartFields("one", fieldWithPath("a").description("one")) .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); - assertThat(this.generatedSnippets.requestPartFields("one")) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one") - .row("`a.b`", "`Number`", "two") - .row("`a.c`", "`String`", "three")); + assertThat(snippets.requestPartFields("one")).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a`", "`Object`", "one") + .row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); + } + + @SnippetTest + void undocumentedRequestPartField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestPartFieldsSnippet("part", Collections.emptyList()) + .document(operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); + } + + @SnippetTest + void missingRequestPartField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestPartFieldsSnippet("part", Arrays.asList(fieldWithPath("b").description("one"))) + .document(operationBuilder.request("http://localhost").part("part", "{\"a\": 5}".getBytes()).build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); + } + + @SnippetTest + void missingRequestPart(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class).isThrownBy( + () -> new RequestPartFieldsSnippet("another", Arrays.asList(fieldWithPath("a.b").description("one"))) + .document(operationBuilder.request("http://localhost") + .part("part", "{\"a\": {\"b\": 5}}".getBytes()) + .build())) + .withMessage("A request part named 'another' was not found in the request"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java index 7ba494bb0..74c659954 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,17 +18,14 @@ import java.io.IOException; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseBody; import static org.springframework.restdocs.snippet.Attributes.attributes; @@ -39,45 +36,72 @@ * * @author Andy Wilkinson */ -public class ResponseBodySnippetTests extends AbstractSnippetTests { +class ResponseBodySnippetTests { + + @RenderedSnippetTest + void responseWithBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new ResponseBodySnippet().document(operationBuilder.response().content("some content").build()); + assertThat(snippets.responseBody()) + .isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("some content")); + } + + @RenderedSnippetTest + void responseWithNoBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new ResponseBodySnippet().document(operationBuilder.response().build()); + assertThat(snippets.responseBody()).isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("")); + } + + @RenderedSnippetTest + void responseWithJsonMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new ResponseBodySnippet().document( + operationBuilder.response().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build()); + assertThat(snippets.responseBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("")); + } - public ResponseBodySnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); + @RenderedSnippetTest + void responseWithJsonSubtypeMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseBodySnippet().document(operationBuilder.response() + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PROBLEM_JSON_VALUE) + .build()); + assertThat(snippets.responseBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("")); } - @Test - public void responseWithBody() throws IOException { - new ResponseBodySnippet().document(this.operationBuilder.response().content("some content").build()); - assertThat(this.generatedSnippets.snippet("response-body")) - .is(codeBlock(null, "nowrap").withContent("some content")); + @RenderedSnippetTest + void responseWithXmlMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new ResponseBodySnippet().document( + operationBuilder.response().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE).build()); + assertThat(snippets.responseBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("xml", "nowrap").content("")); } - @Test - public void responseWithNoBody() throws IOException { - new ResponseBodySnippet().document(this.operationBuilder.response().build()); - assertThat(this.generatedSnippets.snippet("response-body")).is(codeBlock(null, "nowrap").withContent("")); + @RenderedSnippetTest + void responseWithXmlSubtypeMediaType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseBodySnippet().document(operationBuilder.response() + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML_VALUE) + .build()); + assertThat(snippets.responseBody()) + .isCodeBlock((codeBlock) -> codeBlock.withLanguageAndOptions("xml", "nowrap").content("")); } - @Test - public void subsectionOfResponseBody() throws IOException { + @RenderedSnippetTest + void subsectionOfResponseBody(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { responseBody(beneathPath("a.b")) - .document(this.operationBuilder.response().content("{\"a\":{\"b\":{\"c\":5}}}").build()); - assertThat(this.generatedSnippets.snippet("response-body-beneath-a.b")) - .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); + .document(operationBuilder.response().content("{\"a\":{\"b\":{\"c\":5}}}").build()); + assertThat(snippets.responseBody("beneath-a.b")) + .isCodeBlock((codeBlock) -> codeBlock.withOptions("nowrap").content("{\"c\":5}")); } - @Test - public void customSnippetAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-body")) - .willReturn(snippetResource("response-body-with-language")); - new ResponseBodySnippet(attributes(key("language").value("json"))).document( - this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response() - .content("{\"a\":\"alpha\"}") - .build()); - assertThat(this.generatedSnippets.snippet("response-body")) - .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "response-body", template = "response-body-with-language") + void customSnippetAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new ResponseBodySnippet(attributes(key("language").value("json"))) + .document(operationBuilder.response().content("{\"a\":\"alpha\"}").build()); + assertThat(snippets.responseBody()).isCodeBlock( + (codeBlock) -> codeBlock.withLanguageAndOptions("json", "nowrap").content("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java deleted file mode 100644 index 3e41d9fec..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.payload; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; - -/** - * Tests for failures when rendering {@link ResponseFieldsSnippet} due to missing or - * undocumented fields. - * - * @author Andy Wilkinson - */ -public class ResponseFieldsSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void attemptToDocumentFieldsWithNoResponseBody() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.build())) - .withMessage("Cannot document response fields as the response body is empty"); - } - - @Test - public void fieldWithExplicitTypeThatDoesNotMatchThePayload() { - assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.response().content("{ \"a\": 5 }}").build())) - .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); - } - - @Test - public void fieldWithExplicitSpecificTypeThatActuallyVaries() { - assertThatExceptionOfType(FieldTypesDoNotMatchException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) - .document(this.operationBuilder.response().content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build())) - .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); - } - - @Test - public void undocumentedXmlResponseField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.response() - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessageStartingWith("The following parts of the payload were not documented:"); - } - - @Test - public void missingXmlAttribute() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), - fieldWithPath("a/@id").description("two").type("c"))) - .document(this.operationBuilder.response() - .content("foo") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessage("Fields with the following paths were not found in the payload: [a/@id]"); - } - - @Test - public void documentedXmlAttributesAreRemoved() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy( - () -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/@id").description("one").type("a"))) - .document(this.operationBuilder.response() - .content("bar") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessage(String.format("The following parts of the payload were not documented:%nbar%n")); - } - - @Test - public void xmlResponseFieldWithNoType() { - assertThatExceptionOfType(FieldTypeRequiredException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) - .document(this.operationBuilder.response() - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())); - } - - @Test - public void missingXmlResponseField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) - .document(this.operationBuilder.response() - .content("") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessage("Fields with the following paths were not found in the payload: [a/b]"); - } - - @Test - public void undocumentedXmlResponseFieldAndMissingXmlResponseField() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) - .document(this.operationBuilder.response() - .content("5") - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) - .build())) - .withMessageStartingWith("The following parts of the payload were not documented:") - .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); - } - - @Test - public void unsupportedContent() { - assertThatExceptionOfType(PayloadHandlingException.class) - .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) - .document(this.operationBuilder.response() - .content("Some plain text") - .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) - .build())) - .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); - } - - @Test - public void nonOptionalFieldBeneathArrayThatIsSometimesNull() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response() - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); - } - - @Test - public void nonOptionalFieldBeneathArrayThatIsSometimesAbsent() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new ResponseFieldsSnippet( - Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), - fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response() - .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") - .build())) - .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java index d8545ea48..e238851b9 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,21 +18,19 @@ import java.io.IOException; import java.util.Arrays; - -import org.junit.Test; +import java.util.Collections; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; @@ -43,356 +41,488 @@ * Tests for {@link ResponseFieldsSnippet}. * * @author Andy Wilkinson + * @author Sungjun Lee */ -public class ResponseFieldsSnippetTests extends AbstractSnippetTests { - - public ResponseFieldsSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +public class ResponseFieldsSnippetTests { - @Test - public void mapResponseWithFields() throws IOException { + @RenderedSnippetTest + void mapResponseWithFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), fieldWithPath("assets").description("three"), fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"), fieldWithPath("assets[].name").description("six"))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}") .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one") - .row("`date`", "`String`", "two") - .row("`assets`", "`Array`", "three") - .row("`assets[]`", "`Array`", "four") - .row("`assets[].id`", "`Number`", "five") - .row("`assets[].name`", "`String`", "six")); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`id`", "`Number`", "one") + .row("`date`", "`String`", "two") + .row("`assets`", "`Array`", "three") + .row("`assets[]`", "`Array`", "four") + .row("`assets[].id`", "`Number`", "five") + .row("`assets[].name`", "`String`", "six")); } - @Test - public void mapResponseWithNullField() throws IOException { + @RenderedSnippetTest + void mapResponseWithNullField(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": null}}").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); + .document(operationBuilder.response().content("{\"a\": {\"b\": null}}").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a.b`", "`Null`", "one")); } - @Test - public void subsectionOfMapResponse() throws IOException { + @RenderedSnippetTest + void subsectionOfMapResponse(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { responseFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); - assertThat(this.generatedSnippets.snippet("response-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "one") + .document(operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + assertThat(snippets.responseFields("beneath-a")) + .isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one") .row("`c`", "`String`", "two")); } - @Test - public void subsectionOfMapResponseBeneathAnArray() throws IOException { + @RenderedSnippetTest + void subsectionOfMapResponseBeneathAnArray(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { responseFields(beneathPath("a.b.[]"), fieldWithPath("c").description("one"), fieldWithPath("d.[].e").description("two")) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("{\"a\": {\"b\": [{\"c\": 1, \"d\": [{\"e\": 5}]}, {\"c\": 3, \"d\": [{\"e\": 4}]}]}}") .build()); - assertThat(this.generatedSnippets.snippet("response-fields-beneath-a.b.[]")) - .is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", "one") + assertThat(snippets.responseFields("beneath-a.b.[]")) + .isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`c`", "`Number`", "one") .row("`d.[].e`", "`Number`", "two")); } - @Test - public void subsectionOfMapResponseWithCommonsPrefix() throws IOException { + @RenderedSnippetTest + void subsectionOfMapResponseWithCommonsPrefix(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { responseFields(beneathPath("a")).andWithPrefix("b.", fieldWithPath("c").description("two")) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build()); - assertThat(this.generatedSnippets.snippet("response-fields-beneath-a")) - .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); + .document(operationBuilder.response().content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build()); + assertThat(snippets.responseFields("beneath-a")) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`b.c`", "`String`", "two")); } - @Test - public void arrayResponseWithFields() throws IOException { + @RenderedSnippetTest + void arrayResponseWithFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"), fieldWithPath("[]a.c").description("two"), fieldWithPath("[]a").description("three"))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Number`", "one") - .row("`[]a.c`", "`String`", "two") - .row("`[]a`", "`Object`", "three")); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`[]a.b`", "`Number`", "one") + .row("`[]a.c`", "`String`", "two") + .row("`[]a`", "`Object`", "three")); } - @Test - public void arrayResponseWithAlwaysNullField() throws IOException { - new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"))) - .document(this.operationBuilder.response() - .content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]") - .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); + @RenderedSnippetTest + void arrayResponseWithAlwaysNullField(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"))).document( + operationBuilder.response().content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`[]a.b`", "`Null`", "one")); } - @Test - public void arrayResponse() throws IOException { + @RenderedSnippetTest + void arrayResponse(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"))) - .document(this.operationBuilder.response().content("[\"a\", \"b\", \"c\"]").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`", "one")); + .document(operationBuilder.response().content("[\"a\", \"b\", \"c\"]").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`[]`", "`Array`", "one")); } - @Test - public void ignoredResponseField() throws IOException { + @RenderedSnippetTest + void ignoredResponseField(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) - .document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .document(operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } - @Test - public void allUndocumentedFieldsCanBeIgnored() throws IOException { + @RenderedSnippetTest + void allUndocumentedFieldsCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) - .document(this.operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); + .document(operationBuilder.response().content("{\"a\": 5, \"b\": 4}").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b")); } - @Test - public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException { + @RenderedSnippetTest + void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors(OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true) .andWithPrefix("c.", fieldWithPath("d").description("Field d")) - .document(this.operationBuilder.response().content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", "Field b") - .row("`c.d`", "`Number`", "Field d")); + .document(operationBuilder.response().content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "Field b") + .row("`c.d`", "`Number`", "Field d")); } - @Test - public void responseFieldsWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-fields")) - .willReturn(snippetResource("response-fields-with-title")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "response-fields", template = "response-fields-with-title") + void responseFieldsWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one")), attributes(key("title").value("Custom title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response() - .content("{\"a\": \"foo\"}") - .build()); - assertThat(this.generatedSnippets.responseFields()).contains("Custom title"); + .document(operationBuilder.response().content("{\"a\": \"foo\"}").build()); + assertThat(snippets.responseFields()).contains("Custom title"); } - @Test - public void missingOptionalResponseField() throws IOException { + @RenderedSnippetTest + void missingOptionalResponseField(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.response().content("{}").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .document(operationBuilder.response().content("{}").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } - @Test - public void missingIgnoredOptionalResponseFieldDoesNotRequireAType() throws IOException { + @RenderedSnippetTest + void missingIgnoredOptionalResponseFieldDoesNotRequireAType(OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one").ignored().optional())) - .document(this.operationBuilder.response().content("{}").build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description")); + .document(operationBuilder.response().content("{}").build()); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description")); } - @Test - public void presentOptionalResponseField() throws IOException { + @RenderedSnippetTest + void presentOptionalResponseField(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.response().content("{\"a\": { \"b\": \"bravo\"}}").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); + .document(operationBuilder.response().content("{\"a\": { \"b\": \"bravo\"}}").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a.b`", "`String`", "one")); } - @Test - public void responseFieldsWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("response-fields")) - .willReturn(snippetResource("response-fields-with-extra-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "response-fields", template = "response-fields-with-extra-column") + void responseFieldsWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a.b").description("one").attributes(key("foo").value("alpha")), fieldWithPath("a.c").description("two").attributes(key("foo").value("bravo")), fieldWithPath("a").description("three").attributes(key("foo").value("charlie")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .response() - .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") - .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description", "Foo").row("a.b", "Number", "one", "alpha") - .row("a.c", "String", "two", "bravo") - .row("a", "Object", "three", "charlie")); + .document(operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description", "Foo") + .row("a.b", "Number", "one", "alpha") + .row("a.c", "String", "two", "bravo") + .row("a", "Object", "three", "charlie")); } - @Test - public void fieldWithExplictExactlyMatchingType() throws IOException { + @RenderedSnippetTest + void fieldWithExplicitExactlyMatchingType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response().content("{\"a\": 5 }").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); + .document(operationBuilder.response().content("{\"a\": 5 }").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a`", "`Number`", "one")); } - @Test - public void fieldWithExplictVariesType() throws IOException { + @RenderedSnippetTest + void fieldWithExplicitVariesType(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) - .document(this.operationBuilder.response().content("{\"a\": 5 }").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); + .document(operationBuilder.response().content("{\"a\": 5 }").build()); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a`", "`Varies`", "one")); } - @Test - public void applicationXmlResponseFields() throws IOException { - xmlResponseFields(MediaType.APPLICATION_XML); + @RenderedSnippetTest + void applicationXmlResponseFields(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + xmlResponseFields(MediaType.APPLICATION_XML, operationBuilder, snippets); } - @Test - public void textXmlResponseFields() throws IOException { - xmlResponseFields(MediaType.TEXT_XML); + @RenderedSnippetTest + void textXmlResponseFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + xmlResponseFields(MediaType.TEXT_XML, operationBuilder, snippets); } - @Test - public void customXmlResponseFields() throws IOException { - xmlResponseFields(MediaType.parseMediaType("application/vnd.com.example+xml")); + @RenderedSnippetTest + void customXmlResponseFields(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + xmlResponseFields(MediaType.parseMediaType("application/vnd.com.example+xml"), operationBuilder, snippets); } - private void xmlResponseFields(MediaType contentType) throws IOException { + private void xmlResponseFields(MediaType contentType, OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one").type("b"), fieldWithPath("a/c").description("two").type("c"), fieldWithPath("a").description("three").type("a"))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("5charlie") .header(HttpHeaders.CONTENT_TYPE, contentType.toString()) .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one") - .row("`a/c`", "`c`", "two") - .row("`a`", "`a`", "three")); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a/b`", "`b`", "one") + .row("`a/c`", "`c`", "two") + .row("`a`", "`a`", "three")); } - @Test - public void xmlAttribute() throws IOException { + @RenderedSnippetTest + void xmlAttribute(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), fieldWithPath("a/@id").description("two").type("c"))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a`", "`b`", "one") + .row("`a/@id`", "`c`", "two")); } - @Test - public void missingOptionalXmlAttribute() throws IOException { + @RenderedSnippetTest + void missingOptionalXmlAttribute(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), fieldWithPath("a/@id").description("two").type("c").optional())) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a`", "`b`", "one") + .row("`a/@id`", "`c`", "two")); } - @Test - public void undocumentedAttributeDoesNotCauseFailure() throws IOException { + @RenderedSnippetTest + void undocumentedAttributeDoesNotCauseFailure(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("a"))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("bar") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { PayloadDocumentation .responseFields(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), fieldWithPath("assets").description("three")) .and(fieldWithPath("assets[]").description("four"), fieldWithPath("assets[].id").description("five"), fieldWithPath("assets[].name").description("six")) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}") .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one") - .row("`date`", "`String`", "two") - .row("`assets`", "`Array`", "three") - .row("`assets[]`", "`Array`", "four") - .row("`assets[].id`", "`Number`", "five") - .row("`assets[].name`", "`String`", "six")); - } - - @Test - public void prefixedAdditionalDescriptors() throws IOException { + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`id`", "`Number`", "one") + .row("`date`", "`String`", "two") + .row("`assets`", "`Array`", "three") + .row("`assets[]`", "`Array`", "four") + .row("`assets[].id`", "`Number`", "five") + .row("`assets[].name`", "`String`", "six")); + } + + @RenderedSnippetTest + void prefixedAdditionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { PayloadDocumentation.responseFields(fieldWithPath("a").description("one")) .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) - .document(this.operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", "one") - .row("`a.b`", "`Number`", "two") - .row("`a.c`", "`String`", "three")); + .document(operationBuilder.response().content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a`", "`Object`", "one") + .row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } - @Test - public void responseWithFieldsWithEscapedContent() throws IOException { + @RenderedSnippetTest + void responseWithFieldsWithEscapedContent(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) - .document(this.operationBuilder.response().content("{\"Foo|Bar\": 5}").build()); - assertThat(this.generatedSnippets.responseFields()).is(tableWithHeader("Path", "Type", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), escapeIfNecessary("three|four"))); + .document(operationBuilder.response().content("{\"Foo|Bar\": 5}").build()); + assertThat(snippets.responseFields()).isTable( + (table) -> table.withHeader("Path", "Type", "Description").row("`Foo|Bar`", "`one|two`", "three|four")); } - @Test - public void mapResponseWithVaryingKeysMatchedUsingWildcard() throws IOException { + @RenderedSnippetTest + void mapResponseWithVaryingKeysMatchedUsingWildcard(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("things.*.size").description("one"), fieldWithPath("things.*.type").description("two"))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("{\"things\": {\"12abf\": {\"type\":" + "\"Whale\", \"size\": \"HUGE\"}," + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`things.*.size`", "`String`", "one") - .row("`things.*.type`", "`String`", "two")); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`things.*.size`", "`String`", "one") + .row("`things.*.type`", "`String`", "two")); } - @Test - public void responseWithArrayContainingFieldThatIsSometimesNull() throws IOException { + @RenderedSnippetTest + void responseWithArrayContainingFieldThatIsSometimesNull(OperationBuilder operationBuilder, + AssertableSnippets snippets) throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("assets[].name").description("one").type(JsonFieldType.STRING).optional())) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("{\"assets\": [" + "{\"name\": \"sample1\"}, " + "{\"name\": null}, " + "{\"name\": \"sample2\"}]}") .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); + assertThat(snippets.responseFields()).isTable( + (table) -> table.withHeader("Path", "Type", "Description").row("`assets[].name`", "`String`", "one")); } - @Test - public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { + @RenderedSnippetTest + void optionalFieldBeneathArrayThatIsSometimesAbsent(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER).optional(), fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) - .document(this.operationBuilder.response() + .document(operationBuilder.response() .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") .build()); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`a[].b`", "`Number`", "one") - .row("`a[].c`", "`Number`", "two")); + assertThat(snippets.responseFields()).isTable((table) -> table.withHeader("Path", "Type", "Description") + .row("`a[].b`", "`Number`", "one") + .row("`a[].c`", "`Number`", "two")); } - @Test - public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException { + @RenderedSnippetTest + void typeDeterminationDoesNotSetTypeOnDescriptor(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { FieldDescriptor descriptor = fieldWithPath("id").description("one"); new ResponseFieldsSnippet(Arrays.asList(descriptor)) - .document(this.operationBuilder.response().content("{\"id\": 67}").build()); + .document(operationBuilder.response().content("{\"id\": 67}").build()); assertThat(descriptor.getType()).isNull(); - assertThat(this.generatedSnippets.responseFields()) - .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", "one")); - } - - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); + assertThat(snippets.responseFields()) + .isTable((table) -> table.withHeader("Path", "Type", "Description").row("`id`", "`Number`", "one")); + } + + @SnippetTest + void attemptToDocumentFieldsWithNoResponseBody(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(operationBuilder.build())) + .withMessage("Cannot document response fields as the response body is empty"); + } + + @SnippetTest + void fieldWithExplicitTypeThatDoesNotMatchThePayload(OperationBuilder operationBuilder) { + assertThatExceptionOfType(FieldTypesDoNotMatchException.class) + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a").description("one").type(JsonFieldType.OBJECT))) + .document(operationBuilder.response().content("{ \"a\": 5 }}").build())) + .withMessage("The documented type of the field 'a' is Object but the actual type is Number"); + } + + @SnippetTest + void fieldWithExplicitSpecificTypeThatActuallyVaries(OperationBuilder operationBuilder) { + assertThatExceptionOfType(FieldTypesDoNotMatchException.class) + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("[].a").description("one").type(JsonFieldType.OBJECT))) + .document(operationBuilder.response().content("[{ \"a\": 5 },{ \"a\": \"b\" }]").build())) + .withMessage("The documented type of the field '[].a' is Object but the actual type is Varies"); + } + + @SnippetTest + void undocumentedXmlResponseField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) + .document(operationBuilder.response() + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:"); + } + + @SnippetTest + void missingXmlAttribute(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one").type("b"), + fieldWithPath("a/@id").description("two").type("c"))) + .document(operationBuilder.response() + .content("foo") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage("Fields with the following paths were not found in the payload: [a/@id]"); + } + + @SnippetTest + void documentedXmlAttributesAreRemoved(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy( + () -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/@id").description("one").type("a"))) + .document(operationBuilder.response() + .content("bar") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage(String.format("The following parts of the payload were not documented:%nbar%n")); + } + + @SnippetTest + void xmlResponseFieldWithNoType(OperationBuilder operationBuilder) { + assertThatExceptionOfType(FieldTypeRequiredException.class) + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").description("one"))) + .document(operationBuilder.response() + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())); + } + + @SnippetTest + void missingXmlResponseField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a/b").description("one"), fieldWithPath("a").description("one"))) + .document(operationBuilder.response() + .content("") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessage("Fields with the following paths were not found in the payload: [a/b]"); + } + + @SnippetTest + void undocumentedXmlResponseFieldAndMissingXmlResponseField(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a/b").description("one"))) + .document(operationBuilder.response() + .content("5") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) + .build())) + .withMessageStartingWith("The following parts of the payload were not documented:") + .withMessageEndingWith("Fields with the following paths were not found in the payload: [a/b]"); + } + + @SnippetTest + void unsupportedContent(OperationBuilder operationBuilder) { + assertThatExceptionOfType(PayloadHandlingException.class) + .isThrownBy(() -> new ResponseFieldsSnippet(Collections.emptyList()) + .document(operationBuilder.response() + .content("Some plain text") + .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE) + .build())) + .withMessage("Cannot handle text/plain content as it could not be parsed as JSON or XML"); + } + + @SnippetTest + void nonOptionalFieldBeneathArrayThatIsSometimesNull(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(operationBuilder.response() + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"b\": null, \"c\": 2}," + " {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); + } + + @SnippetTest + void nonOptionalFieldBeneathArrayThatIsSometimesAbsent(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new ResponseFieldsSnippet( + Arrays.asList(fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER), + fieldWithPath("a[].c").description("two").type(JsonFieldType.NUMBER))) + .document(operationBuilder.response() + .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") + .build())) + .withMessageStartingWith("Fields with the following paths were not found in the payload: [a[].b]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java index 24b1f8b21..6b98dac40 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -20,11 +20,10 @@ import java.util.Collections; import java.util.List; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; @@ -35,9 +34,6 @@ */ public class XmlContentHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void topLevelElementCanBeDocumented() { List descriptors = Arrays.asList(fieldWithPath("a").type("a").description("description")); @@ -84,8 +80,8 @@ public void multipleElementsCanBeInAscendingOrderDocumented() { @Test public void failsFastWithNonXmlContent() { - this.thrown.expect(PayloadHandlingException.class); - createHandler("non-XML content", Collections.emptyList()); + assertThatExceptionOfType(PayloadHandlingException.class) + .isThrownBy(() -> createHandler("non-XML content", Collections.emptyList())); } private XmlContentHandler createHandler(String xml, List descriptors) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/FormParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/FormParametersSnippetTests.java new file mode 100644 index 000000000..0cf383690 --- /dev/null +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/FormParametersSnippetTests.java @@ -0,0 +1,188 @@ +/* + * Copyright 2014-2025 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.restdocs.request; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; + +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.snippet.Attributes.attributes; +import static org.springframework.restdocs.snippet.Attributes.key; + +/** + * Tests for {@link FormParametersSnippet}. + * + * @author Andy Wilkinson + */ +class FormParametersSnippetTests { + + @RenderedSnippetTest + void formParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new FormParametersSnippet( + Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void formParameterWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new FormParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost").content("a=").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one")); + } + + @RenderedSnippetTest + void ignoredFormParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new FormParametersSnippet( + Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`b`", "two")); + } + + @RenderedSnippetTest + void allUndocumentedFormParametersCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new FormParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`b`", "two")); + } + + @RenderedSnippetTest + void missingOptionalFormParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new FormParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), + parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost").content("b=bravo").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void presentOptionalFormParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new FormParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) + .document(operationBuilder.request("http://localhost").content("a=alpha").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one")); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "form-parameters", template = "form-parameters-with-title") + void formParametersWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new FormParametersSnippet( + Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), + parameterWithName("b").description("two").attributes(key("foo").value("bravo"))), + attributes(key("title").value("The title"))) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo").build()); + assertThat(snippets.formParameters()).contains("The title"); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "form-parameters", template = "form-parameters-with-extra-column") + void formParametersWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new FormParametersSnippet( + Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), + parameterWithName("b").description("two").attributes(key("foo").value("bravo")))) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo").build()); + assertThat(snippets.formParameters()).isTable((table) -> table.withHeader("Parameter", "Description", "Foo") + .row("a", "one", "alpha") + .row("b", "two", "bravo")); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "form-parameters", template = "form-parameters-with-optional-column") + void formParametersWithOptionalColumn(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new FormParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), + parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Optional", "Description") + .row("a", "true", "one") + .row("b", "false", "two")); + } + + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + RequestDocumentation.formParameters(parameterWithName("a").description("one")) + .and(parameterWithName("b").description("two")) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void additionalDescriptorsWithRelaxedFormParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + RequestDocumentation.relaxedFormParameters(parameterWithName("a").description("one")) + .and(parameterWithName("b").description("two")) + .document(operationBuilder.request("http://localhost").content("a=alpha&b=bravo&c=undocumented").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void formParametersWithEscapedContent(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + RequestDocumentation.formParameters(parameterWithName("Foo|Bar").description("one|two")) + .document(operationBuilder.request("http://localhost").content("Foo%7CBar=baz").build()); + assertThat(snippets.formParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`Foo|Bar`", "one|two")); + } + + @SnippetTest + void undocumentedParameter(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new FormParametersSnippet(Collections.emptyList()) + .document(operationBuilder.request("http://localhost").content("a=alpha").build())) + .withMessage("Form parameters with the following names were not documented: [a]"); + } + + @SnippetTest + void missingParameter(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new FormParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost").build())) + .withMessage("Form parameters with the following names were not found in the request: [a]"); + } + + @SnippetTest + void undocumentedAndMissingParameters(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new FormParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost").content("b=bravo").build())) + .withMessage("Form parameters with the following names were not documented: [b]. Form parameters" + + " with the following names were not found in the request: [a]"); + } + +} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java deleted file mode 100644 index b8c7d3747..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.request; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.restdocs.generate.RestDocumentationGenerator; -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; - -/** - * Tests for failures when rendering {@link PathParametersSnippet} due to missing or - * undocumented path parameters. - * - * @author Andy Wilkinson - */ -public class PathParametersSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void undocumentedPathParameter() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new PathParametersSnippet(Collections.emptyList()).document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/") - .build())) - .withMessage("Path parameters with the following names were not documented: [a]"); - } - - @Test - public void missingPathParameter() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/") - .build())) - .withMessage("Path parameters with the following names were not found in the request: [a]"); - } - - @Test - public void undocumentedAndMissingPathParameters() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{b}") - .build())) - .withMessage("Path parameters with the following names were not documented: [b]. Path parameters with the" - + " following names were not found in the request: [a]"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java index 6a0009a16..d178bde51 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,20 +18,20 @@ import java.io.IOException; import java.util.Arrays; +import java.util.Collections; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.generate.RestDocumentationGenerator; -import org.springframework.restdocs.templates.TemplateEngine; +import org.springframework.restdocs.snippet.SnippetException; import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; @@ -41,164 +41,192 @@ * * @author Andy Wilkinson */ -public class PathParametersSnippetTests extends AbstractSnippetTests { - - public PathParametersSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +class PathParametersSnippetTests { - @Test - public void pathParameters() throws IOException { + @RenderedSnippetTest + void pathParameters(OperationBuilder operationBuilder, AssertableSnippets snippets, TemplateFormat templateFormat) + throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); + assertThat(snippets.pathParameters()) + .isTable((table) -> table.withTitleAndHeader(getTitle(templateFormat), "Parameter", "Description") + .row("`a`", "one") + .row("`b`", "two")); } - @Test - public void ignoredPathParameter() throws IOException { + @RenderedSnippetTest + void ignoredPathParameter(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))) - .document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two")); + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); + assertThat(snippets.pathParameters()) + .isTable((table) -> table.withTitleAndHeader(getTitle(templateFormat), "Parameter", "Description") + .row("`b`", "two")); } - @Test - public void allUndocumentedPathParametersCanBeIgnored() throws IOException { + @RenderedSnippetTest + void allUndocumentedPathParametersCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { new PathParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true).document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", "two")); + operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build()); + assertThat(snippets.pathParameters()) + .isTable((table) -> table.withTitleAndHeader(getTitle(templateFormat), "Parameter", "Description") + .row("`b`", "two")); } - @Test - public void missingOptionalPathParameter() throws IOException { + @RenderedSnippetTest + void missingOptionalPathParameter(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two").optional())) - .document(this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}") - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one") + .document( + operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build()); + assertThat(snippets.pathParameters()) + .isTable((table) -> table.withTitleAndHeader(getTitle(templateFormat, "/{a}"), "Parameter", "Description") + .row("`a`", "one") .row("`b`", "two")); } - @Test - public void presentOptionalPathParameter() throws IOException { - new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) - .document(this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}") - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description").row("`a`", "one")); + @RenderedSnippetTest + void presentOptionalPathParameter(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { + new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())).document( + operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build()); + assertThat(snippets.pathParameters()) + .isTable((table) -> table.withTitleAndHeader(getTitle(templateFormat, "/{a}"), "Parameter", "Description") + .row("`a`", "one")); } - @Test - public void pathParametersWithQueryString() throws IOException { + @RenderedSnippetTest + void pathParametersWithQueryString(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document(this.operationBuilder + .document(operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo=bar") .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + assertThat(snippets.pathParameters()) + .isTable((table) -> table.withTitleAndHeader(getTitle(templateFormat), "Parameter", "Description") + .row("`a`", "one") + .row("`b`", "two")); } - @Test - public void pathParametersWithQueryStringWithParameters() throws IOException { + @RenderedSnippetTest + void pathParametersWithQueryStringWithParameters(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document(this.operationBuilder + .document(operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo={c}") .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + assertThat(snippets.pathParameters()) + .isTable((table) -> table.withTitleAndHeader(getTitle(templateFormat), "Parameter", "Description") + .row("`a`", "one") + .row("`b`", "two")); } - @Test - public void pathParametersWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("path-parameters")) - .willReturn(snippetResource("path-parameters-with-title")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "path-parameters", template = "path-parameters-with-title") + void pathParametersWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), parameterWithName("b").description("two").attributes(key("foo").value("bravo"))), attributes(key("title").value("The title"))) - .document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); - assertThat(this.generatedSnippets.pathParameters()).contains("The title"); + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); + assertThat(snippets.pathParameters()).contains("The title"); } - @Test - public void pathParametersWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("path-parameters")) - .willReturn(snippetResource("path-parameters-with-extra-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "path-parameters", template = "path-parameters-with-extra-column") + void pathParametersWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), parameterWithName("b").description("two").attributes(key("foo").value("bravo")))) - .document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); + assertThat(snippets.pathParameters()).isTable((table) -> table.withHeader("Parameter", "Description", "Foo") + .row("a", "one", "alpha") + .row("b", "two", "bravo")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { RequestDocumentation.pathParameters(parameterWithName("a").description("one")) .and(parameterWithName("b").description("two")) - .document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`a`", "one").row("`b`", "two")); + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") + .build()); + assertThat(snippets.pathParameters()).isTable( + (table) -> table.withTitleAndHeader(getTitle(templateFormat, "/{a}/{b}"), "Parameter", "Description") + .row("`a`", "one") + .row("`b`", "two")); } - @Test - public void additionalDescriptorsWithRelaxedRequestParameters() throws IOException { + @RenderedSnippetTest + void additionalDescriptorsWithRelaxedRequestParameters(OperationBuilder operationBuilder, + AssertableSnippets snippets, TemplateFormat templateFormat) throws IOException { RequestDocumentation.relaxedPathParameters(parameterWithName("a").description("one")) .and(parameterWithName("b").description("two")) - .document(this.operationBuilder - .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}/{c}") + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}/{c}") .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("/{a}/{b}/{c}"), "Parameter", "Description").row("`a`", "one") - .row("`b`", "two")); + assertThat(snippets.pathParameters()).isTable((table) -> table + .withTitleAndHeader(getTitle(templateFormat, "/{a}/{b}/{c}"), "Parameter", "Description") + .row("`a`", "one") + .row("`b`", "two")); } - @Test - public void pathParametersWithEscapedContent() throws IOException { + @RenderedSnippetTest + void pathParametersWithEscapedContent(OperationBuilder operationBuilder, AssertableSnippets snippets, + TemplateFormat templateFormat) throws IOException { RequestDocumentation.pathParameters(parameterWithName("Foo|Bar").description("one|two")) - .document( - this.operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{Foo|Bar}") - .build()); - assertThat(this.generatedSnippets.pathParameters()) - .is(tableWithTitleAndHeader(getTitle("{Foo|Bar}"), "Parameter", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{Foo|Bar}") + .build()); + assertThat(snippets.pathParameters()).isTable( + (table) -> table.withTitleAndHeader(getTitle(templateFormat, "{Foo|Bar}"), "Parameter", "Description") + .row("`Foo|Bar`", "one|two")); } - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); + @SnippetTest + void undocumentedPathParameter(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new PathParametersSnippet(Collections.emptyList()) + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/") + .build())) + .withMessage("Path parameters with the following names were not documented: [a]"); + } + + @SnippetTest + void missingPathParameter(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/") + .build())) + .withMessage("Path parameters with the following names were not found in the request: [a]"); + } + + @SnippetTest + void undocumentedAndMissingPathParameters(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{b}") + .build())) + .withMessage("Path parameters with the following names were not documented: [b]. Path parameters with the" + + " following names were not found in the request: [a]"); } - private String getTitle() { - return getTitle("/{a}/{b}"); + private String getTitle(TemplateFormat templateFormat) { + return getTitle(templateFormat, "/{a}/{b}"); } - private String getTitle(String title) { - if (this.templateFormat.getId().equals(TemplateFormats.asciidoctor().getId())) { + private String getTitle(TemplateFormat templateFormat, String title) { + if (templateFormat.getId().equals(TemplateFormats.asciidoctor().getId())) { return "+" + title + "+"; } return "`" + title + "`"; diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/QueryParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/QueryParametersSnippetTests.java new file mode 100644 index 000000000..8084a2382 --- /dev/null +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/QueryParametersSnippetTests.java @@ -0,0 +1,188 @@ +/* + * Copyright 2014-2025 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.restdocs.request; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; + +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.snippet.Attributes.attributes; +import static org.springframework.restdocs.snippet.Attributes.key; + +/** + * Tests for {@link QueryParametersSnippet}. + * + * @author Andy Wilkinson + */ +class QueryParametersSnippetTests { + + @RenderedSnippetTest + void queryParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new QueryParametersSnippet( + Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void queryParameterWithNoValue(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new QueryParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost?a").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one")); + } + + @RenderedSnippetTest + void ignoredQueryParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + new QueryParametersSnippet( + Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`b`", "two")); + } + + @RenderedSnippetTest + void allUndocumentedQueryParametersCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new QueryParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`b`", "two")); + } + + @RenderedSnippetTest + void missingOptionalQueryParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new QueryParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), + parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost?b=bravo").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void presentOptionalQueryParameter(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new QueryParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) + .document(operationBuilder.request("http://localhost?a=alpha").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one")); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "query-parameters", template = "query-parameters-with-title") + void queryParametersWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new QueryParametersSnippet( + Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), + parameterWithName("b").description("two").attributes(key("foo").value("bravo"))), + attributes(key("title").value("The title"))) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo").build()); + assertThat(snippets.queryParameters()).contains("The title"); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "query-parameters", template = "query-parameters-with-extra-column") + void queryParametersWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new QueryParametersSnippet( + Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), + parameterWithName("b").description("two").attributes(key("foo").value("bravo")))) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo").build()); + assertThat(snippets.queryParameters()).isTable((table) -> table.withHeader("Parameter", "Description", "Foo") + .row("a", "one", "alpha") + .row("b", "two", "bravo")); + } + + @RenderedSnippetTest + @SnippetTemplate(snippet = "query-parameters", template = "query-parameters-with-optional-column") + void queryParametersWithOptionalColumn(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + new QueryParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), + parameterWithName("b").description("two"))) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Optional", "Description") + .row("a", "true", "one") + .row("b", "false", "two")); + } + + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { + RequestDocumentation.queryParameters(parameterWithName("a").description("one")) + .and(parameterWithName("b").description("two")) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void additionalDescriptorsWithRelaxedQueryParameters(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + RequestDocumentation.relaxedQueryParameters(parameterWithName("a").description("one")) + .and(parameterWithName("b").description("two")) + .document(operationBuilder.request("http://localhost?a=alpha&b=bravo&c=undocumented").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); + } + + @RenderedSnippetTest + void queryParametersWithEscapedContent(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { + RequestDocumentation.queryParameters(parameterWithName("Foo|Bar").description("one|two")) + .document(operationBuilder.request("http://localhost?Foo%7CBar=baz").build()); + assertThat(snippets.queryParameters()) + .isTable((table) -> table.withHeader("Parameter", "Description").row("`Foo|Bar`", "one|two")); + } + + @SnippetTest + void undocumentedParameter(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new QueryParametersSnippet(Collections.emptyList()) + .document(operationBuilder.request("http://localhost?a=alpha").build())) + .withMessage("Query parameters with the following names were not documented: [a]"); + } + + @SnippetTest + void missingParameter(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new QueryParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost").build())) + .withMessage("Query parameters with the following names were not found in the request: [a]"); + } + + @SnippetTest + void undocumentedAndMissingParameters(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new QueryParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost?b=bravo").build())) + .withMessage("Query parameters with the following names were not documented: [b]. Query parameters" + + " with the following names were not found in the request: [a]"); + } + +} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java deleted file mode 100644 index 5834ad2df..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.request; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; - -/** - * Tests for failures when rendering {@link RequestParametersSnippet} due to missing or - * undocumented request parameters. - * - * @author Andy Wilkinson - */ -public class RequestParametersSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void undocumentedParameter() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestParametersSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost").param("a", "alpha").build())) - .withMessage("Request parameters with the following names were not documented: [a]"); - } - - @Test - public void missingParameter() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Request parameters with the following names were not found in the request: [a]"); - } - - @Test - public void undocumentedAndMissingParameters() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").param("b", "bravo").build())) - .withMessage("Request parameters with the following names were not documented: [b]. Request parameters" - + " with the following names were not found in the request: [a]"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java deleted file mode 100644 index 75677dd85..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.request; - -import java.io.IOException; -import java.util.Arrays; - -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.snippet.Attributes.attributes; -import static org.springframework.restdocs.snippet.Attributes.key; - -/** - * Tests for {@link RequestParametersSnippet}. - * - * @author Andy Wilkinson - */ -public class RequestParametersSnippetTests extends AbstractSnippetTests { - - public RequestParametersSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } - - @Test - public void requestParameters() throws IOException { - new RequestParametersSnippet( - Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))) - .document( - this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); - } - - @Test - public void requestParameterWithNoValue() throws IOException { - new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").param("a").build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); - } - - @Test - public void ignoredRequestParameter() throws IOException { - new RequestParametersSnippet( - Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))) - .document( - this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); - } - - @Test - public void allUndocumentedRequestParametersCanBeIgnored() throws IOException { - new RequestParametersSnippet(Arrays.asList(parameterWithName("b").description("two")), true).document( - this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); - } - - @Test - public void missingOptionalRequestParameter() throws IOException { - new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), - parameterWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").param("b", "bravo").build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); - } - - @Test - public void presentOptionalRequestParameter() throws IOException { - new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional())) - .document(this.operationBuilder.request("http://localhost").param("a", "one").build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); - } - - @Test - public void requestParametersWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parameters")) - .willReturn(snippetResource("request-parameters-with-title")); - new RequestParametersSnippet( - Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), - parameterWithName("b").description("two").attributes(key("foo").value("bravo"))), - attributes(key("title").value("The title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.requestParameters()).contains("The title"); - } - - @Test - public void requestParametersWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parameters")) - .willReturn(snippetResource("request-parameters-with-extra-column")); - new RequestParametersSnippet( - Arrays.asList(parameterWithName("a").description("one").attributes(key("foo").value("alpha")), - parameterWithName("b").description("two").attributes(key("foo").value("bravo")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); - } - - @Test - public void requestParametersWithOptionalColumn() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parameters")) - .willReturn(snippetResource("request-parameters-with-optional-column")); - new RequestParametersSnippet(Arrays.asList(parameterWithName("a").description("one").optional(), - parameterWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") - .param("a", "alpha") - .param("b", "bravo") - .build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Optional", "Description").row("a", "true", "one") - .row("b", "false", "two")); - } - - @Test - public void additionalDescriptors() throws IOException { - RequestDocumentation.requestParameters(parameterWithName("a").description("one")) - .and(parameterWithName("b").description("two")) - .document( - this.operationBuilder.request("http://localhost").param("a", "bravo").param("b", "bravo").build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); - } - - @Test - public void additionalDescriptorsWithRelaxedRequestParameters() throws IOException { - RequestDocumentation.relaxedRequestParameters(parameterWithName("a").description("one")) - .and(parameterWithName("b").description("two")) - .document(this.operationBuilder.request("http://localhost") - .param("a", "bravo") - .param("b", "bravo") - .param("c", "undocumented") - .build()); - assertThat(this.generatedSnippets.requestParameters()) - .is(tableWithHeader("Parameter", "Description").row("`a`", "one").row("`b`", "two")); - } - - @Test - public void requestParametersWithEscapedContent() throws IOException { - RequestDocumentation.requestParameters(parameterWithName("Foo|Bar").description("one|two")) - .document(this.operationBuilder.request("http://localhost").param("Foo|Bar", "baz").build()); - assertThat(this.generatedSnippets.requestParameters()).is(tableWithHeader("Parameter", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); - } - - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java deleted file mode 100644 index e8ad15874..000000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.request; - -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.OperationBuilder; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.springframework.restdocs.request.RequestDocumentation.partWithName; - -/** - * Tests for failures when rendering {@link RequestPartsSnippet} due to missing or - * undocumented request parts. - * - * @author Andy Wilkinson - */ -public class RequestPartsSnippetFailureTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Test - public void undocumentedPart() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartsSnippet(Collections.emptyList()) - .document(this.operationBuilder.request("http://localhost").part("a", "alpha".getBytes()).build())) - .withMessage("Request parts with the following names were not documented: [a]"); - } - - @Test - public void missingPart() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").build())) - .withMessage("Request parts with the following names were not found in the request: [a]"); - } - - @Test - public void undocumentedAndMissingParts() { - assertThatExceptionOfType(SnippetException.class) - .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) - .document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build())) - .withMessage("Request parts with the following names were not documented: [b]. Request parts with the" - + " following names were not found in the request: [a]"); - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java index 51c3fbb0d..9dcc12f9f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,19 +18,17 @@ import java.io.IOException; import java.util.Arrays; +import java.util.Collections; -import org.junit.Test; - -import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.snippet.SnippetException; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTemplate; +import org.springframework.restdocs.testfixtures.jupiter.SnippetTest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; @@ -40,145 +38,157 @@ * * @author Andy Wilkinson */ -public class RequestPartsSnippetTests extends AbstractSnippetTests { - - public RequestPartsSnippetTests(String name, TemplateFormat templateFormat) { - super(name, templateFormat); - } +class RequestPartsSnippetTests { - @Test - public void requestParts() throws IOException { + @RenderedSnippetTest + void requestParts(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one"), partWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()) .and() .part("b", "bravo".getBytes()) .build()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); + assertThat(snippets.requestParts()) + .isTable((table) -> table.withHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); } - @Test - public void ignoredRequestPart() throws IOException { + @RenderedSnippetTest + void ignoredRequestPart(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestPartsSnippet(Arrays.asList(partWithName("a").ignored(), partWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()) .and() .part("b", "bravo".getBytes()) .build()); - assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`b`", "two")); + assertThat(snippets.requestParts()) + .isTable((table) -> table.withHeader("Part", "Description").row("`b`", "two")); } - @Test - public void allUndocumentedRequestPartsCanBeIgnored() throws IOException { + @RenderedSnippetTest + void allUndocumentedRequestPartsCanBeIgnored(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestPartsSnippet(Arrays.asList(partWithName("b").description("two")), true) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()) .and() .part("b", "bravo".getBytes()) .build()); - assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`b`", "two")); + assertThat(snippets.requestParts()) + .isTable((table) -> table.withHeader("Part", "Description").row("`b`", "two")); } - @Test - public void missingOptionalRequestPart() throws IOException { + @RenderedSnippetTest + void missingOptionalRequestPart(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two"))) - .document(this.operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); + .document(operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build()); + assertThat(snippets.requestParts()) + .isTable((table) -> table.withHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); } - @Test - public void presentOptionalRequestPart() throws IOException { + @RenderedSnippetTest + void presentOptionalRequestPart(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one").optional())) - .document(this.operationBuilder.request("http://localhost").part("a", "one".getBytes()).build()); - assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description").row("`a`", "one")); + .document(operationBuilder.request("http://localhost").part("a", "one".getBytes()).build()); + assertThat(snippets.requestParts()) + .isTable((table) -> table.withHeader("Part", "Description").row("`a`", "one")); } - @Test - public void requestPartsWithCustomAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parts")) - .willReturn(snippetResource("request-parts-with-title")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-parts", template = "request-parts-with-title") + void requestPartsWithCustomAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").attributes(key("foo").value("alpha")), partWithName("b").description("two").attributes(key("foo").value("bravo"))), attributes(key("title").value("The title"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("a", "alpha".getBytes()) .and() .part("b", "bravo".getBytes()) .build()); - assertThat(this.generatedSnippets.requestParts()).contains("The title"); + assertThat(snippets.requestParts()).contains("The title"); } - @Test - public void requestPartsWithCustomDescriptorAttributes() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parts")) - .willReturn(snippetResource("request-parts-with-extra-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-parts", template = "request-parts-with-extra-column") + void requestPartsWithCustomDescriptorAttributes(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").attributes(key("foo").value("alpha")), partWithName("b").description("two").attributes(key("foo").value("bravo")))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("a", "alpha".getBytes()) .and() .part("b", "bravo".getBytes()) .build()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description", "Foo").row("a", "one", "alpha").row("b", "two", "bravo")); + assertThat(snippets.requestParts()).isTable((table) -> table.withHeader("Part", "Description", "Foo") + .row("a", "one", "alpha") + .row("b", "two", "bravo")); } - @Test - public void requestPartsWithOptionalColumn() throws IOException { - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("request-parts")) - .willReturn(snippetResource("request-parts-with-optional-column")); + @RenderedSnippetTest + @SnippetTemplate(snippet = "request-parts", template = "request-parts-with-optional-column") + void requestPartsWithOptionalColumn(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two"))) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) - .request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("a", "alpha".getBytes()) .and() .part("b", "bravo".getBytes()) .build()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Optional", "Description").row("a", "true", "one").row("b", "false", "two")); + assertThat(snippets.requestParts()).isTable((table) -> table.withHeader("Part", "Optional", "Description") + .row("a", "true", "one") + .row("b", "false", "two")); } - @Test - public void additionalDescriptors() throws IOException { + @RenderedSnippetTest + void additionalDescriptors(OperationBuilder operationBuilder, AssertableSnippets snippets) throws IOException { RequestDocumentation.requestParts(partWithName("a").description("one")) .and(partWithName("b").description("two")) - .document(this.operationBuilder.request("http://localhost") + .document(operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()) .and() .part("b", "bravo".getBytes()) .build()); - assertThat(this.generatedSnippets.requestParts()) - .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); + assertThat(snippets.requestParts()) + .isTable((table) -> table.withHeader("Part", "Description").row("`a`", "one").row("`b`", "two")); } - @Test - public void requestPartsWithEscapedContent() throws IOException { + @RenderedSnippetTest + void requestPartsWithEscapedContent(OperationBuilder operationBuilder, AssertableSnippets snippets) + throws IOException { RequestDocumentation.requestParts(partWithName("Foo|Bar").description("one|two")) - .document(this.operationBuilder.request("http://localhost").part("Foo|Bar", "baz".getBytes()).build()); - assertThat(this.generatedSnippets.requestParts()).is(tableWithHeader("Part", "Description") - .row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); + .document(operationBuilder.request("http://localhost").part("Foo|Bar", "baz".getBytes()).build()); + assertThat(snippets.requestParts()) + .isTable((table) -> table.withHeader("Part", "Description").row("`Foo|Bar`", "one|two")); + } + + @SnippetTest + void undocumentedPart(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestPartsSnippet(Collections.emptyList()) + .document(operationBuilder.request("http://localhost").part("a", "alpha".getBytes()).build())) + .withMessage("Request parts with the following names were not documented: [a]"); + } + + @SnippetTest + void missingPart(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost").build())) + .withMessage("Request parts with the following names were not found in the request: [a]"); } - private String escapeIfNecessary(String input) { - if (this.templateFormat.getId().equals(TemplateFormats.markdown().getId())) { - return input; - } - return input.replace("|", "\\|"); + @SnippetTest + void undocumentedAndMissingParts(OperationBuilder operationBuilder) { + assertThatExceptionOfType(SnippetException.class) + .isThrownBy(() -> new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"))) + .document(operationBuilder.request("http://localhost").part("b", "bravo".getBytes()).build())) + .withMessage("Request parts with the following names were not documented: [b]. Request parts with the" + + " following names were not found in the request: [a]"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java index ab592d380..22b285c30 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,7 +16,7 @@ package org.springframework.restdocs.snippet; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.ManualRestDocumentation; import org.springframework.restdocs.RestDocumentationContext; @@ -30,82 +30,82 @@ * @author Andy Wilkinson * */ -public class RestDocumentationContextPlaceholderResolverTests { +class RestDocumentationContextPlaceholderResolverTests { @Test - public void kebabCaseMethodName() { + void kebabCaseMethodName() { assertThat(createResolver("dashSeparatedMethodName").resolvePlaceholder("method-name")) .isEqualTo("dash-separated-method-name"); } @Test - public void kebabCaseMethodNameWithUpperCaseOpeningSection() { + void kebabCaseMethodNameWithUpperCaseOpeningSection() { assertThat(createResolver("URIDashSeparatedMethodName").resolvePlaceholder("method-name")) .isEqualTo("uri-dash-separated-method-name"); } @Test - public void kebabCaseMethodNameWithUpperCaseMidSection() { + void kebabCaseMethodNameWithUpperCaseMidSection() { assertThat(createResolver("dashSeparatedMethodNameWithURIInIt").resolvePlaceholder("method-name")) .isEqualTo("dash-separated-method-name-with-uri-in-it"); } @Test - public void kebabCaseMethodNameWithUpperCaseEndSection() { + void kebabCaseMethodNameWithUpperCaseEndSection() { assertThat(createResolver("dashSeparatedMethodNameWithURI").resolvePlaceholder("method-name")) .isEqualTo("dash-separated-method-name-with-uri"); } @Test - public void snakeCaseMethodName() { + void snakeCaseMethodName() { assertThat(createResolver("underscoreSeparatedMethodName").resolvePlaceholder("method_name")) .isEqualTo("underscore_separated_method_name"); } @Test - public void snakeCaseMethodNameWithUpperCaseOpeningSection() { + void snakeCaseMethodNameWithUpperCaseOpeningSection() { assertThat(createResolver("URIUnderscoreSeparatedMethodName").resolvePlaceholder("method_name")) .isEqualTo("uri_underscore_separated_method_name"); } @Test - public void snakeCaseMethodNameWithUpperCaseMidSection() { + void snakeCaseMethodNameWithUpperCaseMidSection() { assertThat(createResolver("underscoreSeparatedMethodNameWithURIInIt").resolvePlaceholder("method_name")) .isEqualTo("underscore_separated_method_name_with_uri_in_it"); } @Test - public void snakeCaseMethodNameWithUpperCaseEndSection() { + void snakeCaseMethodNameWithUpperCaseEndSection() { assertThat(createResolver("underscoreSeparatedMethodNameWithURI").resolvePlaceholder("method_name")) .isEqualTo("underscore_separated_method_name_with_uri"); } @Test - public void camelCaseMethodName() { + void camelCaseMethodName() { assertThat(createResolver("camelCaseMethodName").resolvePlaceholder("methodName")) .isEqualTo("camelCaseMethodName"); } @Test - public void kebabCaseClassName() { + void kebabCaseClassName() { assertThat(createResolver().resolvePlaceholder("class-name")) .isEqualTo("rest-documentation-context-placeholder-resolver-tests"); } @Test - public void snakeCaseClassName() { + void snakeCaseClassName() { assertThat(createResolver().resolvePlaceholder("class_name")) .isEqualTo("rest_documentation_context_placeholder_resolver_tests"); } @Test - public void camelCaseClassName() { + void camelCaseClassName() { assertThat(createResolver().resolvePlaceholder("ClassName")) .isEqualTo("RestDocumentationContextPlaceholderResolverTests"); } @Test - public void stepCount() { + void stepCount() { assertThat(createResolver("stepCount").resolvePlaceholder("step")).isEqualTo("1"); } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java index e4f600bef..0df5118d1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -21,9 +21,8 @@ import java.io.IOException; import java.io.Writer; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.restdocs.ManualRestDocumentation; import org.springframework.restdocs.RestDocumentationContext; @@ -40,10 +39,10 @@ * * @author Andy Wilkinson */ -public class StandardWriterResolverTests { +class StandardWriterResolverTests { - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); + @TempDir + File temp; private final PlaceholderResolverFactory placeholderResolverFactory = mock(PlaceholderResolverFactory.class); @@ -51,21 +50,21 @@ public class StandardWriterResolverTests { TemplateFormats.asciidoctor()); @Test - public void absoluteInput() { + void absoluteInput() { String absolutePath = new File("foo").getAbsolutePath(); assertThat(this.resolver.resolveFile(absolutePath, "bar.txt", createContext(absolutePath))) .isEqualTo(new File(absolutePath, "bar.txt")); } @Test - public void configuredOutputAndRelativeInput() { + void configuredOutputAndRelativeInput() { File outputDir = new File("foo").getAbsoluteFile(); assertThat(this.resolver.resolveFile("bar", "baz.txt", createContext(outputDir.getAbsolutePath()))) .isEqualTo(new File(outputDir, "bar/baz.txt")); } @Test - public void configuredOutputAndAbsoluteInput() { + void configuredOutputAndAbsoluteInput() { File outputDir = new File("foo").getAbsoluteFile(); String absolutePath = new File("bar").getAbsolutePath(); assertThat(this.resolver.resolveFile(absolutePath, "baz.txt", createContext(outputDir.getAbsolutePath()))) @@ -73,25 +72,27 @@ public void configuredOutputAndAbsoluteInput() { } @Test - public void placeholdersAreResolvedInOperationName() throws IOException { - File outputDirectory = this.temp.newFolder(); + void placeholdersAreResolvedInOperationName() throws IOException { + File outputDirectory = this.temp; RestDocumentationContext context = createContext(outputDirectory.getAbsolutePath()); PlaceholderResolver resolver = mock(PlaceholderResolver.class); given(resolver.resolvePlaceholder("a")).willReturn("alpha"); given(this.placeholderResolverFactory.create(context)).willReturn(resolver); - Writer writer = this.resolver.resolve("{a}", "bravo", context); - assertSnippetLocation(writer, new File(outputDirectory, "alpha/bravo.adoc")); + try (Writer writer = this.resolver.resolve("{a}", "bravo", context)) { + assertSnippetLocation(writer, new File(outputDirectory, "alpha/bravo.adoc")); + } } @Test - public void placeholdersAreResolvedInSnippetName() throws IOException { - File outputDirectory = this.temp.newFolder(); + void placeholdersAreResolvedInSnippetName() throws IOException { + File outputDirectory = this.temp; RestDocumentationContext context = createContext(outputDirectory.getAbsolutePath()); PlaceholderResolver resolver = mock(PlaceholderResolver.class); given(resolver.resolvePlaceholder("b")).willReturn("bravo"); given(this.placeholderResolverFactory.create(context)).willReturn(resolver); - Writer writer = this.resolver.resolve("alpha", "{b}", context); - assertSnippetLocation(writer, new File(outputDirectory, "alpha/bravo.adoc")); + try (Writer writer = this.resolver.resolve("alpha", "{b}", context)) { + assertSnippetLocation(writer, new File(outputDirectory, "alpha/bravo.adoc")); + } } private RestDocumentationContext createContext(String outputDir) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java index 8892891af..724e68a5d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2025 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. @@ -21,13 +21,12 @@ import java.util.HashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.operation.Operation; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.testfixtures.GeneratedSnippets; -import org.springframework.restdocs.testfixtures.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.AssertableSnippets; +import org.springframework.restdocs.testfixtures.jupiter.OperationBuilder; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest; import static org.assertj.core.api.Assertions.assertThat; @@ -36,16 +35,10 @@ * * @author Andy Wilkinson */ -public class TemplatedSnippetTests { - - @Rule - public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor()); - - @Rule - public GeneratedSnippets snippets = new GeneratedSnippets(TemplateFormats.asciidoctor()); +class TemplatedSnippetTests { @Test - public void attributesAreCopied() { + void attributesAreCopied() { Map attributes = new HashMap<>(); attributes.put("a", "alpha"); TemplatedSnippet snippet = new TestTemplatedSnippet(attributes); @@ -55,22 +48,23 @@ public void attributesAreCopied() { } @Test - public void nullAttributesAreTolerated() { + void nullAttributesAreTolerated() { assertThat(new TestTemplatedSnippet(null).getAttributes()).isNotNull(); assertThat(new TestTemplatedSnippet(null).getAttributes()).isEmpty(); } @Test - public void snippetName() { + void snippetName() { assertThat(new TestTemplatedSnippet(Collections.emptyMap()).getSnippetName()).isEqualTo("test"); } - @Test - public void multipleSnippetsCanBeProducedFromTheSameTemplate() throws IOException { - new TestTemplatedSnippet("one", "multiple-snippets").document(this.operationBuilder.build()); - new TestTemplatedSnippet("two", "multiple-snippets").document(this.operationBuilder.build()); - assertThat(this.snippets.snippet("multiple-snippets-one")).isNotNull(); - assertThat(this.snippets.snippet("multiple-snippets-two")).isNotNull(); + @RenderedSnippetTest + void multipleSnippetsCanBeProducedFromTheSameTemplate(OperationBuilder operationBuilder, AssertableSnippets snippet) + throws IOException { + new TestTemplatedSnippet("one", "multiple-snippets").document(operationBuilder.build()); + new TestTemplatedSnippet("two", "multiple-snippets").document(operationBuilder.build()); + assertThat(snippet.named("multiple-snippets-one")).exists(); + assertThat(snippet.named("multiple-snippets-two")).exists(); } private static class TestTemplatedSnippet extends TemplatedSnippet { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java index 0737db800..4f5646337 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -22,7 +22,7 @@ import java.util.Map; import java.util.concurrent.Callable; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.io.Resource; @@ -34,7 +34,7 @@ * * @author Andy Wilkinson */ -public class StandardTemplateResourceResolverTests { +class StandardTemplateResourceResolverTests { private final TemplateResourceResolver resolver = new StandardTemplateResourceResolver( TemplateFormats.asciidoctor()); @@ -42,7 +42,7 @@ public class StandardTemplateResourceResolverTests { private final TestClassLoader classLoader = new TestClassLoader(); @Test - public void formatSpecificCustomSnippetHasHighestPrecedence() throws IOException { + void formatSpecificCustomSnippetHasHighestPrecedence() throws IOException { this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/test.snippet", getClass().getResource("test-format-specific-custom.snippet")); this.classLoader.addResource("org/springframework/restdocs/templates/test.snippet", @@ -62,7 +62,7 @@ public Resource call() { } @Test - public void generalCustomSnippetIsUsedInAbsenceOfFormatSpecificCustomSnippet() throws IOException { + void generalCustomSnippetIsUsedInAbsenceOfFormatSpecificCustomSnippet() throws IOException { this.classLoader.addResource("org/springframework/restdocs/templates/test.snippet", getClass().getResource("test-custom.snippet")); this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet", @@ -80,7 +80,7 @@ public Resource call() { } @Test - public void defaultSnippetIsUsedInAbsenceOfCustomSnippets() throws Exception { + void defaultSnippetIsUsedInAbsenceOfCustomSnippets() throws Exception { this.classLoader.addResource("org/springframework/restdocs/templates/asciidoctor/default-test.snippet", getClass().getResource("test-default.snippet")); Resource snippet = doWithThreadContextClassLoader(this.classLoader, new Callable() { @@ -96,7 +96,7 @@ public Resource call() { } @Test - public void failsIfCustomAndDefaultSnippetsDoNotExist() { + void failsIfCustomAndDefaultSnippetsDoNotExist() { assertThatIllegalStateException() .isThrownBy(() -> doWithThreadContextClassLoader(this.classLoader, () -> StandardTemplateResourceResolverTests.this.resolver.resolveTemplateResource("test"))) @@ -120,7 +120,7 @@ private T doWithThreadContextClassLoader(ClassLoader classLoader, Callable resources = new HashMap<>(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java index 161471d00..635a80ae5 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2025 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. @@ -19,7 +19,7 @@ import java.io.IOException; import java.io.StringWriter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.restdocs.mustache.Template.Fragment; @@ -32,10 +32,10 @@ * * @author Andy Wilkinson */ -public class AsciidoctorTableCellContentLambdaTests { +class AsciidoctorTableCellContentLambdaTests { @Test - public void verticalBarCharactersAreEscaped() throws IOException { + void verticalBarCharactersAreEscaped() throws IOException { Fragment fragment = mock(Fragment.class); given(fragment.execute()).willReturn("|foo|bar|baz|"); StringWriter writer = new StringWriter(); @@ -44,7 +44,7 @@ public void verticalBarCharactersAreEscaped() throws IOException { } @Test - public void escapedVerticalBarCharactersAreNotEscapedAgain() throws IOException { + void escapedVerticalBarCharactersAreNotEscapedAgain() throws IOException { Fragment fragment = mock(Fragment.class); given(fragment.execute()).willReturn("\\|foo|bar\\|baz|"); StringWriter writer = new StringWriter(); diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-parameters-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/form-parameters-with-extra-column.snippet similarity index 100% rename from spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-parameters-with-extra-column.snippet rename to spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/form-parameters-with-extra-column.snippet diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-parameters-with-optional-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/form-parameters-with-optional-column.snippet similarity index 100% rename from spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-parameters-with-optional-column.snippet rename to spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/form-parameters-with-optional-column.snippet diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-parameters-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/form-parameters-with-title.snippet similarity index 100% rename from spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-parameters-with-title.snippet rename to spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/form-parameters-with-title.snippet diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-extra-column.snippet new file mode 100644 index 000000000..fb97f89bf --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-extra-column.snippet @@ -0,0 +1,10 @@ +|=== +|Parameter|Description|Foo + +{{#parameters}} +|{{name}} +|{{description}} +|{{foo}} + +{{/parameters}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-optional-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-optional-column.snippet new file mode 100644 index 000000000..70847ba1d --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-optional-column.snippet @@ -0,0 +1,10 @@ +|=== +|Parameter|Optional|Description + +{{#parameters}} +|{{name}} +|{{optional}} +|{{description}} + +{{/parameters}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-title.snippet new file mode 100644 index 000000000..611254aa9 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/query-parameters-with-title.snippet @@ -0,0 +1,10 @@ +.{{title}} +|=== +|Parameter|Description + +{{#parameters}} +|{{name}} +|{{description}} + +{{/parameters}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-cookies-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-cookies-with-extra-column.snippet new file mode 100644 index 000000000..62c9dad68 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-cookies-with-extra-column.snippet @@ -0,0 +1,10 @@ +|=== +|Name|Description|Foo + +{{#cookies}} +|{{name}} +|{{description}} +|{{foo}} + +{{/cookies}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-cookies-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-cookies-with-title.snippet new file mode 100644 index 000000000..5e4a4af43 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/request-cookies-with-title.snippet @@ -0,0 +1,10 @@ +.{{title}} +|=== +|Name|Description + +{{#cookies}} +|{{name}} +|{{description}} + +{{/cookies}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/response-cookies-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/response-cookies-with-extra-column.snippet new file mode 100644 index 000000000..62c9dad68 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/response-cookies-with-extra-column.snippet @@ -0,0 +1,10 @@ +|=== +|Name|Description|Foo + +{{#cookies}} +|{{name}} +|{{description}} +|{{foo}} + +{{/cookies}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/response-cookies-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/response-cookies-with-title.snippet new file mode 100644 index 000000000..5e4a4af43 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/asciidoctor/response-cookies-with-title.snippet @@ -0,0 +1,10 @@ +.{{title}} +|=== +|Name|Description + +{{#cookies}} +|{{name}} +|{{description}} + +{{/cookies}} +|=== \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-parameters-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/form-parameters-with-extra-column.snippet similarity index 100% rename from spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-parameters-with-extra-column.snippet rename to spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/form-parameters-with-extra-column.snippet diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-parameters-with-optional-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/form-parameters-with-optional-column.snippet similarity index 100% rename from spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-parameters-with-optional-column.snippet rename to spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/form-parameters-with-optional-column.snippet diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-parameters-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/form-parameters-with-title.snippet similarity index 100% rename from spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-parameters-with-title.snippet rename to spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/form-parameters-with-title.snippet diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-extra-column.snippet new file mode 100644 index 000000000..260502b69 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-extra-column.snippet @@ -0,0 +1,5 @@ +Parameter | Description | Foo +--------- | ----------- | --- +{{#parameters}} +{{name}} | {{description}} | {{foo}} +{{/parameters}} \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-optional-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-optional-column.snippet new file mode 100644 index 000000000..2f9cd0774 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-optional-column.snippet @@ -0,0 +1,5 @@ +Parameter | Optional | Description +--------- | -------- | ----------- +{{#parameters}} +{{name}} | {{optional}} | {{description}} +{{/parameters}} \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-title.snippet new file mode 100644 index 000000000..b63b62353 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/query-parameters-with-title.snippet @@ -0,0 +1,6 @@ +{{title}} +Parameter | Description +--------- | ----------- +{{#parameters}} +{{name}} | {{description}} +{{/parameters}} \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-cookies-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-cookies-with-extra-column.snippet new file mode 100644 index 000000000..8c7416287 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-cookies-with-extra-column.snippet @@ -0,0 +1,5 @@ +Name | Description | Foo +---- | ----------- | --- +{{#cookies}} +{{name}} | {{description}} | {{foo}} +{{/cookies}} \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-cookies-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-cookies-with-title.snippet new file mode 100644 index 000000000..e5e2c8bda --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-cookies-with-title.snippet @@ -0,0 +1,6 @@ +{{title}} +Name | Description +---- | ----------- +{{#cookies}} +{{name}} | {{description}} +{{/cookies}} \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-fields-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-fields-with-title.snippet index 24bb63fa9..ff141ad37 100644 --- a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-fields-with-title.snippet +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/request-fields-with-title.snippet @@ -1,4 +1,5 @@ {{title}} + Path | Type | Description ---- | ---- | ----------- {{#fields}} diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/response-cookies-with-extra-column.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/response-cookies-with-extra-column.snippet new file mode 100644 index 000000000..8c7416287 --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/response-cookies-with-extra-column.snippet @@ -0,0 +1,5 @@ +Name | Description | Foo +---- | ----------- | --- +{{#cookies}} +{{name}} | {{description}} | {{foo}} +{{/cookies}} \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/response-cookies-with-title.snippet b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/response-cookies-with-title.snippet new file mode 100644 index 000000000..e5e2c8bda --- /dev/null +++ b/spring-restdocs-core/src/test/resources/custom-snippet-templates/markdown/response-cookies-with-title.snippet @@ -0,0 +1,6 @@ +{{title}} +Name | Description +---- | ----------- +{{#cookies}} +{{name}} | {{description}} +{{/cookies}} \ No newline at end of file diff --git a/spring-restdocs-core/src/test/resources/org/springframework/restdocs/constraints/TestConstraintDescriptions.properties b/spring-restdocs-core/src/test/resources/org/springframework/restdocs/constraints/TestConstraintDescriptions.properties index ea0f3a91c..b7150793e 100644 --- a/spring-restdocs-core/src/test/resources/org/springframework/restdocs/constraints/TestConstraintDescriptions.properties +++ b/spring-restdocs-core/src/test/resources/org/springframework/restdocs/constraints/TestConstraintDescriptions.properties @@ -1 +1 @@ -javax.validation.constraints.NotNull.description=Should not be null \ No newline at end of file +jakarta.validation.constraints.NotNull.description=Should not be null \ No newline at end of file diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/GeneratedSnippets.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/GeneratedSnippets.java deleted file mode 100644 index 4a577a4d1..000000000 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/GeneratedSnippets.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.testfixtures; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; - -import org.junit.runners.model.Statement; - -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.util.FileCopyUtils; - -import static org.assertj.core.api.Assertions.fail; - -/** - * The {@code GeneratedSnippets} rule is used to capture the snippets generated by a test - * and assert their existence and content. - * - * @author Andy Wilkinson - * @author Andreas Evers - */ -public class GeneratedSnippets extends OperationTestRule { - - private final TemplateFormat templateFormat; - - private String operationName; - - private File outputDirectory; - - public GeneratedSnippets(TemplateFormat templateFormat) { - this.templateFormat = templateFormat; - } - - @Override - public Statement apply(Statement base, File outputDirectory, String operationName) { - this.outputDirectory = outputDirectory; - this.operationName = operationName; - return base; - } - - public String curlRequest() { - return snippet("curl-request"); - } - - public String httpieRequest() { - return snippet("httpie-request"); - } - - public String requestHeaders() { - return snippet("request-headers"); - } - - public String responseHeaders() { - return snippet("response-headers"); - } - - public String httpRequest() { - return snippet("http-request"); - } - - public String httpResponse() { - return snippet("http-response"); - } - - public String links() { - return snippet("links"); - } - - public String requestFields() { - return snippet("request-fields"); - } - - public String requestParts() { - return snippet("request-parts"); - } - - public String requestPartFields(String partName) { - return snippet("request-part-" + partName + "-fields"); - } - - public String responseFields() { - return snippet("response-fields"); - } - - public String pathParameters() { - return snippet("path-parameters"); - } - - public String requestParameters() { - return snippet("request-parameters"); - } - - public String snippet(String name) { - File snippetFile = getSnippetFile(name); - try { - return FileCopyUtils - .copyToString(new InputStreamReader(new FileInputStream(snippetFile), StandardCharsets.UTF_8)); - } - catch (Exception ex) { - fail("Failed to read '" + snippetFile + "'", ex); - return null; - } - } - - private File getSnippetFile(String name) { - if (this.outputDirectory == null) { - fail("Output directory was null"); - } - if (this.operationName == null) { - fail("Operation name was null"); - } - File snippetDir = new File(this.outputDirectory, this.operationName); - return new File(snippetDir, name + "." + this.templateFormat.getFileExtension()); - } - -} diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OperationTestRule.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OperationTestRule.java deleted file mode 100644 index 79e19f0ff..000000000 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OperationTestRule.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2014-2021 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.restdocs.testfixtures; - -import java.io.File; - -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * Abstract base class for Operation-related {@link TestRule TestRules}. - * - * @author Andy Wilkinson - */ -abstract class OperationTestRule implements TestRule { - - @Override - public final Statement apply(Statement base, Description description) { - return apply(base, determineOutputDirectory(description), determineOperationName(description)); - } - - private File determineOutputDirectory(Description description) { - return new File("build/" + description.getTestClass().getSimpleName()); - } - - private String determineOperationName(Description description) { - String operationName = description.getMethodName(); - int index = operationName.indexOf('['); - if (index > 0) { - operationName = operationName.substring(0, index); - } - return operationName; - } - - protected abstract Statement apply(Statement base, File outputDirectory, String operationName); - -} diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OutputCaptureRule.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OutputCaptureRule.java deleted file mode 100644 index 38710f25b..000000000 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OutputCaptureRule.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2014-2022 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.restdocs.testfixtures; - -import org.junit.Rule; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * JUnit {@code @Rule} to capture output from System.out and System.err. - *

        - * To use add as a {@link Rule @Rule}: - * - *

        - * public class MyTest {
        - *
        - *     @Rule
        - *     public OutputCaptureRule output = new OutputCaptureRule();
        - *
        - *     @Test
        - *     public void test() {
        - *         assertThat(output).contains("ok");
        - *     }
        - *
        - * }
        - * 
        - * - * @author Phillip Webb - * @author Andy Wilkinson - */ -public class OutputCaptureRule implements TestRule, CapturedOutput { - - private final OutputCapture delegate = new OutputCapture(); - - @Override - public Statement apply(Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - OutputCaptureRule.this.delegate.push(); - try { - base.evaluate(); - } - finally { - OutputCaptureRule.this.delegate.pop(); - } - } - }; - } - - @Override - public String getAll() { - return this.delegate.getAll(); - } - - @Override - public String getOut() { - return this.delegate.getOut(); - } - - @Override - public String getErr() { - return this.delegate.getErr(); - } - - @Override - public String toString() { - return this.delegate.toString(); - } - -} diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/SnippetConditions.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/SnippetConditions.java index 9bd3db020..ec20b374f 100644 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/SnippetConditions.java +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/SnippetConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2024 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. @@ -81,7 +81,7 @@ public static HttpResponseCondition httpResponse(TemplateFormat format, Integer new MarkdownCodeBlockCondition<>("http"), 2); } - @SuppressWarnings({ "rawtypes" }) + @SuppressWarnings("rawtypes") public static CodeBlockCondition codeBlock(TemplateFormat format, String language) { if ("adoc".equals(format.getFileExtension())) { return new AsciidoctorCodeBlockCondition(language, null); @@ -89,7 +89,7 @@ public static CodeBlockCondition codeBlock(TemplateFormat format, String lang return new MarkdownCodeBlockCondition(language); } - @SuppressWarnings({ "rawtypes" }) + @SuppressWarnings("rawtypes") public static CodeBlockCondition codeBlock(TemplateFormat format, String language, String options) { if ("adoc".equals(format.getFileExtension())) { return new AsciidoctorCodeBlockCondition(language, options); diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/AssertableSnippets.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/AssertableSnippets.java new file mode 100644 index 000000000..fdab049e1 --- /dev/null +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/AssertableSnippets.java @@ -0,0 +1,679 @@ +/* + * Copyright 2014-2025 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.restdocs.testfixtures.jupiter; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.function.UnaryOperator; + +import org.assertj.core.api.AbstractStringAssert; +import org.assertj.core.api.AssertProvider; +import org.assertj.core.api.Assertions; + +import org.springframework.restdocs.templates.TemplateFormat; +import org.springframework.restdocs.templates.TemplateFormats; +import org.springframework.util.StringUtils; + +/** + * AssertJ {@link AssertProvider} for asserting that the generated snippets are correct. + * + * @author Andy Wilkinson + */ +public class AssertableSnippets { + + private final File outputDirectory; + + private final String operationName; + + private final TemplateFormat templateFormat; + + AssertableSnippets(File outputDirectory, String operationName, TemplateFormat templateFormat) { + this.outputDirectory = outputDirectory; + this.operationName = operationName; + this.templateFormat = templateFormat; + } + + public File named(String name) { + return getSnippetFile(name); + } + + private File getSnippetFile(String name) { + File snippetDir = new File(this.outputDirectory, this.operationName); + return new File(snippetDir, name + "." + this.templateFormat.getFileExtension()); + } + + public CodeBlockSnippetAssertProvider curlRequest() { + return new CodeBlockSnippetAssertProvider("curl-request"); + } + + public TableSnippetAssertProvider formParameters() { + return new TableSnippetAssertProvider("form-parameters"); + } + + public CodeBlockSnippetAssertProvider httpieRequest() { + return new CodeBlockSnippetAssertProvider("httpie-request"); + } + + public HttpRequestSnippetAssertProvider httpRequest() { + return new HttpRequestSnippetAssertProvider("http-request"); + } + + public HttpResponseSnippetAssertProvider httpResponse() { + return new HttpResponseSnippetAssertProvider("http-response"); + } + + public TableSnippetAssertProvider links() { + return new TableSnippetAssertProvider("links"); + } + + public TableSnippetAssertProvider pathParameters() { + return new TableSnippetAssertProvider("path-parameters"); + } + + public TableSnippetAssertProvider queryParameters() { + return new TableSnippetAssertProvider("query-parameters"); + } + + public CodeBlockSnippetAssertProvider requestBody() { + return new CodeBlockSnippetAssertProvider("request-body"); + } + + public CodeBlockSnippetAssertProvider requestBody(String suffix) { + return new CodeBlockSnippetAssertProvider("request-body-%s".formatted(suffix)); + } + + public TableSnippetAssertProvider requestCookies() { + return new TableSnippetAssertProvider("request-cookies"); + } + + public TableSnippetAssertProvider requestCookies(String suffix) { + return new TableSnippetAssertProvider("request-cookies-%s".formatted(suffix)); + } + + public TableSnippetAssertProvider requestFields() { + return new TableSnippetAssertProvider("request-fields"); + } + + public TableSnippetAssertProvider requestFields(String suffix) { + return new TableSnippetAssertProvider("request-fields-%s".formatted(suffix)); + } + + public TableSnippetAssertProvider requestHeaders() { + return new TableSnippetAssertProvider("request-headers"); + } + + public TableSnippetAssertProvider requestHeaders(String suffix) { + return new TableSnippetAssertProvider("request-headers-%s".formatted(suffix)); + } + + public CodeBlockSnippetAssertProvider requestPartBody(String partName) { + return new CodeBlockSnippetAssertProvider("request-part-%s-body".formatted(partName)); + } + + public CodeBlockSnippetAssertProvider requestPartBody(String partName, String suffix) { + return new CodeBlockSnippetAssertProvider("request-part-%s-body-%s".formatted(partName, suffix)); + } + + public TableSnippetAssertProvider requestPartFields(String partName) { + return new TableSnippetAssertProvider("request-part-%s-fields".formatted(partName)); + } + + public TableSnippetAssertProvider requestPartFields(String partName, String suffix) { + return new TableSnippetAssertProvider("request-part-%s-fields-%s".formatted(partName, suffix)); + } + + public TableSnippetAssertProvider requestParts() { + return new TableSnippetAssertProvider("request-parts"); + } + + public CodeBlockSnippetAssertProvider responseBody() { + return new CodeBlockSnippetAssertProvider("response-body"); + } + + public CodeBlockSnippetAssertProvider responseBody(String suffix) { + return new CodeBlockSnippetAssertProvider("response-body-%s".formatted(suffix)); + } + + public TableSnippetAssertProvider responseCookies() { + return new TableSnippetAssertProvider("response-cookies"); + } + + public TableSnippetAssertProvider responseFields() { + return new TableSnippetAssertProvider("response-fields"); + } + + public TableSnippetAssertProvider responseFields(String suffix) { + return new TableSnippetAssertProvider("response-fields-%s".formatted(suffix)); + } + + public TableSnippetAssertProvider responseHeaders() { + return new TableSnippetAssertProvider("response-headers"); + } + + public final class TableSnippetAssertProvider implements AssertProvider { + + private final String snippetName; + + private TableSnippetAssertProvider(String snippetName) { + this.snippetName = snippetName; + } + + @Override + public TableSnippetAssert assertThat() { + try { + String content = Files + .readString(new File(AssertableSnippets.this.outputDirectory, AssertableSnippets.this.operationName + + "/" + this.snippetName + "." + AssertableSnippets.this.templateFormat.getFileExtension()) + .toPath()); + return new TableSnippetAssert(content); + } + catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + } + + public final class TableSnippetAssert extends AbstractStringAssert { + + private TableSnippetAssert(String actual) { + super(actual, TableSnippetAssert.class); + } + + public void isTable(UnaryOperator> tableOperator) { + Table table = tableOperator + .apply(AssertableSnippets.this.templateFormat.equals(TemplateFormats.asciidoctor()) + ? new AsciidoctorTable() : new MarkdownTable()); + table.getLinesAsString(); + Assertions.assertThat(this.actual).isEqualTo(table.getLinesAsString()); + } + + } + + public abstract class Table> extends SnippetContent { + + public abstract T withHeader(String... columns); + + public abstract T withTitleAndHeader(String title, String... columns); + + public abstract T row(String... entries); + + public abstract T configuration(String string); + + } + + private final class AsciidoctorTable extends Table { + + @Override + public AsciidoctorTable withHeader(String... columns) { + return withTitleAndHeader("", columns); + } + + @Override + public AsciidoctorTable withTitleAndHeader(String title, String... columns) { + if (!title.isBlank()) { + this.addLine("." + title); + } + this.addLine("|==="); + String header = "|" + StringUtils.collectionToDelimitedString(Arrays.asList(columns), "|"); + this.addLine(header); + this.addLine(""); + this.addLine("|==="); + return this; + } + + @Override + public AsciidoctorTable row(String... entries) { + for (String entry : entries) { + this.addLine(-1, "|" + escapeEntry(entry)); + } + this.addLine(-1, ""); + return this; + } + + private String escapeEntry(String entry) { + entry = entry.replace("|", "\\|"); + if (entry.startsWith("`") && entry.endsWith("`")) { + return "`+" + entry.substring(1, entry.length() - 1) + "+`"; + } + return entry; + } + + @Override + public AsciidoctorTable configuration(String configuration) { + this.addLine(0, configuration); + return this; + } + + } + + private final class MarkdownTable extends Table { + + @Override + public MarkdownTable withHeader(String... columns) { + return withTitleAndHeader("", columns); + } + + @Override + public MarkdownTable withTitleAndHeader(String title, String... columns) { + if (StringUtils.hasText(title)) { + this.addLine(title); + this.addLine(""); + } + String header = StringUtils.collectionToDelimitedString(Arrays.asList(columns), " | "); + this.addLine(header); + List components = new ArrayList<>(); + for (String column : columns) { + StringBuilder dashes = new StringBuilder(); + for (int i = 0; i < column.length(); i++) { + dashes.append("-"); + } + components.add(dashes.toString()); + } + this.addLine(StringUtils.collectionToDelimitedString(components, " | ")); + this.addLine(""); + return this; + } + + @Override + public MarkdownTable row(String... entries) { + this.addLine(-1, StringUtils.collectionToDelimitedString(Arrays.asList(entries), " | ")); + return this; + } + + @Override + public MarkdownTable configuration(String configuration) { + throw new UnsupportedOperationException("Markdown tables do not support configuration"); + } + + } + + public final class CodeBlockSnippetAssertProvider implements AssertProvider { + + private final String snippetName; + + private CodeBlockSnippetAssertProvider(String snippetName) { + this.snippetName = snippetName; + } + + @Override + public CodeBlockSnippetAssert assertThat() { + try { + String content = Files + .readString(new File(AssertableSnippets.this.outputDirectory, AssertableSnippets.this.operationName + + "/" + this.snippetName + "." + AssertableSnippets.this.templateFormat.getFileExtension()) + .toPath()); + return new CodeBlockSnippetAssert(content); + } + catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + } + + public final class CodeBlockSnippetAssert extends AbstractStringAssert { + + private CodeBlockSnippetAssert(String actual) { + super(actual, CodeBlockSnippetAssert.class); + } + + public void isCodeBlock(UnaryOperator> codeBlockOperator) { + CodeBlock codeBlock = codeBlockOperator + .apply(AssertableSnippets.this.templateFormat.equals(TemplateFormats.asciidoctor()) + ? new AsciidoctorCodeBlock() : new MarkdownCodeBlock()); + Assertions.assertThat(this.actual).isEqualTo(codeBlock.getLinesAsString()); + } + + } + + public abstract class CodeBlock> extends SnippetContent { + + public abstract T withLanguage(String language); + + public abstract T withOptions(String options); + + public abstract T withLanguageAndOptions(String language, String options); + + public abstract T content(String string); + + } + + private final class AsciidoctorCodeBlock extends CodeBlock { + + @Override + public AsciidoctorCodeBlock withLanguage(String language) { + addLine("[source,%s]".formatted(language)); + return this; + } + + @Override + public AsciidoctorCodeBlock withOptions(String options) { + addLine("[source,options=\"%s\"]".formatted(options)); + return this; + } + + @Override + public AsciidoctorCodeBlock withLanguageAndOptions(String language, String options) { + addLine("[source,%s,options=\"%s\"]".formatted(language, options)); + return this; + } + + @Override + public AsciidoctorCodeBlock content(String content) { + addLine("----"); + addLine(content); + addLine("----"); + return this; + } + + } + + private final class MarkdownCodeBlock extends CodeBlock { + + @Override + public MarkdownCodeBlock withLanguage(String language) { + addLine("```%s".formatted(language)); + return this; + } + + @Override + public MarkdownCodeBlock withOptions(String options) { + addLine("```"); + return this; + } + + @Override + public MarkdownCodeBlock withLanguageAndOptions(String language, String options) { + addLine("```%s".formatted(language)); + return this; + } + + @Override + public MarkdownCodeBlock content(String content) { + addLine(content); + addLine("```"); + return this; + } + + } + + public final class HttpRequestSnippetAssertProvider implements AssertProvider { + + private final String snippetName; + + private HttpRequestSnippetAssertProvider(String snippetName) { + this.snippetName = snippetName; + } + + @Override + public HttpRequestSnippetAssert assertThat() { + try { + String content = Files + .readString(new File(AssertableSnippets.this.outputDirectory, AssertableSnippets.this.operationName + + "/" + this.snippetName + "." + AssertableSnippets.this.templateFormat.getFileExtension()) + .toPath()); + return new HttpRequestSnippetAssert(content); + } + catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + } + + public final class HttpRequestSnippetAssert extends AbstractStringAssert { + + private HttpRequestSnippetAssert(String actual) { + super(actual, HttpRequestSnippetAssert.class); + } + + public void isHttpRequest(UnaryOperator> operator) { + HttpRequest codeBlock = operator + .apply(AssertableSnippets.this.templateFormat.equals(TemplateFormats.asciidoctor()) + ? new AsciidoctorHttpRequest() : new MarkdownHttpRequest()); + Assertions.assertThat(this.actual).isEqualTo(codeBlock.getLinesAsString()); + } + + } + + public abstract class HttpRequest> extends SnippetContent { + + public T get(String uri) { + return request("GET", uri); + } + + public T post(String uri) { + return request("POST", uri); + } + + public T put(String uri) { + return request("PUT", uri); + } + + public T patch(String uri) { + return request("PATCH", uri); + } + + public T delete(String uri) { + return request("DELETE", uri); + } + + protected abstract T request(String method, String uri); + + public abstract T header(String name, Object value); + + @SuppressWarnings("unchecked") + public T content(String content) { + addLine(-1, content); + return (T) this; + } + + } + + private final class AsciidoctorHttpRequest extends HttpRequest { + + private int headerOffset = 3; + + @Override + protected AsciidoctorHttpRequest request(String method, String uri) { + addLine("[source,http,options=\"nowrap\"]"); + addLine("----"); + addLine("%s %s HTTP/1.1".formatted(method, uri)); + addLine(""); + addLine("----"); + return this; + } + + @Override + public AsciidoctorHttpRequest header(String name, Object value) { + addLine(this.headerOffset++, "%s: %s".formatted(name, value)); + return this; + } + + } + + private final class MarkdownHttpRequest extends HttpRequest { + + private int headerOffset = 2; + + @Override + public MarkdownHttpRequest request(String method, String uri) { + addLine("```http"); + addLine("%s %s HTTP/1.1".formatted(method, uri)); + addLine(""); + addLine("```"); + return this; + } + + @Override + public MarkdownHttpRequest header(String name, Object value) { + addLine(this.headerOffset++, "%s: %s".formatted(name, value)); + return this; + } + + } + + public final class HttpResponseSnippetAssertProvider implements AssertProvider { + + private final String snippetName; + + private HttpResponseSnippetAssertProvider(String snippetName) { + this.snippetName = snippetName; + } + + @Override + public HttpResponseSnippetAssert assertThat() { + try { + String content = Files + .readString(new File(AssertableSnippets.this.outputDirectory, AssertableSnippets.this.operationName + + "/" + this.snippetName + "." + AssertableSnippets.this.templateFormat.getFileExtension()) + .toPath()); + return new HttpResponseSnippetAssert(content); + } + catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + } + + public final class HttpResponseSnippetAssert extends AbstractStringAssert { + + private HttpResponseSnippetAssert(String actual) { + super(actual, HttpResponseSnippetAssert.class); + } + + public void isHttpResponse(UnaryOperator> operator) { + HttpResponse httpResponse = operator + .apply(AssertableSnippets.this.templateFormat.equals(TemplateFormats.asciidoctor()) + ? new AsciidoctorHttpResponse() : new MarkdownHttpResponse()); + Assertions.assertThat(this.actual).isEqualTo(httpResponse.getLinesAsString()); + } + + } + + public abstract class HttpResponse> extends SnippetContent { + + public T ok() { + return status("200 OK"); + } + + public T badRequest() { + return status("400 Bad Request"); + } + + public T status(int status) { + return status("%d ".formatted(status)); + } + + protected abstract T status(String status); + + public abstract T header(String name, Object value); + + @SuppressWarnings("unchecked") + public T content(String content) { + addLine(-1, content); + return (T) this; + } + + } + + private final class AsciidoctorHttpResponse extends HttpResponse { + + private int headerOffset = 3; + + @Override + protected AsciidoctorHttpResponse status(String status) { + addLine("[source,http,options=\"nowrap\"]"); + addLine("----"); + addLine("HTTP/1.1 %s".formatted(status)); + addLine(""); + addLine("----"); + return this; + } + + @Override + public AsciidoctorHttpResponse header(String name, Object value) { + addLine(this.headerOffset++, "%s: %s".formatted(name, value)); + return this; + } + + } + + private final class MarkdownHttpResponse extends HttpResponse { + + private int headerOffset = 2; + + @Override + public MarkdownHttpResponse status(String status) { + addLine("```http"); + addLine("HTTP/1.1 %s".formatted(status)); + addLine(""); + addLine("```"); + return this; + } + + @Override + public MarkdownHttpResponse header(String name, Object value) { + addLine(this.headerOffset++, "%s: %s".formatted(name, value)); + return this; + } + + } + + private static class SnippetContent { + + private List lines = new ArrayList<>(); + + protected void addLine(String line) { + this.lines.add(line); + } + + protected void addLine(int index, String line) { + this.lines.add(determineIndex(index), line); + } + + private int determineIndex(int index) { + if (index >= 0) { + return index; + } + return index + this.lines.size(); + } + + protected String getLinesAsString() { + StringWriter writer = new StringWriter(); + Iterator iterator = this.lines.iterator(); + while (iterator.hasNext()) { + writer.append(String.format("%s", iterator.next())); + if (iterator.hasNext()) { + writer.append(String.format("%n")); + } + } + return writer.toString(); + } + + } + +} diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/CapturedOutput.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/CapturedOutput.java similarity index 77% rename from spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/CapturedOutput.java rename to spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/CapturedOutput.java index 699864f5f..d3aaed82c 100644 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/CapturedOutput.java +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/CapturedOutput.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2025 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. @@ -14,16 +14,11 @@ * limitations under the License. */ -package org.springframework.restdocs.testfixtures; +package org.springframework.restdocs.testfixtures.jupiter; /** * Provides access to {@link System#out System.out} and {@link System#err System.err} - * output that has been captured by the {@link OutputCaptureRule}. Can be used to apply - * assertions using AssertJ. For example:
        - * assertThat(output).contains("started"); // Checks all output
        - * assertThat(output.getErr()).contains("failed"); // Only checks System.err
        - * assertThat(output.getOut()).contains("ok"); // Only checks System.out
        - * 
        + * output that has been captured. * * @author Madhura Bhave * @author Phillip Webb diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OperationBuilder.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OperationBuilder.java similarity index 86% rename from spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OperationBuilder.java rename to spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OperationBuilder.java index 9308255b6..97c9ebcdd 100644 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OperationBuilder.java +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OperationBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2025 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. @@ -14,22 +14,22 @@ * limitations under the License. */ -package org.springframework.restdocs.testfixtures; +package org.springframework.restdocs.testfixtures.jupiter; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; - -import org.junit.runners.model.Statement; +import java.util.Set; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.restdocs.ManualRestDocumentation; import org.springframework.restdocs.RestDocumentationContext; import org.springframework.restdocs.mustache.Mustache; @@ -40,8 +40,8 @@ import org.springframework.restdocs.operation.OperationRequestPartFactory; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; +import org.springframework.restdocs.operation.ResponseCookie; import org.springframework.restdocs.operation.StandardOperation; import org.springframework.restdocs.snippet.RestDocumentationContextPlaceholderResolverFactory; import org.springframework.restdocs.snippet.StandardWriterResolver; @@ -57,21 +57,27 @@ * * @author Andy Wilkinson */ -public class OperationBuilder extends OperationTestRule { +public class OperationBuilder { private final Map attributes = new HashMap<>(); - private OperationResponseBuilder responseBuilder; - - private String name; + private final File outputDirectory; - private File outputDirectory; + private final String name; private final TemplateFormat templateFormat; + private OperationResponseBuilder responseBuilder; + private OperationRequestBuilder requestBuilder; - public OperationBuilder(TemplateFormat templateFormat) { + OperationBuilder(File outputDirectory, String name) { + this(outputDirectory, name, null); + } + + OperationBuilder(File outputDirectory, String name, TemplateFormat templateFormat) { + this.outputDirectory = outputDirectory; + this.name = name; this.templateFormat = templateFormat; } @@ -90,14 +96,6 @@ public OperationBuilder attribute(String name, Object value) { return this; } - private void prepare(String operationName, File outputDirectory) { - this.name = operationName; - this.outputDirectory = outputDirectory; - this.requestBuilder = null; - this.requestBuilder = null; - this.attributes.clear(); - } - public Operation build() { if (this.attributes.get(TemplateEngine.class.getName()) == null) { Map templateContext = new HashMap<>(); @@ -126,12 +124,6 @@ private RestDocumentationContext createContext() { return context; } - @Override - public Statement apply(Statement base, File outputDirectory, String operationName) { - prepare(operationName, outputDirectory); - return base; - } - /** * Basic builder API for creating an {@link OperationRequest}. */ @@ -145,8 +137,6 @@ public final class OperationRequestBuilder { private HttpHeaders headers = new HttpHeaders(); - private Parameters parameters = new Parameters(); - private List partBuilders = new ArrayList<>(); private Collection cookies = new ArrayList<>(); @@ -160,8 +150,8 @@ private OperationRequest buildRequest() { for (OperationRequestPartBuilder builder : this.partBuilders) { parts.add(builder.buildPart()); } - return new OperationRequestFactory().create(this.requestUri, this.method, this.content, this.headers, - this.parameters, parts, this.cookies); + return new OperationRequestFactory().create(this.requestUri, this.method, this.content, this.headers, parts, + this.cookies); } public Operation build() { @@ -183,18 +173,6 @@ public OperationRequestBuilder content(byte[] content) { return this; } - public OperationRequestBuilder param(String name, String... values) { - if (values.length > 0) { - for (String value : values) { - this.parameters.add(name, value); - } - } - else { - this.parameters.put(name, Collections.emptyList()); - } - return this; - } - public OperationRequestBuilder header(String name, String value) { this.headers.add(name, value); return this; @@ -261,17 +239,19 @@ public OperationRequestPartBuilder header(String name, String value) { */ public final class OperationResponseBuilder { - private int status = HttpStatus.OK.value(); + private HttpStatusCode status = HttpStatus.OK; private HttpHeaders headers = new HttpHeaders(); + private Set cookies = new HashSet<>(); + private byte[] content = new byte[0]; private OperationResponse buildResponse() { - return new OperationResponseFactory().create(this.status, this.headers, this.content); + return new OperationResponseFactory().create(this.status, this.headers, this.content, this.cookies); } - public OperationResponseBuilder status(int status) { + public OperationResponseBuilder status(HttpStatusCode status) { this.status = status; return this; } @@ -281,6 +261,11 @@ public OperationResponseBuilder header(String name, String value) { return this; } + public OperationResponseBuilder cookie(String name, String value) { + this.cookies.add(new ResponseCookie(name, value)); + return this; + } + public OperationResponseBuilder content(byte[] content) { this.content = content; return this; diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OutputCapture.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OutputCapture.java similarity index 94% rename from spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OutputCapture.java rename to spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OutputCapture.java index eef8d6a39..385dd49cf 100644 --- a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/OutputCapture.java +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OutputCapture.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2025 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.testfixtures; +package org.springframework.restdocs.testfixtures.jupiter; import java.io.IOException; import java.io.OutputStream; @@ -35,8 +35,6 @@ * @author Madhura Bhave * @author Phillip Webb * @author Andy Wilkinson - * @author Sam Brannen - * @see OutputCaptureRule */ class OutputCapture implements CapturedOutput { @@ -61,7 +59,7 @@ public boolean equals(Object obj) { if (obj == this) { return true; } - if (obj instanceof CapturedOutput || obj instanceof CharSequence) { + if (obj instanceof CharSequence) { return getAll().equals(obj.toString()); } return false; @@ -123,17 +121,17 @@ private String get(Predicate filter) { } /** - * A capture session that captures {@link System#out System.out} and {@link System#out + * A capture session that captures {@link System#out System.out} and {@link System#err * System.err}. */ private static class SystemCapture { - private final Object monitor = new Object(); - private final PrintStreamCapture out; private final PrintStreamCapture err; + private final Object monitor = new Object(); + private final List capturedStrings = new ArrayList<>(); SystemCapture() { @@ -195,8 +193,8 @@ PrintStream getParent() { } private static PrintStream getSystemStream(PrintStream printStream) { - while (printStream instanceof PrintStreamCapture) { - printStream = ((PrintStreamCapture) printStream).getParent(); + while (printStream instanceof PrintStreamCapture printStreamCapture) { + printStream = printStreamCapture.getParent(); } return printStream; } diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OutputCaptureExtension.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OutputCaptureExtension.java new file mode 100644 index 000000000..4dbb2b8ed --- /dev/null +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/OutputCaptureExtension.java @@ -0,0 +1,112 @@ +/* + * Copyright 2014-2025 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.restdocs.testfixtures.jupiter; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +/** + * JUnit Jupiter {@code @Extension} to capture {@link System#out System.out} and + * {@link System#err System.err}. Can be registered for an entire test class or for an + * individual test method through {@link ExtendWith @ExtendWith}. This extension provides + * {@linkplain ParameterResolver parameter resolution} for a {@link CapturedOutput} + * instance which can be used to assert that the correct output was written. + *

        + * To use with {@link ExtendWith @ExtendWith}, inject the {@link CapturedOutput} as an + * argument to your test class constructor, test method, or lifecycle methods: + * + *

        + * @ExtendWith(OutputCaptureExtension.class)
        + * class MyTest {
        + *
        + *     @Test
        + *     void test(CapturedOutput output) {
        + *         System.out.println("ok");
        + *         assertThat(output).contains("ok");
        + *         System.err.println("error");
        + *     }
        + *
        + *     @AfterEach
        + *     void after(CapturedOutput output) {
        + *         assertThat(output.getOut()).contains("ok");
        + *         assertThat(output.getErr()).contains("error");
        + *     }
        + *
        + * }
        + * 
        + * + * @author Madhura Bhave + * @author Phillip Webb + * @author Andy Wilkinson + * @author Sam Brannen + * @see CapturedOutput + */ +public class OutputCaptureExtension + implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver { + + OutputCaptureExtension() { + } + + @Override + public void beforeAll(ExtensionContext context) throws Exception { + getOutputCapture(context).push(); + } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + getOutputCapture(context).pop(); + } + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + getOutputCapture(context).push(); + } + + @Override + public void afterEach(ExtensionContext context) throws Exception { + getOutputCapture(context).pop(); + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return CapturedOutput.class.equals(parameterContext.getParameter().getType()); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { + return getOutputCapture(extensionContext); + } + + private OutputCapture getOutputCapture(ExtensionContext context) { + return getStore(context).getOrComputeIfAbsent(OutputCapture.class); + } + + private Store getStore(ExtensionContext context) { + return context.getStore(Namespace.create(getClass())); + } + +} diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/RenderedSnippetTest.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/RenderedSnippetTest.java new file mode 100644 index 000000000..15eb8d39c --- /dev/null +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/RenderedSnippetTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2014-2025 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.restdocs.testfixtures.jupiter; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.restdocs.templates.TemplateFormat; +import org.springframework.restdocs.templates.TemplateFormats; + +/** + * Signals that a method is a template for a test that renders a snippet. The test will be + * executed once for each of the two supported snippet formats (Asciidoctor and Markdown). + *

        + * A rendered snippet test method can inject the following types: + *

          + *
        • {@link OperationBuilder}
        • + *
        • {@link AssertableSnippets}
        • + *
        + * + * @author Andy Wilkinson + */ +@TestTemplate +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@ExtendWith(RenderedSnippetTestExtension.class) +public @interface RenderedSnippetTest { + + /** + * The snippet formats to render. + * @return the formats + */ + Format[] format() default { Format.ASCIIDOCTOR, Format.MARKDOWN }; + + enum Format { + + /** + * Asciidoctor snippet format. + */ + ASCIIDOCTOR(TemplateFormats.asciidoctor()), + + /** + * Markdown snippet format. + */ + MARKDOWN(TemplateFormats.markdown()); + + private final TemplateFormat templateFormat; + + Format(TemplateFormat templateFormat) { + this.templateFormat = templateFormat; + } + + TemplateFormat templateFormat() { + return this.templateFormat; + } + + } + +} diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/RenderedSnippetTestExtension.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/RenderedSnippetTestExtension.java new file mode 100644 index 000000000..34bb83ef9 --- /dev/null +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/RenderedSnippetTestExtension.java @@ -0,0 +1,155 @@ +/* + * Copyright 2014-2025 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.restdocs.testfixtures.jupiter; + +import java.io.File; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; +import org.junit.jupiter.api.extension.TestTemplateInvocationContext; +import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; +import org.junit.platform.commons.util.AnnotationUtils; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.restdocs.templates.TemplateEngine; +import org.springframework.restdocs.templates.TemplateFormat; +import org.springframework.restdocs.templates.TemplateResourceResolver; +import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import org.springframework.restdocs.testfixtures.jupiter.RenderedSnippetTest.Format; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** + * {@link TestTemplateInvocationContextProvider} for + * {@link RenderedSnippetTest @RenderedSnippetTest} and + * {@link SnippetTemplate @SnippetTemplate}. + * + * @author Andy Wilkinson + */ +class RenderedSnippetTestExtension implements TestTemplateInvocationContextProvider { + + @Override + public boolean supportsTestTemplate(ExtensionContext context) { + return true; + } + + @Override + public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { + return AnnotationUtils.findAnnotation(context.getRequiredTestMethod(), RenderedSnippetTest.class) + .map((renderedSnippetTest) -> Stream.of(renderedSnippetTest.format()) + .map(Format::templateFormat) + .map(SnippetTestInvocationContext::new) + .map(TestTemplateInvocationContext.class::cast)) + .orElseThrow(); + } + + static class SnippetTestInvocationContext implements TestTemplateInvocationContext { + + private final TemplateFormat templateFormat; + + SnippetTestInvocationContext(TemplateFormat templateFormat) { + this.templateFormat = templateFormat; + } + + @Override + public List getAdditionalExtensions() { + return List.of(new RenderedSnippetTestParameterResolver(this.templateFormat)); + } + + @Override + public String getDisplayName(int invocationIndex) { + return this.templateFormat.getId(); + } + + } + + static class RenderedSnippetTestParameterResolver implements ParameterResolver { + + private final TemplateFormat templateFormat; + + RenderedSnippetTestParameterResolver(TemplateFormat templateFormat) { + this.templateFormat = templateFormat; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Class parameterType = parameterContext.getParameter().getType(); + return AssertableSnippets.class.equals(parameterType) || OperationBuilder.class.equals(parameterType) + || TemplateFormat.class.equals(parameterType); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { + Class parameterType = parameterContext.getParameter().getType(); + if (AssertableSnippets.class.equals(parameterType)) { + return getStore(extensionContext).getOrComputeIfAbsent(AssertableSnippets.class, + (key) -> new AssertableSnippets(determineOutputDirectory(extensionContext), + determineOperationName(extensionContext), this.templateFormat)); + } + if (TemplateFormat.class.equals(parameterType)) { + return this.templateFormat; + } + return getStore(extensionContext).getOrComputeIfAbsent(OperationBuilder.class, (key) -> { + OperationBuilder operationBuilder = new OperationBuilder(determineOutputDirectory(extensionContext), + determineOperationName(extensionContext), this.templateFormat); + AnnotationUtils.findAnnotation(extensionContext.getRequiredTestMethod(), SnippetTemplate.class) + .ifPresent((snippetTemplate) -> { + TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); + given(resolver.resolveTemplateResource(snippetTemplate.snippet())) + .willReturn(snippetResource(snippetTemplate.template(), this.templateFormat)); + operationBuilder.attribute(TemplateEngine.class.getName(), + new MustacheTemplateEngine(resolver)); + }); + + return operationBuilder; + }); + } + + private Store getStore(ExtensionContext extensionContext) { + return extensionContext.getStore(Namespace.create(getClass())); + } + + private File determineOutputDirectory(ExtensionContext extensionContext) { + return new File("build/" + extensionContext.getRequiredTestClass().getSimpleName()); + } + + private String determineOperationName(ExtensionContext extensionContext) { + String operationName = extensionContext.getRequiredTestMethod().getName(); + int index = operationName.indexOf('['); + if (index > 0) { + operationName = operationName.substring(0, index); + } + return operationName; + } + + private FileSystemResource snippetResource(String name, TemplateFormat templateFormat) { + return new FileSystemResource( + "src/test/resources/custom-snippet-templates/" + templateFormat.getId() + "/" + name + ".snippet"); + } + + } + +} diff --git a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NullOrNotBlank.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTemplate.java similarity index 53% rename from samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NullOrNotBlank.java rename to spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTemplate.java index 23dbbd45c..a07e34ce7 100644 --- a/samples/rest-notes-spring-hateoas/src/main/java/com/example/notes/NullOrNotBlank.java +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2025 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. @@ -14,33 +14,33 @@ * limitations under the License. */ -package com.example.notes; +package org.springframework.restdocs.testfixtures.jupiter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import javax.validation.Constraint; -import javax.validation.Payload; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Null; - -import org.hibernate.validator.constraints.CompositionType; -import org.hibernate.validator.constraints.ConstraintComposition; - -@ConstraintComposition(CompositionType.OR) -@Constraint(validatedBy = {}) -@Null -@NotBlank -@Target({ ElementType.FIELD, ElementType.PARAMETER }) +/** + * Customizes the template that will be used when rendering a snippet in a + * {@link RenderedSnippetTest rendered snippet test}. + * + * @author Andy Wilkinson + */ @Retention(RetentionPolicy.RUNTIME) -@interface NullOrNotBlank { - - String message() default "Must be null or not blank"; - - Class[] groups() default {}; - - Class[] payload() default {}; +@Target(ElementType.METHOD) +public @interface SnippetTemplate { + + /** + * The name of the snippet whose template should be customized. + * @return the snippet name + */ + String snippet(); + + /** + * The custom template to use when rendering the snippet. + * @return the custom template + */ + String template(); } diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTest.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTest.java new file mode 100644 index 000000000..291f3e6f7 --- /dev/null +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTest.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014-2025 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.restdocs.testfixtures.jupiter; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.restdocs.snippet.Snippet; + +/** + * Signals that a method is a test of a {@link Snippet}. Typically used to test scenarios + * where a failure occurs before the snippet is rendered. To test snippet rendering, use + * {@link RenderedSnippetTest}. + *

        + * A snippet test method can inject the following types: + *

          + *
        • {@link OperationBuilder}
        • + *
        + * + * @author Andy Wilkinson + */ +@Test +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@ExtendWith(SnippetTestExtension.class) +public @interface SnippetTest { + +} diff --git a/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTestExtension.java b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTestExtension.java new file mode 100644 index 000000000..1488902fc --- /dev/null +++ b/spring-restdocs-core/src/testFixtures/java/org/springframework/restdocs/testfixtures/jupiter/SnippetTestExtension.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014-2025 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.restdocs.testfixtures.jupiter; + +import java.io.File; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +/** + * {@link ParameterResolver} for {@link SnippetTest @SnippetTest}. + * + * @author Andy Wilkinson + */ +class SnippetTestExtension implements ParameterResolver { + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + Class parameterType = parameterContext.getParameter().getType(); + return OperationBuilder.class.equals(parameterType); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { + return getStore(extensionContext).getOrComputeIfAbsent(OperationBuilder.class, + (key) -> new OperationBuilder(determineOutputDirectory(extensionContext), + determineOperationName(extensionContext))); + } + + private Store getStore(ExtensionContext extensionContext) { + return extensionContext.getStore(Namespace.create(getClass())); + } + + private File determineOutputDirectory(ExtensionContext extensionContext) { + return new File("build/" + extensionContext.getRequiredTestClass().getSimpleName()); + } + + private String determineOperationName(ExtensionContext extensionContext) { + String operationName = extensionContext.getRequiredTestMethod().getName(); + int index = operationName.indexOf('['); + if (index > 0) { + operationName = operationName.substring(0, index); + } + return operationName; + } + +} diff --git a/spring-restdocs-mockmvc/build.gradle b/spring-restdocs-mockmvc/build.gradle index 2b1789fed..875d74148 100644 --- a/spring-restdocs-mockmvc/build.gradle +++ b/spring-restdocs-mockmvc/build.gradle @@ -1,5 +1,4 @@ plugins { - id "io.spring.compatibility-test" version "0.0.2" id "java-library" id "maven-publish" id "optional-dependencies" @@ -12,20 +11,13 @@ dependencies { api("org.springframework:spring-webmvc") api("org.springframework:spring-test") - implementation("javax.servlet:javax.servlet-api") + implementation("jakarta.servlet:jakarta.servlet-api") internal(platform(project(":spring-restdocs-platform"))) testImplementation(testFixtures(project(":spring-restdocs-core"))) - testImplementation("junit:junit") - testImplementation("org.assertj:assertj-core") - testImplementation("org.hamcrest:hamcrest-library") - testImplementation("org.mockito:mockito-core") } -compatibilityTest { - dependency("Spring Framework") { springFramework -> - springFramework.groupId = "org.springframework" - springFramework.versions = ["5.1.+", "5.2.+", "5.3.+"] - } +tasks.named("test") { + useJUnitPlatform() } diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java index a456e252d..580bc763f 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -17,17 +17,21 @@ package org.springframework.restdocs.mockmvc; import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Scanner; -import javax.servlet.ServletException; -import javax.servlet.http.Part; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Part; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -39,10 +43,11 @@ import org.springframework.restdocs.operation.OperationRequestFactory; import org.springframework.restdocs.operation.OperationRequestPart; import org.springframework.restdocs.operation.OperationRequestPartFactory; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestConverter; import org.springframework.restdocs.operation.RequestCookie; import org.springframework.util.FileCopyUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; @@ -51,45 +56,98 @@ * {@link MockHttpServletRequest}. * * @author Andy Wilkinson + * @author Clyde Stubbs */ class MockMvcRequestConverter implements RequestConverter { - private static final String SCHEME_HTTP = "http"; - - private static final String SCHEME_HTTPS = "https"; - - private static final int STANDARD_PORT_HTTP = 80; - - private static final int STANDARD_PORT_HTTPS = 443; - @Override public OperationRequest convert(MockHttpServletRequest mockRequest) { try { HttpHeaders headers = extractHeaders(mockRequest); - Parameters parameters = extractParameters(mockRequest); List parts = extractParts(mockRequest); Collection cookies = extractCookies(mockRequest, headers); - String queryString = mockRequest.getQueryString(); - if (!StringUtils.hasText(queryString) && "GET".equals(mockRequest.getMethod())) { - queryString = parameters.toQueryString(); - } - return new OperationRequestFactory().create( - URI.create( - getRequestUri(mockRequest) + (StringUtils.hasText(queryString) ? "?" + queryString : "")), - HttpMethod.valueOf(mockRequest.getMethod()), mockRequest.getContentAsByteArray(), headers, - parameters, parts, cookies); + return new OperationRequestFactory().create(getRequestUri(mockRequest), + HttpMethod.valueOf(mockRequest.getMethod()), getRequestContent(mockRequest, headers), headers, + parts, cookies); } catch (Exception ex) { throw new ConversionException(ex); } } + private URI getRequestUri(MockHttpServletRequest mockRequest) { + String queryString = ""; + if (mockRequest.getQueryString() != null) { + queryString = mockRequest.getQueryString(); + } + else if ("GET".equals(mockRequest.getMethod()) || mockRequest.getContentLengthLong() > 0) { + queryString = urlEncodedParameters(mockRequest); + } + StringBuffer requestUrlBuffer = mockRequest.getRequestURL(); + if (queryString.length() > 0) { + requestUrlBuffer.append("?").append(queryString.toString()); + } + return URI.create(requestUrlBuffer.toString()); + } + + private String urlEncodedParameters(MockHttpServletRequest mockRequest) { + StringBuilder parameters = new StringBuilder(); + MultiValueMap queryParameters = parse(mockRequest.getQueryString()); + for (String name : IterableEnumeration.of(mockRequest.getParameterNames())) { + if (!queryParameters.containsKey(name)) { + String[] values = mockRequest.getParameterValues(name); + if (values.length == 0) { + append(parameters, name); + } + else { + for (String value : values) { + append(parameters, name, value); + } + } + } + } + return parameters.toString(); + } + + private byte[] getRequestContent(MockHttpServletRequest mockRequest, HttpHeaders headers) { + byte[] content = mockRequest.getContentAsByteArray(); + if ("GET".equals(mockRequest.getMethod())) { + return content; + } + MediaType contentType = headers.getContentType(); + if (contentType == null || MediaType.APPLICATION_FORM_URLENCODED.includes(contentType)) { + Map parameters = mockRequest.getParameterMap(); + if (!parameters.isEmpty() && (content == null || content.length == 0)) { + StringBuilder contentBuilder = new StringBuilder(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + MultiValueMap queryParameters = parse(mockRequest.getQueryString()); + mockRequest.getParameterMap().forEach((name, values) -> { + List queryParameterValues = queryParameters.get(name); + if (values.length == 0) { + if (queryParameterValues == null) { + append(contentBuilder, name); + } + } + else { + for (String value : values) { + if (queryParameterValues == null || !queryParameterValues.contains(value)) { + append(contentBuilder, name, value); + } + } + } + }); + return contentBuilder.toString().getBytes(StandardCharsets.UTF_8); + } + } + return content; + } + private Collection extractCookies(MockHttpServletRequest mockRequest, HttpHeaders headers) { if (mockRequest.getCookies() == null || mockRequest.getCookies().length == 0) { return Collections.emptyList(); } List cookies = new ArrayList<>(); - for (javax.servlet.http.Cookie servletCookie : mockRequest.getCookies()) { + for (jakarta.servlet.http.Cookie servletCookie : mockRequest.getCookies()) { cookies.add(new RequestCookie(servletCookie.getName(), servletCookie.getValue())); } headers.remove(HttpHeaders.COOKIE); @@ -157,16 +215,6 @@ private HttpHeaders extractHeaders(Part part) { return partHeaders; } - private Parameters extractParameters(MockHttpServletRequest servletRequest) { - Parameters parameters = new Parameters(); - for (String name : IterableEnumeration.of(servletRequest.getParameterNames())) { - for (String value : servletRequest.getParameterValues(name)) { - parameters.add(name, value); - } - } - return parameters; - } - private HttpHeaders extractHeaders(MockHttpServletRequest servletRequest) { HttpHeaders headers = new HttpHeaders(); for (String headerName : IterableEnumeration.of(servletRequest.getHeaderNames())) { @@ -177,21 +225,62 @@ private HttpHeaders extractHeaders(MockHttpServletRequest servletRequest) { return headers; } - private boolean isNonStandardPort(MockHttpServletRequest request) { - return (SCHEME_HTTP.equals(request.getScheme()) && request.getServerPort() != STANDARD_PORT_HTTP) - || (SCHEME_HTTPS.equals(request.getScheme()) && request.getServerPort() != STANDARD_PORT_HTTPS); + private static void append(StringBuilder sb, String key) { + append(sb, key, ""); } - private String getRequestUri(MockHttpServletRequest request) { - StringWriter uriWriter = new StringWriter(); - PrintWriter printer = new PrintWriter(uriWriter); + private static void append(StringBuilder sb, String key, String value) { + doAppend(sb, urlEncode(key) + "=" + urlEncode(value)); + } - printer.printf("%s://%s", request.getScheme(), request.getServerName()); - if (isNonStandardPort(request)) { - printer.printf(":%d", request.getServerPort()); + private static void doAppend(StringBuilder sb, String toAppend) { + if (sb.length() > 0) { + sb.append("&"); } - printer.print(request.getRequestURI()); - return uriWriter.toString(); + sb.append(toAppend); + } + + private static String urlEncode(String s) { + if (!StringUtils.hasLength(s)) { + return ""; + } + return URLEncoder.encode(s, StandardCharsets.UTF_8); + } + + private static MultiValueMap parse(String query) { + MultiValueMap parameters = new LinkedMultiValueMap<>(); + if (!StringUtils.hasLength(query)) { + return parameters; + } + try (Scanner scanner = new Scanner(query)) { + scanner.useDelimiter("&"); + while (scanner.hasNext()) { + processParameter(scanner.next(), parameters); + } + } + return parameters; + } + + private static void processParameter(String parameter, MultiValueMap parameters) { + String[] components = parameter.split("="); + if (components.length > 0 && components.length < 3) { + if (components.length == 2) { + String name = components[0]; + String value = components[1]; + parameters.add(decode(name), decode(value)); + } + else { + List values = parameters.computeIfAbsent(components[0], (p) -> new LinkedList<>()); + values.add(""); + } + } + else { + throw new IllegalArgumentException("The parameter '" + parameter + "' is malformed"); + } + } + + private static String decode(String encoded) { + return URLDecoder.decode(encoded, StandardCharsets.US_ASCII); } } diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverter.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverter.java index 93e6b1f47..701d86998 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverter.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -16,13 +16,20 @@ package org.springframework.restdocs.mockmvc; -import javax.servlet.http.Cookie; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import jakarta.servlet.http.Cookie; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatusCode; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.ResponseConverter; +import org.springframework.restdocs.operation.ResponseCookie; import org.springframework.util.StringUtils; /** @@ -30,13 +37,27 @@ * {@link MockHttpServletResponse}. * * @author Andy Wilkinson + * @author Clyde Stubbs */ class MockMvcResponseConverter implements ResponseConverter { @Override public OperationResponse convert(MockHttpServletResponse mockResponse) { - return new OperationResponseFactory().create(mockResponse.getStatus(), extractHeaders(mockResponse), - mockResponse.getContentAsByteArray()); + HttpHeaders headers = extractHeaders(mockResponse); + Collection cookies = extractCookies(mockResponse); + return new OperationResponseFactory().create(HttpStatusCode.valueOf(mockResponse.getStatus()), headers, + mockResponse.getContentAsByteArray(), cookies); + } + + private Collection extractCookies(MockHttpServletResponse mockResponse) { + if (mockResponse.getCookies() == null || mockResponse.getCookies().length == 0) { + return Collections.emptyList(); + } + List cookies = new ArrayList<>(); + for (Cookie cookie : mockResponse.getCookies()) { + cookies.add(new ResponseCookie(cookie.getName(), cookie.getValue())); + } + return cookies; } private HttpHeaders extractHeaders(MockHttpServletResponse response) { @@ -47,7 +68,7 @@ private HttpHeaders extractHeaders(MockHttpServletResponse response) { } } - if (response.getCookies() != null && !headers.containsKey(HttpHeaders.SET_COOKIE)) { + if (response.getCookies() != null && !headers.containsHeader(HttpHeaders.SET_COOKIE)) { for (Cookie cookie : response.getCookies()) { headers.add(HttpHeaders.SET_COOKIE, generateSetCookieHeader(cookie)); } diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java index 73eeb9997..9c495ebb3 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2024 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. @@ -16,8 +16,10 @@ package org.springframework.restdocs.mockmvc; +import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import java.util.function.Function; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.restdocs.RestDocumentationContext; @@ -27,6 +29,7 @@ import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder; import org.springframework.test.web.servlet.setup.MockMvcConfigurer; +import org.springframework.util.ReflectionUtils; import org.springframework.web.context.WebApplicationContext; /** @@ -85,6 +88,26 @@ public MockMvcOperationPreprocessorsConfigurer operationPreprocessors() { private final class ConfigurerApplyingRequestPostProcessor implements RequestPostProcessor { + private static final Function urlTemplateExtractor; + + static { + Function fromRequestAttribute = ( + request) -> (String) request.getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE); + Function extractor; + try { + Method accessorMethod = MockHttpServletRequest.class.getMethod("getUriTemplate"); + extractor = (request) -> { + String urlTemplate = fromRequestAttribute.apply(request); + return (urlTemplate != null) ? urlTemplate + : (String) ReflectionUtils.invokeMethod(accessorMethod, request); + }; + } + catch (Exception ex) { + extractor = fromRequestAttribute; + } + urlTemplateExtractor = extractor; + } + private final RestDocumentationContextProvider contextManager; private ConfigurerApplyingRequestPostProcessor(RestDocumentationContextProvider contextManager) { @@ -97,7 +120,7 @@ public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) Map configuration = new HashMap<>(); configuration.put(MockHttpServletRequest.class.getName(), request); configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, - request.getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)); + urlTemplateExtractor.apply(request)); configuration.put(RestDocumentationContext.class.getName(), context); request.setAttribute(RestDocumentationResultHandler.ATTRIBUTE_NAME_CONFIGURATION, configuration); MockMvcRestDocumentationConfigurer.this.apply(configuration, context); diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java index f61e50ff8..30f302041 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuilders.java @@ -215,30 +215,6 @@ public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, URI u return MockMvcRequestBuilders.request(httpMethod, uri); } - /** - * Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request. - * The url template will be captured and made available for documentation. - * @param urlTemplate a URL template; the resulting URL will be encoded - * @param urlVariables zero or more URL variables - * @return the builder for the file upload request - * @deprecated since 2.0.6 in favor of {@link #multipart(String, Object...)} - */ - @Deprecated - public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables) { - return multipart(urlTemplate, urlVariables); - } - - /** - * Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request. - * @param uri the URL - * @return the builder for the file upload request - * @deprecated since 2.0.6 in favor of {@link #multipart(URI)} - */ - @Deprecated - public static MockMultipartHttpServletRequestBuilder fileUpload(URI uri) { - return multipart(uri); - } - /** * Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request. * The URL template will be captured and made available for documentation. diff --git a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java index e5a0c37dd..33b2f3d85 100644 --- a/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java +++ b/spring-restdocs-mockmvc/src/main/java/org/springframework/restdocs/mockmvc/RestDocumentationResultHandler.java @@ -48,7 +48,7 @@ public class RestDocumentationResultHandler implements ResultHandler { } @Override - public void handle(MvcResult result) throws Exception { + public void handle(MvcResult result) { this.delegate.handle(result.getRequest(), result.getResponse(), retrieveConfiguration(result)); } diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java index 6286cb553..c0d3c1fc3 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -22,9 +22,8 @@ import java.util.Arrays; import java.util.Iterator; -import javax.servlet.http.Part; - -import org.junit.Test; +import jakarta.servlet.http.Part; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; @@ -38,6 +37,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -46,19 +46,19 @@ * * @author Andy Wilkinson */ -public class MockMvcRequestConverterTests { +class MockMvcRequestConverterTests { private final MockMvcRequestConverter factory = new MockMvcRequestConverter(); @Test - public void httpRequest() { + void httpRequest() { OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test - public void httpRequestWithCustomPort() { + void httpRequestWithCustomPort() { MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); mockRequest.setServerPort(8080); OperationRequest request = this.factory.convert(mockRequest); @@ -67,27 +67,27 @@ public void httpRequestWithCustomPort() { } @Test - public void requestWithContextPath() { + void requestWithContextPath() { OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo/bar").contextPath("/foo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo/bar")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test - public void requestWithHeaders() { + void requestWithHeaders() { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.get("/foo").header("a", "alpha", "apple").header("b", "bravo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); - assertThat(request.getHeaders()).containsEntry("a", Arrays.asList("alpha", "apple")); - assertThat(request.getHeaders()).containsEntry("b", Arrays.asList("bravo")); + assertThat(request.getHeaders().headerSet()).contains(entry("a", Arrays.asList("alpha", "apple")), + entry("b", Arrays.asList("bravo"))); } @Test - public void requestWithCookies() { + void requestWithCookies() { OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo") - .cookie(new javax.servlet.http.Cookie("cookieName1", "cookieVal1"), - new javax.servlet.http.Cookie("cookieName2", "cookieVal2"))); + .cookie(new jakarta.servlet.http.Cookie("cookieName1", "cookieVal1"), + new jakarta.servlet.http.Cookie("cookieName2", "cookieVal2"))); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); assertThat(request.getCookies().size()).isEqualTo(2); @@ -104,7 +104,7 @@ public void requestWithCookies() { } @Test - public void httpsRequest() { + void httpsRequest() { MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); mockRequest.setScheme("https"); mockRequest.setServerPort(443); @@ -114,7 +114,7 @@ public void httpsRequest() { } @Test - public void httpsRequestWithCustomPort() { + void httpsRequestWithCustomPort() { MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); mockRequest.setScheme("https"); mockRequest.setServerPort(8443); @@ -124,39 +124,43 @@ public void httpsRequestWithCustomPort() { } @Test - public void getRequestWithParametersProducesUriWithQueryString() { + void getRequestWithParametersProducesUriWithQueryString() { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.get("/foo").param("a", "alpha", "apple").param("b", "br&vo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); - assertThat(request.getParameters().size()).isEqualTo(2); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); - assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test - public void getRequestWithQueryStringPopulatesParameters() { - OperationRequest request = createOperationRequest(MockMvcRequestBuilders.get("/foo?a=alpha&b=bravo")); + void getRequestWithQueryString() { + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/foo?a=alpha&b=bravo"); + OperationRequest request = createOperationRequest(builder); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); - assertThat(request.getParameters().size()).isEqualTo(2); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); - assertThat(request.getParameters()).containsEntry("b", Arrays.asList("bravo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test - public void postRequestWithParameters() { + void postRequestWithParametersCreatesFormUrlEncodedContent() { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.post("/foo").param("a", "alpha", "apple").param("b", "br&vo")); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); - assertThat(request.getParameters().size()).isEqualTo(2); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); - assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); + assertThat(request.getContentAsString()).isEqualTo("a=alpha&a=apple&b=br%26vo"); + assertThat(request.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED); + } + + @Test + void postRequestWithParametersAndQueryStringCreatesFormUrlEncodedContentWithoutDuplication() { + OperationRequest request = createOperationRequest( + MockMvcRequestBuilders.post("/foo?a=alpha").param("a", "apple").param("b", "br&vo")); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getContentAsString()).isEqualTo("a=apple&b=br%26vo"); + assertThat(request.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED); } @Test - public void mockMultipartFileUpload() { + void mockMultipartFileUpload() { OperationRequest request = createOperationRequest(MockMvcRequestBuilders.multipart("/foo") .file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }))); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); @@ -171,7 +175,7 @@ public void mockMultipartFileUpload() { } @Test - public void mockMultipartFileUploadWithContentType() { + void mockMultipartFileUploadWithContentType() { OperationRequest request = createOperationRequest(MockMvcRequestBuilders.multipart("/foo") .file(new MockMultipartFile("file", "original", "image/png", new byte[] { 1, 2, 3, 4 }))); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); @@ -185,7 +189,7 @@ public void mockMultipartFileUploadWithContentType() { } @Test - public void requestWithPart() throws IOException { + void requestWithPart() throws IOException { MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); Part mockPart = mock(Part.class); given(mockPart.getHeaderNames()).willReturn(Arrays.asList("a", "b")); @@ -207,7 +211,7 @@ public void requestWithPart() throws IOException { } @Test - public void requestWithPartWithContentType() throws IOException { + void requestWithPartWithContentType() throws IOException { MockHttpServletRequest mockRequest = MockMvcRequestBuilders.get("/foo").buildRequest(new MockServletContext()); Part mockPart = mock(Part.class); given(mockPart.getHeaderNames()).willReturn(Arrays.asList("a", "b")); diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java index ef9b85c28..e13bb03be 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -18,29 +18,31 @@ import java.util.Collections; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; - -import org.junit.Test; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.restdocs.operation.OperationResponse; +import org.springframework.restdocs.operation.ResponseCookie; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; /** * Tests for {@link MockMvcResponseConverter}. * * @author Tomasz Kopczynski */ -public class MockMvcResponseConverterTests { +class MockMvcResponseConverterTests { private final MockMvcResponseConverter factory = new MockMvcResponseConverter(); @Test - public void basicResponse() { + void basicResponse() { MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(HttpServletResponse.SC_OK); OperationResponse operationResponse = this.factory.convert(response); @@ -48,7 +50,7 @@ public void basicResponse() { } @Test - public void responseWithCookie() { + void responseWithCookie() { MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(HttpServletResponse.SC_OK); Cookie cookie = new Cookie("name", "value"); @@ -56,18 +58,19 @@ public void responseWithCookie() { cookie.setHttpOnly(true); response.addCookie(cookie); OperationResponse operationResponse = this.factory.convert(response); - assertThat(operationResponse.getHeaders()).hasSize(1); - assertThat(operationResponse.getHeaders()).containsEntry(HttpHeaders.SET_COOKIE, - Collections.singletonList("name=value; Domain=localhost; HttpOnly")); + assertThat(operationResponse.getHeaders().headerSet()).containsOnly( + entry(HttpHeaders.SET_COOKIE, Collections.singletonList("name=value; Domain=localhost; HttpOnly"))); + assertThat(operationResponse.getCookies()).hasSize(1); + assertThat(operationResponse.getCookies()).first().extracting(ResponseCookie::getName).isEqualTo("name"); + assertThat(operationResponse.getCookies()).first().extracting(ResponseCookie::getValue).isEqualTo("value"); } @Test - public void responseWithCustomStatus() { + void responseWithCustomStatus() { MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(600); OperationResponse operationResponse = this.factory.convert(response); - assertThat(operationResponse.getStatus()).isNull(); - assertThat(operationResponse.getStatusCode()).isEqualTo(600); + assertThat(operationResponse.getStatus()).isEqualTo(HttpStatusCode.valueOf(600)); } } diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java index a135125cf..dfb2debc9 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -16,12 +16,19 @@ package org.springframework.restdocs.mockmvc; -import org.junit.Rule; -import org.junit.Test; +import java.lang.reflect.Method; +import java.util.Map; + +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.util.ReflectionUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -35,24 +42,22 @@ * @author Andy Wilkinson * @author Dmitriy Mayboroda */ -public class MockMvcRestDocumentationConfigurerTests { +@ExtendWith(RestDocumentationExtension.class) +class MockMvcRestDocumentationConfigurerTests { private MockHttpServletRequest request = new MockHttpServletRequest(); - @Rule - public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - @Test - public void defaultConfiguration() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation) + void defaultConfiguration(RestDocumentationContextProvider restDocumentation) { + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(restDocumentation) .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertUriConfiguration("http", "localhost", 8080); } @Test - public void customScheme() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + void customScheme(RestDocumentationContextProvider restDocumentation) { + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(restDocumentation).uris() .withScheme("https") .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); @@ -60,8 +65,8 @@ public void customScheme() { } @Test - public void customHost() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + void customHost(RestDocumentationContextProvider restDocumentation) { + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(restDocumentation).uris() .withHost("api.example.com") .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); @@ -69,8 +74,8 @@ public void customHost() { } @Test - public void customPort() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + void customPort(RestDocumentationContextProvider restDocumentation) { + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(restDocumentation).uris() .withPort(8081) .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); @@ -78,14 +83,41 @@ public void customPort() { } @Test - public void noContentLengthHeaderWhenRequestHasNotContent() { - RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(this.restDocumentation).uris() + void noContentLengthHeaderWhenRequestHasNotContent(RestDocumentationContextProvider restDocumentation) { + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(restDocumentation).uris() .withPort(8081) .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); assertThat(this.request.getHeader("Content-Length")).isNull(); } + @Test + @SuppressWarnings("unchecked") + void uriTemplateFromRequestAttribute(RestDocumentationContextProvider restDocumentation) { + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(restDocumentation) + .beforeMockMvcCreated(null, null); + this.request.setAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{a}/{b}"); + postProcessor.postProcessRequest(this.request); + Map configuration = (Map) this.request + .getAttribute(RestDocumentationResultHandler.ATTRIBUTE_NAME_CONFIGURATION); + assertThat(configuration).containsEntry(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{a}/{b}"); + } + + @Test + @SuppressWarnings("unchecked") + void uriTemplateFromRequest(RestDocumentationContextProvider restDocumentation) { + Method setUriTemplate = ReflectionUtils.findMethod(MockHttpServletRequest.class, "setUriTemplate", + String.class); + Assumptions.assumeFalse(setUriTemplate == null); + RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer(restDocumentation) + .beforeMockMvcCreated(null, null); + ReflectionUtils.invokeMethod(setUriTemplate, this.request, "{a}/{b}"); + postProcessor.postProcessRequest(this.request); + Map configuration = (Map) this.request + .getAttribute(RestDocumentationResultHandler.ATTRIBUTE_NAME_CONFIGURATION); + assertThat(configuration).containsEntry(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{a}/{b}"); + } + private void assertUriConfiguration(String scheme, String host, int port) { assertThat(scheme).isEqualTo(this.request.getScheme()); assertThat(host).isEqualTo(this.request.getServerName()); diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java index 81a5b5065..49460f1e3 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -31,15 +31,13 @@ import java.util.Set; import java.util.regex.Pattern; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; - +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; import org.assertj.core.api.Condition; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -48,7 +46,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationIntegrationTests.TestConfiguration; import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateFormats; @@ -57,7 +56,7 @@ import org.springframework.restdocs.testfixtures.SnippetConditions.HttpRequestCondition; import org.springframework.restdocs.testfixtures.SnippetConditions.HttpResponseCondition; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; @@ -81,10 +80,10 @@ import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.operation.preprocess.Preprocessors.maskLinks; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.replacePattern; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; @@ -93,7 +92,7 @@ import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -107,29 +106,30 @@ * @author Tomasz Kopczynski * @author Filip Hrisafov */ -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig @WebAppConfiguration +@ExtendWith(RestDocumentationExtension.class) @ContextConfiguration(classes = TestConfiguration.class) public class MockMvcRestDocumentationIntegrationTests { - @Rule - public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); + private RestDocumentationContextProvider restDocumentation; @Autowired private WebApplicationContext context; - @Before - public void deleteSnippets() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { + this.restDocumentation = restDocumentation; FileSystemUtils.deleteRecursively(new File("build/generated-snippets")); } - @After - public void clearOutputDirSystemProperty() { + @AfterEach + void clearOutputDirSystemProperty() { System.clearProperty("org.springframework.restdocs.outputDir"); } @Test - public void basicSnippetGeneration() throws Exception { + void basicSnippetGeneration() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation).snippets().withEncoding("UTF-8")) .build(); @@ -141,7 +141,19 @@ public void basicSnippetGeneration() throws Exception { } @Test - public void markdownSnippetGeneration() throws Exception { + void getRequestWithBody() throws Exception { + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation).snippets().withEncoding("UTF-8")) + .build(); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON).content("some body content")) + .andExpect(status().isOk()) + .andDo(document("get-request-with-body")); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/get-request-with-body"), "http-request.adoc", + "http-response.adoc", "curl-request.adoc"); + } + + @Test + void markdownSnippetGeneration() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation).snippets() .withEncoding("UTF-8") @@ -155,7 +167,7 @@ public void markdownSnippetGeneration() throws Exception { } @Test - public void curlSnippetWithContent() throws Exception { + void curlSnippetWithContent() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -169,7 +181,7 @@ public void curlSnippetWithContent() throws Exception { } @Test - public void curlSnippetWithCookies() throws Exception { + void curlSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -183,11 +195,11 @@ public void curlSnippetWithCookies() throws Exception { } @Test - public void curlSnippetWithQueryStringOnPost() throws Exception { + void curlSnippetWithQueryStringOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); - mockMvc.perform(post("/?foo=bar").param("foo", "bar").param("a", "alpha").accept(MediaType.APPLICATION_JSON)) + mockMvc.perform(post("/?foo=bar").param("a", "alpha").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("curl-snippet-with-query-string")); assertThat(new File("build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc")) @@ -197,7 +209,7 @@ public void curlSnippetWithQueryStringOnPost() throws Exception { } @Test - public void curlSnippetWithEmptyParameterQueryString() throws Exception { + void curlSnippetWithEmptyParameterQueryString() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -211,7 +223,7 @@ public void curlSnippetWithEmptyParameterQueryString() throws Exception { } @Test - public void curlSnippetWithContentAndParametersOnPost() throws Exception { + void curlSnippetWithContentAndParametersOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -225,7 +237,7 @@ public void curlSnippetWithContentAndParametersOnPost() throws Exception { } @Test - public void httpieSnippetWithContent() throws Exception { + void httpieSnippetWithContent() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -238,7 +250,7 @@ public void httpieSnippetWithContent() throws Exception { } @Test - public void httpieSnippetWithCookies() throws Exception { + void httpieSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -252,21 +264,21 @@ public void httpieSnippetWithCookies() throws Exception { } @Test - public void httpieSnippetWithQueryStringOnPost() throws Exception { + void httpieSnippetWithQueryStringOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); - mockMvc.perform(post("/?foo=bar").param("foo", "bar").param("a", "alpha").accept(MediaType.APPLICATION_JSON)) + mockMvc.perform(post("/?foo=bar").param("a", "alpha").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("httpie-snippet-with-query-string")); assertThat(new File("build/generated-snippets/httpie-snippet-with-query-string/httpie-request.adoc")) .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") - .withContent(String.format("$ http " + "--form POST 'http://localhost:8080/?foo=bar' \\%n" + .withContent(String.format("$ http --form POST 'http://localhost:8080/?foo=bar' \\%n" + " 'Accept:application/json' \\%n 'a=alpha'")))); } @Test - public void httpieSnippetWithContentAndParametersOnPost() throws Exception { + void httpieSnippetWithContentAndParametersOnPost() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -281,7 +293,7 @@ public void httpieSnippetWithContentAndParametersOnPost() throws Exception { } @Test - public void linksSnippet() throws Exception { + void linksSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -294,7 +306,7 @@ public void linksSnippet() throws Exception { } @Test - public void pathParametersSnippet() throws Exception { + void pathParametersSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -306,19 +318,19 @@ public void pathParametersSnippet() throws Exception { } @Test - public void requestParametersSnippet() throws Exception { + void queryParametersSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) - .andDo(document("links", requestParameters(parameterWithName("foo").description("The description")))); + .andDo(document("links", queryParameters(parameterWithName("foo").description("The description")))); assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", - "http-response.adoc", "curl-request.adoc", "request-parameters.adoc"); + "http-response.adoc", "curl-request.adoc", "query-parameters.adoc"); } @Test - public void requestFieldsSnippet() throws Exception { + void requestFieldsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -330,7 +342,7 @@ public void requestFieldsSnippet() throws Exception { } @Test - public void requestPartsSnippet() throws Exception { + void requestPartsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -342,7 +354,7 @@ public void requestPartsSnippet() throws Exception { } @Test - public void responseFieldsSnippet() throws Exception { + void responseFieldsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -355,7 +367,7 @@ public void responseFieldsSnippet() throws Exception { } @Test - public void responseWithSetCookie() throws Exception { + void responseWithSetCookie() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -369,7 +381,7 @@ public void responseWithSetCookie() throws Exception { } @Test - public void parameterizedOutputDirectory() throws Exception { + void parameterizedOutputDirectory() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -381,7 +393,7 @@ public void parameterizedOutputDirectory() throws Exception { } @Test - public void multiStep() throws Exception { + void multiStep() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .alwaysDo(document("{method-name}-{step}")) @@ -399,7 +411,7 @@ public void multiStep() throws Exception { } @Test - public void alwaysDoWithAdditionalSnippets() throws Exception { + void alwaysDoWithAdditionalSnippets() throws Exception { RestDocumentationResultHandler documentation = document("{method-name}-{step}"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) @@ -413,7 +425,7 @@ public void alwaysDoWithAdditionalSnippets() throws Exception { } @Test - public void preprocessedRequest() throws Exception { + void preprocessedRequest() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -427,7 +439,8 @@ public void preprocessedRequest() throws Exception { .andExpect(status().isOk()) .andDo(document("original-request")) .andDo(document("preprocessed-request", - preprocessRequest(prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), + preprocessRequest(prettyPrint(), + modifyHeaders().remove("a").remove(HttpHeaders.HOST).remove(HttpHeaders.CONTENT_LENGTH), replacePattern(pattern, "\"<>\"")))) .andReturn(); HttpRequestCondition originalRequest = httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/"); @@ -455,11 +468,12 @@ public void preprocessedRequest() throws Exception { } @Test - public void defaultPreprocessedRequest() throws Exception { + void defaultPreprocessedRequest() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withRequestDefaults(prettyPrint(), removeHeaders("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH), + .withRequestDefaults(prettyPrint(), + modifyHeaders().remove("a").remove(HttpHeaders.HOST).remove(HttpHeaders.CONTENT_LENGTH), replacePattern(pattern, "\"<>\""))) .build(); @@ -485,7 +499,7 @@ public void defaultPreprocessedRequest() throws Exception { } @Test - public void preprocessedResponse() throws Exception { + void preprocessedResponse() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -495,8 +509,8 @@ public void preprocessedResponse() throws Exception { mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("original-response")) - .andDo(document("preprocessed-response", preprocessResponse(prettyPrint(), maskLinks(), removeHeaders("a"), - replacePattern(pattern, "\"<>\"")))); + .andDo(document("preprocessed-response", preprocessResponse(prettyPrint(), maskLinks(), + modifyHeaders().remove("a"), replacePattern(pattern, "\"<>\"")))); String original = "{\"a\":\"alpha\",\"links\":[{\"rel\":\"rel\"," + "\"href\":\"href\"}]}"; assertThat(new File("build/generated-snippets/original-response/http-response.adoc")) @@ -514,11 +528,11 @@ public void preprocessedResponse() throws Exception { } @Test - public void defaultPreprocessedResponse() throws Exception { + void defaultPreprocessedResponse() throws Exception { Pattern pattern = Pattern.compile("(\"alpha\")"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation).operationPreprocessors() - .withResponseDefaults(prettyPrint(), maskLinks(), removeHeaders("a"), + .withResponseDefaults(prettyPrint(), maskLinks(), modifyHeaders().remove("a"), replacePattern(pattern, "\"<>\""))) .build(); @@ -536,7 +550,7 @@ public void defaultPreprocessedResponse() throws Exception { } @Test - public void customSnippetTemplate() throws Exception { + void customSnippetTemplate() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -558,7 +572,7 @@ public void customSnippetTemplate() throws Exception { } @Test - public void customContextPath() throws Exception { + void customContextPath() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -572,7 +586,7 @@ public void customContextPath() throws Exception { } @Test - public void exceptionShouldBeThrownWhenCallDocumentMockMvcNotConfigured() { + void exceptionShouldBeThrownWhenCallDocumentMockMvcNotConfigured() { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); assertThatThrownBy(() -> mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)).andDo(document("basic"))) .isInstanceOf(IllegalStateException.class) @@ -582,7 +596,7 @@ public void exceptionShouldBeThrownWhenCallDocumentMockMvcNotConfigured() { } @Test - public void exceptionShouldBeThrownWhenCallDocumentSnippetsMockMvcNotConfigured() { + void exceptionShouldBeThrownWhenCallDocumentSnippetsMockMvcNotConfigured() { RestDocumentationResultHandler documentation = document("{method-name}-{step}"); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); assertThatThrownBy(() -> mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) @@ -593,7 +607,7 @@ public void exceptionShouldBeThrownWhenCallDocumentSnippetsMockMvcNotConfigured( } @Test - public void multiPart() throws Exception { + void multiPart() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); @@ -609,7 +623,7 @@ private void assertExpectedSnippetFilesExist(File directory, String... snippets) } private Condition content(final Condition delegate) { - return new Condition() { + return new Condition<>() { @Override public boolean matches(File value) { @@ -641,9 +655,9 @@ private HttpResponseCondition httpResponse(TemplateFormat format, HttpStatus sta /** * Test configuration that enables Spring MVC. */ - @Configuration @EnableWebMvc - static class TestConfiguration { + @Configuration(proxyBeanMethods = false) + static final class TestConfiguration { @Bean TestController testController() { @@ -653,7 +667,7 @@ TestController testController() { } @RestController - private static class TestController { + private static final class TestController { @RequestMapping(value = "/", produces = "application/json;charset=UTF-8") ResponseEntity> foo() { diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java index 018f7a5a9..f689778a6 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,9 +18,8 @@ import java.net.URI; -import javax.servlet.ServletContext; - -import org.junit.Test; +import jakarta.servlet.ServletContext; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; @@ -30,9 +29,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.fileUpload; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.head; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.multipart; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.options; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; @@ -45,100 +44,98 @@ * @author Andy Wilkinson * */ -public class RestDocumentationRequestBuildersTests { +class RestDocumentationRequestBuildersTests { private final ServletContext servletContext = new MockServletContext(); @Test - public void getTemplate() { + void getTemplate() { assertTemplate(get("/{template}", "t"), HttpMethod.GET); } @Test - public void getUri() { + void getUri() { assertUri(get(URI.create("/uri")), HttpMethod.GET); } @Test - public void postTemplate() { + void postTemplate() { assertTemplate(post("/{template}", "t"), HttpMethod.POST); } @Test - public void postUri() { + void postUri() { assertUri(post(URI.create("/uri")), HttpMethod.POST); } @Test - public void putTemplate() { + void putTemplate() { assertTemplate(put("/{template}", "t"), HttpMethod.PUT); } @Test - public void putUri() { + void putUri() { assertUri(put(URI.create("/uri")), HttpMethod.PUT); } @Test - public void patchTemplate() { + void patchTemplate() { assertTemplate(patch("/{template}", "t"), HttpMethod.PATCH); } @Test - public void patchUri() { + void patchUri() { assertUri(patch(URI.create("/uri")), HttpMethod.PATCH); } @Test - public void deleteTemplate() { + void deleteTemplate() { assertTemplate(delete("/{template}", "t"), HttpMethod.DELETE); } @Test - public void deleteUri() { + void deleteUri() { assertUri(delete(URI.create("/uri")), HttpMethod.DELETE); } @Test - public void optionsTemplate() { + void optionsTemplate() { assertTemplate(options("/{template}", "t"), HttpMethod.OPTIONS); } @Test - public void optionsUri() { + void optionsUri() { assertUri(options(URI.create("/uri")), HttpMethod.OPTIONS); } @Test - public void headTemplate() { + void headTemplate() { assertTemplate(head("/{template}", "t"), HttpMethod.HEAD); } @Test - public void headUri() { + void headUri() { assertUri(head(URI.create("/uri")), HttpMethod.HEAD); } @Test - public void requestTemplate() { + void requestTemplate() { assertTemplate(request(HttpMethod.GET, "/{template}", "t"), HttpMethod.GET); } @Test - public void requestUri() { + void requestUri() { assertUri(request(HttpMethod.GET, URI.create("/uri")), HttpMethod.GET); } @Test - @SuppressWarnings("deprecation") - public void fileUploadTemplate() { - assertTemplate(fileUpload("/{template}", "t"), HttpMethod.POST); + void multipartTemplate() { + assertTemplate(multipart("/{template}", "t"), HttpMethod.POST); } @Test - @SuppressWarnings("deprecation") - public void fileUploadUri() { - assertUri(fileUpload(URI.create("/uri")), HttpMethod.POST); + void multipartUri() { + assertUri(multipart(URI.create("/uri")), HttpMethod.POST); } private void assertTemplate(MockHttpServletRequestBuilder builder, HttpMethod httpMethod) { diff --git a/spring-restdocs-platform/build.gradle b/spring-restdocs-platform/build.gradle index a5ae8aa67..5e0404db0 100644 --- a/spring-restdocs-platform/build.gradle +++ b/spring-restdocs-platform/build.gradle @@ -8,24 +8,24 @@ javaPlatform { dependencies { constraints { - api("com.fasterxml.jackson.core:jackson-databind:2.9.5") api("com.samskivert:jmustache:$jmustacheVersion") - api("jakarta.xml.bind:jakarta.xml.bind-api:2.3.3") - api("javax.servlet:javax.servlet-api:3.1.0") - api("javax.validation:validation-api:2.0.0.Final") - api("junit:junit:4.12") - api("io.rest-assured:rest-assured:3.0.7") - api("org.apache.pdfbox:pdfbox:2.0.7") - api("org.assertj:assertj-core:3.11.1") - api("org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.18") + api("jakarta.servlet:jakarta.servlet-api:6.1.0") + api("jakarta.validation:jakarta.validation-api:3.1.0") + api("org.apache.pdfbox:pdfbox:2.0.27") + api("org.apache.tomcat.embed:tomcat-embed-core:11.0.2") + api("org.apache.tomcat.embed:tomcat-embed-el:11.0.2") + api("org.apiguardian:apiguardian-api:1.1.2") + api("org.asciidoctor:asciidoctorj:3.0.0") + api("org.asciidoctor:asciidoctorj-pdf:2.3.19") + api("org.assertj:assertj-core:3.23.1") api("org.hamcrest:hamcrest-core:1.3") api("org.hamcrest:hamcrest-library:1.3") - api("org.hibernate.validator:hibernate-validator:6.0.9.Final") - api("org.javamoney:moneta:1.1") - api("org.jruby:jruby-complete:9.1.13.0") - api("org.junit.jupiter:junit-jupiter-api:5.0.0") - api("org.mockito:mockito-core:4.2.0") - api("org.synchronoss.cloud:nio-multipart-parser:1.1.0") + api("org.hibernate.validator:hibernate-validator:9.0.0.CR1") + api("org.javamoney:moneta:1.4.2") } - api(enforcedPlatform("org.springframework:spring-framework-bom:$springVersion")) + api(enforcedPlatform("com.fasterxml.jackson:jackson-bom:2.14.0")) + api(enforcedPlatform("io.rest-assured:rest-assured-bom:5.2.1")) + api(enforcedPlatform("org.mockito:mockito-bom:4.9.0")) + api(enforcedPlatform("org.junit:junit-bom:5.13.0")) + api(enforcedPlatform("org.springframework:spring-framework-bom:$springFrameworkVersion")) } diff --git a/spring-restdocs-restassured/build.gradle b/spring-restdocs-restassured/build.gradle index 3c6f0ecc5..42a05a522 100644 --- a/spring-restdocs-restassured/build.gradle +++ b/spring-restdocs-restassured/build.gradle @@ -1,5 +1,5 @@ plugins { - id "io.spring.compatibility-test" version "0.0.2" + id "io.spring.compatibility-test" version "0.0.4" id "java-library" id "maven-publish" } @@ -8,27 +8,24 @@ description = "Spring REST Docs REST Assured" dependencies { api(project(":spring-restdocs-core")) - api("io.rest-assured:rest-assured") { - exclude group: "commons-logging", module: "commons-logging" - exclude group: "javax.xml.bind", module: "jaxb-api" - } - implementation("jakarta.xml.bind:jakarta.xml.bind-api") + api("io.rest-assured:rest-assured") implementation("org.springframework:spring-web") internal(platform(project(":spring-restdocs-platform"))) + testCompileOnly("org.apiguardian:apiguardian-api") testImplementation(testFixtures(project(":spring-restdocs-core"))) testImplementation("com.fasterxml.jackson.core:jackson-databind") - testImplementation("junit:junit") - testImplementation("org.apache.tomcat.embed:tomcat-embed-core:8.5.13") - testImplementation("org.assertj:assertj-core") - testImplementation("org.hamcrest:hamcrest-library") - testImplementation("org.mockito:mockito-core") + testImplementation("org.apache.tomcat.embed:tomcat-embed-core") +} + +tasks.named("test") { + useJUnitPlatform(); } compatibilityTest { dependency("REST Assured") { restAssured -> restAssured.groupId = "io.rest-assured" - restAssured.versions = ["4.0.0", "4.1.2", "4.2.0", "4.3.1"] + restAssured.versions = ["5.3.+", "5.4.+", "5.5.+"] } } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredOperationPreprocessorsConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredOperationPreprocessorsConfigurer.java similarity index 93% rename from spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredOperationPreprocessorsConfigurer.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredOperationPreprocessorsConfigurer.java index e5d539ecf..cef1e925e 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredOperationPreprocessorsConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredOperationPreprocessorsConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import io.restassured.filter.Filter; import io.restassured.filter.FilterContext; @@ -26,7 +26,7 @@ /** * A configurer that can be used to configure the operation preprocessors when using REST - * Assured 3. + * Assured. * * @author Filip Hrisafov * @since 2.0.0 diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRequestConverter.java similarity index 74% rename from spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverter.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRequestConverter.java index 6356e437e..091d51ecc 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRequestConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -14,15 +14,18 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.Map.Entry; import io.restassured.http.Cookie; @@ -37,17 +40,18 @@ import org.springframework.restdocs.operation.OperationRequestFactory; import org.springframework.restdocs.operation.OperationRequestPart; import org.springframework.restdocs.operation.OperationRequestPartFactory; -import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestConverter; import org.springframework.restdocs.operation.RequestCookie; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; +import org.springframework.util.StringUtils; /** * A converter for creating an {@link OperationRequest} from a REST Assured * {@link FilterableRequestSpecification}. * * @author Andy Wilkinson + * @author Clyde Stubbs */ class RestAssuredRequestConverter implements RequestConverter { @@ -55,7 +59,7 @@ class RestAssuredRequestConverter implements RequestConverter extractCookies(FilterableRequestSpecification requestSpec) { @@ -67,7 +71,36 @@ private Collection extractCookies(FilterableRequestSpecification } private byte[] extractContent(FilterableRequestSpecification requestSpec) { - return convertContent(requestSpec.getBody()); + Object body = requestSpec.getBody(); + if (body != null) { + return convertContent(body); + } + StringBuilder parameters = new StringBuilder(); + if ("POST".equals(requestSpec.getMethod())) { + appendParameters(parameters, requestSpec.getRequestParams()); + } + if (!"GET".equals(requestSpec.getMethod())) { + appendParameters(parameters, requestSpec.getFormParams()); + } + return parameters.toString().getBytes(StandardCharsets.ISO_8859_1); + } + + private void appendParameters(StringBuilder content, Map parameters) { + for (Entry entry : parameters.entrySet()) { + String name = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof Iterable) { + for (Object v : (Iterable) value) { + append(content, name, v.toString()); + } + } + else if (value != null) { + append(content, name, value.toString()); + } + else { + append(content, name); + } + } } private byte[] convertContent(Object content) { @@ -130,28 +163,6 @@ private boolean isAllMediaTypesAcceptHeader(Header header) { return HttpHeaders.ACCEPT.equals(header.getName()) && "*/*".equals(header.getValue()); } - private Parameters extractParameters(FilterableRequestSpecification requestSpec) { - Parameters parameters = new Parameters(); - for (Entry entry : requestSpec.getQueryParams().entrySet()) { - if (entry.getValue() instanceof Collection) { - Collection queryParams = ((Collection) entry.getValue()); - for (Object queryParam : queryParams) { - parameters.add(entry.getKey(), queryParam.toString()); - } - } - else { - parameters.add(entry.getKey(), entry.getValue().toString()); - } - } - for (Entry entry : requestSpec.getRequestParams().entrySet()) { - parameters.add(entry.getKey(), entry.getValue().toString()); - } - for (Entry entry : requestSpec.getFormParams().entrySet()) { - parameters.add(entry.getKey(), entry.getValue().toString()); - } - return parameters; - } - private Collection extractParts(FilterableRequestSpecification requestSpec) { List parts = new ArrayList<>(); for (MultiPartSpecification multiPartSpec : requestSpec.getMultiPartParams()) { @@ -164,4 +175,26 @@ private Collection extractParts(FilterableRequestSpecifica return parts; } + private static void append(StringBuilder sb, String key) { + append(sb, key, ""); + } + + private static void append(StringBuilder sb, String key, String value) { + doAppend(sb, urlEncode(key) + "=" + urlEncode(value)); + } + + private static void doAppend(StringBuilder sb, String toAppend) { + if (sb.length() > 0) { + sb.append("&"); + } + sb.append(toAppend); + } + + private static String urlEncode(String s) { + if (!StringUtils.hasLength(s)) { + return ""; + } + return URLEncoder.encode(s, StandardCharsets.UTF_8); + } + } diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredResponseConverter.java similarity index 58% rename from spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverter.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredResponseConverter.java index e1e31aec2..a049ea1ae 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredResponseConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -14,28 +14,50 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; import io.restassured.http.Header; import io.restassured.response.Response; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatusCode; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.ResponseConverter; +import org.springframework.restdocs.operation.ResponseCookie; /** * A converter for creating an {@link OperationResponse} from a REST Assured * {@link Response}. * * @author Andy Wilkinson + * @author Clyde Stubbs */ class RestAssuredResponseConverter implements ResponseConverter { @Override public OperationResponse convert(Response response) { - return new OperationResponseFactory().create(response.getStatusCode(), extractHeaders(response), - extractContent(response)); + HttpHeaders headers = extractHeaders(response); + Collection cookies = extractCookies(response, headers); + return new OperationResponseFactory().create(HttpStatusCode.valueOf(response.getStatusCode()), + extractHeaders(response), extractContent(response), cookies); + } + + private Collection extractCookies(Response response, HttpHeaders headers) { + if (response.getCookies() == null || response.getCookies().size() == 0) { + return Collections.emptyList(); + } + List cookies = new ArrayList<>(); + for (Map.Entry cookie : response.getCookies().entrySet()) { + cookies.add(new ResponseCookie(cookie.getKey(), cookie.getValue())); + } + return cookies; } private HttpHeaders extractHeaders(Response response) { diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentation.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentation.java similarity index 97% rename from spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentation.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentation.java index b2e899b46..a5309d49d 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentation.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.generate.RestDocumentationGenerator; @@ -23,7 +23,7 @@ import org.springframework.restdocs.snippet.Snippet; /** - * Static factory methods for documenting RESTful APIs using REST Assured 3. + * Static factory methods for documenting RESTful APIs using REST Assured. * * @author Andy Wilkinson * @since 1.2.0 diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurer.java similarity index 93% rename from spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurer.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurer.java index 581911b72..401d02b8c 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import java.util.HashMap; import java.util.Map; @@ -30,7 +30,7 @@ import org.springframework.restdocs.config.RestDocumentationConfigurer; /** - * A REST Assured 3-specific {@link RestDocumentationConfigurer}. + * A REST Assured-specific {@link RestDocumentationConfigurer}. * * @author Andy Wilkinson * @author Filip Hrisafov diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredSnippetConfigurer.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredSnippetConfigurer.java similarity index 92% rename from spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredSnippetConfigurer.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredSnippetConfigurer.java index 0dbebbdb5..250f61fb8 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestAssuredSnippetConfigurer.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestAssuredSnippetConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import io.restassured.filter.Filter; import io.restassured.filter.FilterContext; @@ -26,7 +26,7 @@ /** * A configurer that can be used to configure the generated documentation snippets when - * using REST Assured 3. + * using REST Assured. * * @author Andy Wilkinson * @since 1.2.0 diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestDocumentationFilter.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestDocumentationFilter.java similarity index 96% rename from spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestDocumentationFilter.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestDocumentationFilter.java index 342d69eb1..e52b9c313 100644 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/RestDocumentationFilter.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/RestDocumentationFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import java.util.HashMap; import java.util.Map; @@ -31,7 +31,7 @@ import org.springframework.util.Assert; /** - * A REST Assured 3 {@link Filter} for documenting RESTful APIs. + * A REST Assured {@link Filter} for documenting RESTful APIs. * * @author Andy Wilkinson * @since 1.2.0 diff --git a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/package-info.java similarity index 84% rename from spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java rename to spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/package-info.java index fd03600b7..502b9a02c 100644 --- a/spring-restdocs-asciidoctor-2.x/src/main/java/org/springframework/restdocs/asciidoctor/package-info.java +++ b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured/package-info.java @@ -15,6 +15,6 @@ */ /** - * Support for Asciidoctor. + * Core classes for using Spring REST Docs with REST Assured. */ -package org.springframework.restdocs.asciidoctor; +package org.springframework.restdocs.restassured; diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/RestAssuredPreprocessors.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/RestAssuredPreprocessors.java deleted file mode 100644 index 0605d76d5..000000000 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/RestAssuredPreprocessors.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2014-2018 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.restdocs.restassured3.operation.preprocess; - -import org.springframework.restdocs.operation.Operation; -import org.springframework.restdocs.operation.OperationRequest; -import org.springframework.restdocs.operation.OperationResponse; -import org.springframework.restdocs.operation.preprocess.Preprocessors; -import org.springframework.restdocs.operation.preprocess.UriModifyingOperationPreprocessor; - -/** - * Static factory methods for creating - * {@link org.springframework.restdocs.operation.preprocess.OperationPreprocessor - * OperationPreprocessors} for use with REST Assured 3. They can be applied to an - * {@link Operation Operation's} {@link OperationRequest request} or - * {@link OperationResponse response} before it is documented. - * - * @author Andy Wilkinson - * @since 1.1.0 - * @deprecated since 2.0.1 in favor of {@link Preprocessors} and, specifically, - * {@link Preprocessors#modifyUris()} - */ -@Deprecated -public abstract class RestAssuredPreprocessors { - - private RestAssuredPreprocessors() { - - } - - /** - * Returns a {@code UriModifyingOperationPreprocessor} that will modify URIs in the - * request or response by changing one or more of their host, scheme, and port. - * @return the preprocessor - * @deprecated since 2.0.1 in favor of {@link Preprocessors#modifyUris()} - */ - @Deprecated - public static UriModifyingOperationPreprocessor modifyUris() { - return new UriModifyingOperationPreprocessor(); - } - -} diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessor.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessor.java deleted file mode 100644 index a1ace08d6..000000000 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessor.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2014-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.restdocs.restassured3.operation.preprocess; - -import org.springframework.restdocs.operation.OperationRequest; -import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.OperationResponse; -import org.springframework.restdocs.operation.preprocess.OperationPreprocessor; - -/** - * An {@link OperationPreprocessor} that modifies URIs in the request and in the response - * by changing one or more of their host, scheme, and port. URIs in the following - * locations are modified: - *
          - *
        • {@link OperationRequest#getUri() Request URI} - *
        • {@link OperationRequest#getHeaders() Request headers} - *
        • {@link OperationRequest#getContent() Request content} - *
        • {@link OperationRequestPart#getHeaders() Request part headers} - *
        • {@link OperationRequestPart#getContent() Request part content} - *
        • {@link OperationResponse#getHeaders() Response headers} - *
        • {@link OperationResponse#getContent() Response content} - *
        - * - * @author Andy Wilkinson - * @since 1.2.0 - * @deprecated since 2.0.1 in favor of - * {@link org.springframework.restdocs.operation.preprocess.UriModifyingOperationPreprocessor} - */ -@Deprecated -public class UriModifyingOperationPreprocessor - extends org.springframework.restdocs.operation.preprocess.UriModifyingOperationPreprocessor { - -} diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/package-info.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/package-info.java deleted file mode 100644 index cdcf9a3a0..000000000 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/operation/preprocess/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2014-2017 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. - */ - -/** - * REST Assured-specific support for preprocessing an operation prior to it being - * documented. - */ -package org.springframework.restdocs.restassured3.operation.preprocess; diff --git a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/package-info.java b/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/package-info.java deleted file mode 100644 index e8ee89e0c..000000000 --- a/spring-restdocs-restassured/src/main/java/org/springframework/restdocs/restassured3/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2014-2017 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. - */ - -/** - * Core classes for using Spring REST Docs with REST Assured 3. - */ -package org.springframework.restdocs.restassured3; diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredParameterBehaviorTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredParameterBehaviorTests.java new file mode 100644 index 000000000..1bef29294 --- /dev/null +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredParameterBehaviorTests.java @@ -0,0 +1,263 @@ +/* + * Copyright 2014-2025 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.restdocs.restassured; + +import io.restassured.RestAssured; +import io.restassured.specification.RequestSpecification; +import org.assertj.core.api.AbstractAssert; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.restdocs.operation.OperationRequest; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests to verify that the understanding of REST Assured's parameter handling behavior is + * correct. + * + * @author Andy Wilkinson + */ +class RestAssuredParameterBehaviorTests { + + private static final MediaType APPLICATION_FORM_URLENCODED_ISO_8859_1 = MediaType + .parseMediaType(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=ISO-8859-1"); + + @RegisterExtension + public static TomcatServer tomcat = new TomcatServer(); + + private final RestAssuredRequestConverter factory = new RestAssuredRequestConverter(); + + private OperationRequest request; + + private RequestSpecification spec = RestAssured.given() + .port(tomcat.getPort()) + .filter((request, response, context) -> { + this.request = this.factory.convert(request); + return context.next(request, response); + }); + + @Test + void queryParameterOnGet() { + this.spec.queryParam("a", "alpha", "apple") + .queryParam("b", "bravo") + .get("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.GET); + } + + @Test + void queryParameterOnHead() { + this.spec.queryParam("a", "alpha", "apple") + .queryParam("b", "bravo") + .head("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.HEAD); + } + + @Test + void queryParameterOnPost() { + this.spec.queryParam("a", "alpha", "apple") + .queryParam("b", "bravo") + .post("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.POST); + } + + @Test + void queryParameterOnPut() { + this.spec.queryParam("a", "alpha", "apple") + .queryParam("b", "bravo") + .put("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.PUT); + } + + @Test + void queryParameterOnPatch() { + this.spec.queryParam("a", "alpha", "apple") + .queryParam("b", "bravo") + .patch("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.PATCH); + } + + @Test + void queryParameterOnDelete() { + this.spec.queryParam("a", "alpha", "apple") + .queryParam("b", "bravo") + .delete("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.DELETE); + } + + @Test + void queryParameterOnOptions() { + this.spec.queryParam("a", "alpha", "apple") + .queryParam("b", "bravo") + .options("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.OPTIONS); + } + + @Test + void paramOnGet() { + this.spec.param("a", "alpha", "apple").param("b", "bravo").get("/query-parameter").then().statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.GET); + } + + @Test + void paramOnHead() { + this.spec.param("a", "alpha", "apple").param("b", "bravo").head("/query-parameter").then().statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.HEAD); + } + + @Test + void paramOnPost() { + this.spec.param("a", "alpha", "apple").param("b", "bravo").post("/form-url-encoded").then().statusCode(200); + assertThatRequest(this.request).isFormUrlEncodedWithMethod(HttpMethod.POST); + } + + @Test + void paramOnPut() { + this.spec.param("a", "alpha", "apple").param("b", "bravo").put("/query-parameter").then().statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.PUT); + } + + @Test + void paramOnPatch() { + this.spec.param("a", "alpha", "apple").param("b", "bravo").patch("/query-parameter").then().statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.PATCH); + } + + @Test + void paramOnDelete() { + this.spec.param("a", "alpha", "apple").param("b", "bravo").delete("/query-parameter").then().statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.DELETE); + } + + @Test + void paramOnOptions() { + this.spec.param("a", "alpha", "apple").param("b", "bravo").options("/query-parameter").then().statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.OPTIONS); + } + + @Test + void formParamOnGet() { + this.spec.formParam("a", "alpha", "apple") + .formParam("b", "bravo") + .get("/query-parameter") + .then() + .statusCode(200); + assertThatRequest(this.request).hasQueryParametersWithMethod(HttpMethod.GET); + } + + @Test + void formParamOnHead() { + this.spec.formParam("a", "alpha", "apple") + .formParam("b", "bravo") + .head("/form-url-encoded") + .then() + .statusCode(200); + assertThatRequest(this.request).isFormUrlEncodedWithMethod(HttpMethod.HEAD); + } + + @Test + void formParamOnPost() { + this.spec.formParam("a", "alpha", "apple") + .formParam("b", "bravo") + .post("/form-url-encoded") + .then() + .statusCode(200); + assertThatRequest(this.request).isFormUrlEncodedWithMethod(HttpMethod.POST); + } + + @Test + void formParamOnPut() { + this.spec.formParam("a", "alpha", "apple") + .formParam("b", "bravo") + .put("/form-url-encoded") + .then() + .statusCode(200); + assertThatRequest(this.request).isFormUrlEncodedWithMethod(HttpMethod.PUT); + } + + @Test + void formParamOnPatch() { + this.spec.formParam("a", "alpha", "apple") + .formParam("b", "bravo") + .patch("/form-url-encoded") + .then() + .statusCode(200); + assertThatRequest(this.request).isFormUrlEncodedWithMethod(HttpMethod.PATCH); + } + + @Test + void formParamOnDelete() { + this.spec.formParam("a", "alpha", "apple") + .formParam("b", "bravo") + .delete("/form-url-encoded") + .then() + .statusCode(200); + assertThatRequest(this.request).isFormUrlEncodedWithMethod(HttpMethod.DELETE); + } + + @Test + void formParamOnOptions() { + this.spec.formParam("a", "alpha", "apple") + .formParam("b", "bravo") + .options("/form-url-encoded") + .then() + .statusCode(200); + assertThatRequest(this.request).isFormUrlEncodedWithMethod(HttpMethod.OPTIONS); + } + + private OperationRequestAssert assertThatRequest(OperationRequest request) { + return new OperationRequestAssert(request); + } + + private static final class OperationRequestAssert extends AbstractAssert { + + private OperationRequestAssert(OperationRequest actual) { + super(actual, OperationRequestAssert.class); + } + + private void isFormUrlEncodedWithMethod(HttpMethod method) { + assertThat(this.actual.getMethod()).isEqualTo(method); + assertThat(this.actual.getUri().getRawQuery()).isNull(); + assertThat(this.actual.getContentAsString()).isEqualTo("a=alpha&a=apple&b=bravo"); + assertThat(this.actual.getHeaders().getContentType()).isEqualTo(APPLICATION_FORM_URLENCODED_ISO_8859_1); + } + + private void hasQueryParametersWithMethod(HttpMethod method) { + assertThat(this.actual.getMethod()).isEqualTo(method); + assertThat(this.actual.getUri().getRawQuery()).isEqualTo("a=alpha&a=apple&b=bravo"); + assertThat(this.actual.getContentAsString()).isEmpty(); + } + + } + +} diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRequestConverterTests.java similarity index 73% rename from spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java rename to spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRequestConverterTests.java index d79a5a649..09d411ae2 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRequestConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -14,14 +14,13 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.URI; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; @@ -29,10 +28,8 @@ import io.restassured.RestAssured; import io.restassured.specification.FilterableRequestSpecification; import io.restassured.specification.RequestSpecification; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -42,24 +39,23 @@ import org.springframework.restdocs.operation.RequestCookie; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.assertj.core.api.Assertions.entry; /** * Tests for {@link RestAssuredRequestConverter}. * * @author Andy Wilkinson */ -public class RestAssuredRequestConverterTests { +class RestAssuredRequestConverterTests { - @ClassRule + @RegisterExtension public static TomcatServer tomcat = new TomcatServer(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final RestAssuredRequestConverter factory = new RestAssuredRequestConverter(); @Test - public void requestUri() { + void requestUri() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()); requestSpec.get("/foo/bar"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); @@ -67,7 +63,7 @@ public void requestUri() { } @Test - public void requestMethod() { + void requestMethod() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()); requestSpec.head("/foo/bar"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); @@ -75,69 +71,53 @@ public void requestMethod() { } @Test - public void queryStringParameters() { + void queryStringParameters() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).queryParam("foo", "bar"); requestSpec.get("/"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", Collections.singletonList("bar")); + assertThat(request.getUri().getRawQuery()).isEqualTo("foo=bar"); } @Test - public void queryStringFromUrlParameters() { + void queryStringFromUrlParameters() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()); requestSpec.get("/?foo=bar&foo=qix"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", Arrays.asList("bar", "qix")); - } - - @Test - public void formParameters() { - RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).formParam("foo", "bar"); - requestSpec.get("/"); - OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", Collections.singletonList("bar")); + assertThat(request.getUri().getRawQuery()).isEqualTo("foo=bar&foo=qix"); } @Test - public void requestParameters() { + void paramOnGetRequestIsMappedToQueryString() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).param("foo", "bar"); requestSpec.get("/"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters()).hasSize(1); - assertThat(request.getParameters()).containsEntry("foo", Collections.singletonList("bar")); + assertThat(request.getUri().getRawQuery()).isEqualTo("foo=bar"); } @Test - public void headers() { + void headers() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).header("Foo", "bar"); requestSpec.get("/"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getHeaders()).hasSize(2); - assertThat(request.getHeaders()).containsEntry("Foo", Collections.singletonList("bar")); - assertThat(request.getHeaders()).containsEntry("Host", - Collections.singletonList("localhost:" + tomcat.getPort())); + assertThat(request.getHeaders().headerSet()).containsOnly(entry("Foo", Collections.singletonList("bar")), + entry("Host", Collections.singletonList("localhost:" + tomcat.getPort()))); } @Test - public void headersWithCustomAccept() { + void headersWithCustomAccept() { RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .header("Foo", "bar") .accept("application/json"); requestSpec.get("/"); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getHeaders()).hasSize(3); - assertThat(request.getHeaders()).containsEntry("Foo", Collections.singletonList("bar")); - assertThat(request.getHeaders()).containsEntry("Accept", Collections.singletonList("application/json")); - assertThat(request.getHeaders()).containsEntry("Host", - Collections.singletonList("localhost:" + tomcat.getPort())); + assertThat(request.getHeaders().headerSet()).containsOnly(entry("Foo", Collections.singletonList("bar")), + entry("Accept", Collections.singletonList("application/json")), + entry("Host", Collections.singletonList("localhost:" + tomcat.getPort()))); } @Test - public void cookies() { + void cookies() { RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .cookie("cookie1", "cookieVal1") @@ -158,7 +138,7 @@ public void cookies() { } @Test - public void multipart() { + void multipart() { RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .multiPart("a", "a.txt", "alpha", null) @@ -170,21 +150,20 @@ public void multipart() { assertThat(parts).extracting("name").containsExactly("a", "b"); assertThat(parts).extracting("submittedFileName").containsExactly("a.txt", "file"); assertThat(parts).extracting("contentAsString").containsExactly("alpha", "{\"foo\":\"bar\"}"); - assertThat(parts).extracting("headers") - .extracting(HttpHeaders.CONTENT_TYPE) + assertThat(parts).map((part) -> part.getHeaders().get(HttpHeaders.CONTENT_TYPE)) .containsExactly(Collections.singletonList(MediaType.TEXT_PLAIN_VALUE), Collections.singletonList(MediaType.APPLICATION_JSON_VALUE)); } @Test - public void byteArrayBody() { + void byteArrayBody() { RequestSpecification requestSpec = RestAssured.given().body("body".getBytes()).port(tomcat.getPort()); requestSpec.post(); this.factory.convert((FilterableRequestSpecification) requestSpec); } @Test - public void stringBody() { + void stringBody() { RequestSpecification requestSpec = RestAssured.given().body("body").port(tomcat.getPort()); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); @@ -192,7 +171,7 @@ public void stringBody() { } @Test - public void objectBody() { + void objectBody() { RequestSpecification requestSpec = RestAssured.given().body(new ObjectBody("bar")).port(tomcat.getPort()); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); @@ -200,7 +179,7 @@ public void objectBody() { } @Test - public void byteArrayInputStreamBody() { + void byteArrayInputStreamBody() { RequestSpecification requestSpec = RestAssured.given() .body(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 })) .port(tomcat.getPort()); @@ -210,7 +189,7 @@ public void byteArrayInputStreamBody() { } @Test - public void fileBody() { + void fileBody() { RequestSpecification requestSpec = RestAssured.given() .body(new File("src/test/resources/body.txt")) .port(tomcat.getPort()); @@ -220,17 +199,17 @@ public void fileBody() { } @Test - public void fileInputStreamBody() throws FileNotFoundException { + void fileInputStreamBody() throws FileNotFoundException { FileInputStream inputStream = new FileInputStream("src/test/resources/body.txt"); RequestSpecification requestSpec = RestAssured.given().body(inputStream).port(tomcat.getPort()); requestSpec.post(); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Cannot read content from input stream " + inputStream + " due to reset() failure"); - this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThatIllegalStateException() + .isThrownBy(() -> this.factory.convert((FilterableRequestSpecification) requestSpec)) + .withMessage("Cannot read content from input stream " + inputStream + " due to reset() failure"); } @Test - public void multipartWithByteArrayInputStreamBody() { + void multipartWithByteArrayInputStreamBody() { RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .multiPart("foo", "foo.txt", new ByteArrayInputStream("foo".getBytes())); @@ -240,7 +219,7 @@ public void multipartWithByteArrayInputStreamBody() { } @Test - public void multipartWithStringBody() { + void multipartWithStringBody() { RequestSpecification requestSpec = RestAssured.given().port(tomcat.getPort()).multiPart("control", "foo"); requestSpec.post(); OperationRequest request = this.factory.convert((FilterableRequestSpecification) requestSpec); @@ -248,7 +227,7 @@ public void multipartWithStringBody() { } @Test - public void multipartWithByteArrayBody() { + void multipartWithByteArrayBody() { RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .multiPart("control", "file", "foo".getBytes()); @@ -258,7 +237,7 @@ public void multipartWithByteArrayBody() { } @Test - public void multipartWithFileBody() { + void multipartWithFileBody() { RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .multiPart(new File("src/test/resources/body.txt")); @@ -268,19 +247,19 @@ public void multipartWithFileBody() { } @Test - public void multipartWithFileInputStreamBody() throws FileNotFoundException { + void multipartWithFileInputStreamBody() throws FileNotFoundException { FileInputStream inputStream = new FileInputStream("src/test/resources/body.txt"); RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .multiPart("foo", "foo.txt", inputStream); requestSpec.post(); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Cannot read content from input stream " + inputStream + " due to reset() failure"); - this.factory.convert((FilterableRequestSpecification) requestSpec); + assertThatIllegalStateException() + .isThrownBy(() -> this.factory.convert((FilterableRequestSpecification) requestSpec)) + .withMessage("Cannot read content from input stream " + inputStream + " due to reset() failure"); } @Test - public void multipartWithObjectBody() { + void multipartWithObjectBody() { RequestSpecification requestSpec = RestAssured.given() .port(tomcat.getPort()) .multiPart("control", new ObjectBody("bar")); diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverterTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredResponseConverterTests.java similarity index 80% rename from spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverterTests.java rename to spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredResponseConverterTests.java index 927cf67be..22b17601b 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredResponseConverterTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredResponseConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2025 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. @@ -14,13 +14,14 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import io.restassured.http.Headers; import io.restassured.response.Response; import io.restassured.response.ResponseBody; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatusCode; import org.springframework.restdocs.operation.OperationResponse; import static org.assertj.core.api.Assertions.assertThat; @@ -32,12 +33,12 @@ * * @author Andy Wilkinson */ -public class RestAssuredResponseConverterTests { +class RestAssuredResponseConverterTests { private final RestAssuredResponseConverter converter = new RestAssuredResponseConverter(); @Test - public void responseWithCustomStatus() { + void responseWithCustomStatus() { Response response = mock(Response.class); given(response.getStatusCode()).willReturn(600); given(response.getHeaders()).willReturn(new Headers()); @@ -45,8 +46,7 @@ public void responseWithCustomStatus() { given(response.getBody()).willReturn(body); given(body.asByteArray()).willReturn(new byte[0]); OperationResponse operationResponse = this.converter.convert(response); - assertThat(operationResponse.getStatus()).isNull(); - assertThat(operationResponse.getStatusCode()).isEqualTo(600); + assertThat(operationResponse.getStatus()).isEqualTo(HttpStatusCode.valueOf(600)); } } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurerTests.java similarity index 79% rename from spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java rename to spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurerTests.java index 156cd278a..8dbf59354 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import java.util.List; import java.util.Map; @@ -22,11 +22,13 @@ import io.restassured.filter.FilterContext; import io.restassured.specification.FilterableRequestSpecification; import io.restassured.specification.FilterableResponseSpecification; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.restdocs.operation.preprocess.OperationRequestPreprocessor; import org.springframework.restdocs.operation.preprocess.OperationResponsePreprocessor; @@ -45,10 +47,8 @@ * @author Andy Wilkinson * @author Filip Hrisafov */ -public class RestAssuredRestDocumentationConfigurerTests { - - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); +@ExtendWith(RestDocumentationExtension.class) +class RestAssuredRestDocumentationConfigurerTests { private final FilterableRequestSpecification requestSpec = mock(FilterableRequestSpecification.class); @@ -56,20 +56,24 @@ public class RestAssuredRestDocumentationConfigurerTests { private final FilterContext filterContext = mock(FilterContext.class); - private final RestAssuredRestDocumentationConfigurer configurer = new RestAssuredRestDocumentationConfigurer( - this.restDocumentation); + private RestAssuredRestDocumentationConfigurer configurer; + + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { + this.configurer = new RestAssuredRestDocumentationConfigurer(restDocumentation); + } @Test - public void nextFilterIsCalled() { + void nextFilterIsCalled() { this.configurer.filter(this.requestSpec, this.responseSpec, this.filterContext); verify(this.filterContext).next(this.requestSpec, this.responseSpec); } @Test - public void configurationIsAddedToTheContext() { + void configurationIsAddedToTheContext() { this.configurer.operationPreprocessors() .withRequestDefaults(Preprocessors.prettyPrint()) - .withResponseDefaults(Preprocessors.removeHeaders("Foo")) + .withResponseDefaults(Preprocessors.modifyHeaders().remove("Foo")) .filter(this.requestSpec, this.responseSpec, this.filterContext); @SuppressWarnings("rawtypes") ArgumentCaptor configurationCaptor = ArgumentCaptor.forClass(Map.class); diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationIntegrationTests.java similarity index 76% rename from spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java rename to spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationIntegrationTests.java index fee8e9a8e..89d9c3516 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/RestAssuredRestDocumentationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.restdocs.restassured3; +package org.springframework.restdocs.restassured; import java.io.File; import java.io.FileInputStream; @@ -29,14 +29,15 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; import org.assertj.core.api.Condition; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.testfixtures.SnippetConditions; @@ -55,11 +56,11 @@ import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.operation.preprocess.Preprocessors.maskLinks; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyUris; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.removeHeaders; import static org.springframework.restdocs.operation.preprocess.Preprocessors.replacePattern; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; @@ -68,10 +69,10 @@ import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document; +import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.documentationConfiguration; /** * Integration tests for using Spring REST Docs with REST Assured. @@ -80,18 +81,16 @@ * @author Tomasz Kopczynski * @author Filip Hrisafov */ -public class RestAssuredRestDocumentationIntegrationTests { +@ExtendWith(RestDocumentationExtension.class) +class RestAssuredRestDocumentationIntegrationTests { - @Rule - public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - - @ClassRule - public static TomcatServer tomcat = new TomcatServer(); + @RegisterExtension + private static TomcatServer tomcat = new TomcatServer(); @Test - public void defaultSnippetGeneration() { + void defaultSnippetGeneration(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("default")) .get("/") .then() @@ -101,10 +100,10 @@ public void defaultSnippetGeneration() { } @Test - public void curlSnippetWithContent() { + void curlSnippetWithContent(RestDocumentationContextProvider restDocumentation) { String contentType = "text/plain; charset=UTF-8"; given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("curl-snippet-with-content")) .accept("application/json") .body("content") @@ -120,10 +119,10 @@ public void curlSnippetWithContent() { } @Test - public void curlSnippetWithCookies() { + void curlSnippetWithCookies(RestDocumentationContextProvider restDocumentation) { String contentType = "text/plain; charset=UTF-8"; given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("curl-snippet-with-cookies")) .accept("application/json") .contentType(contentType) @@ -138,9 +137,9 @@ public void curlSnippetWithCookies() { } @Test - public void curlSnippetWithEmptyParameterQueryString() { + void curlSnippetWithEmptyParameterQueryString(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("curl-snippet-with-empty-parameter-query-string")) .accept("application/json") .param("a", "") @@ -155,9 +154,9 @@ public void curlSnippetWithEmptyParameterQueryString() { } @Test - public void curlSnippetWithQueryStringOnPost() { + void curlSnippetWithQueryStringOnPost(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("curl-snippet-with-query-string")) .accept("application/json") .param("foo", "bar") @@ -170,13 +169,13 @@ public void curlSnippetWithQueryStringOnPost() { .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") .withContent(String.format("$ curl " + "'http://localhost:" + tomcat.getPort() + "/?foo=bar' -i -X POST \\%n" + " -H 'Accept: application/json' \\%n" - + " -H 'Content-Type: " + contentType + "' \\%n" + " -d 'a=alpha'")))); + + " -H 'Content-Type: " + contentType + "' \\%n" + " -d 'foo=bar&a=alpha'")))); } @Test - public void linksSnippet() { + void linksSnippet(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("links", links(linkWithRel("rel").description("The description")))) .accept("application/json") .get("/") @@ -187,9 +186,9 @@ public void linksSnippet() { } @Test - public void pathParametersSnippet() { + void pathParametersSnippet(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("path-parameters", pathParameters(parameterWithName("foo").description("The description")))) .accept("application/json") @@ -201,24 +200,24 @@ public void pathParametersSnippet() { } @Test - public void requestParametersSnippet() { + void queryParametersSnippet(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) - .filter(document("request-parameters", - requestParameters(parameterWithName("foo").description("The description")))) + .filter(documentationConfiguration(restDocumentation)) + .filter(document("query-parameters", + queryParameters(parameterWithName("foo").description("The description")))) .accept("application/json") .param("foo", "bar") .get("/") .then() .statusCode(200); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/request-parameters"), "http-request.adoc", - "http-response.adoc", "curl-request.adoc", "request-parameters.adoc"); + assertExpectedSnippetFilesExist(new File("build/generated-snippets/query-parameters"), "http-request.adoc", + "http-response.adoc", "curl-request.adoc", "query-parameters.adoc"); } @Test - public void requestFieldsSnippet() { + void requestFieldsSnippet(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("request-fields", requestFields(fieldWithPath("a").description("The description")))) .accept("application/json") .body("{\"a\":\"alpha\"}") @@ -230,9 +229,9 @@ public void requestFieldsSnippet() { } @Test - public void requestPartsSnippet() { + void requestPartsSnippet(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("request-parts", requestParts(partWithName("a").description("The description")))) .multiPart("a", "foo") .post("/upload") @@ -243,9 +242,9 @@ public void requestPartsSnippet() { } @Test - public void responseFieldsSnippet() { + void responseFieldsSnippet(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("response-fields", responseFields(fieldWithPath("a").description("The description"), subsectionWithPath("links").description("Links to other resources")))) @@ -258,9 +257,9 @@ public void responseFieldsSnippet() { } @Test - public void parameterizedOutputDirectory() { + void parameterizedOutputDirectory(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("{method-name}")) .get("/") .then() @@ -270,9 +269,9 @@ public void parameterizedOutputDirectory() { } @Test - public void multiStep() { + void multiStep(RestDocumentationContextProvider restDocumentation) { RequestSpecification spec = new RequestSpecBuilder().setPort(tomcat.getPort()) - .addFilter(documentationConfiguration(this.restDocumentation)) + .addFilter(documentationConfiguration(restDocumentation)) .addFilter(document("{method-name}-{step}")) .build(); given(spec).get("/").then().statusCode(200); @@ -287,10 +286,10 @@ public void multiStep() { } @Test - public void additionalSnippets() { + void additionalSnippets(RestDocumentationContextProvider restDocumentation) { RestDocumentationFilter documentation = document("{method-name}-{step}"); RequestSpecification spec = new RequestSpecBuilder().setPort(tomcat.getPort()) - .addFilter(documentationConfiguration(this.restDocumentation)) + .addFilter(documentationConfiguration(restDocumentation)) .addFilter(documentation) .build(); given(spec) @@ -304,26 +303,28 @@ public void additionalSnippets() { } @Test - public void responseWithCookie() { + void responseWithCookie(RestDocumentationContextProvider restDocumentation) { given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("set-cookie", - preprocessResponse(removeHeaders(HttpHeaders.DATE, HttpHeaders.CONTENT_TYPE)))) + preprocessResponse(modifyHeaders().remove(HttpHeaders.DATE).remove(HttpHeaders.CONTENT_TYPE)))) .get("/set-cookie") .then() .statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/set-cookie"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc")) - .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK).header(HttpHeaders.SET_COOKIE, - "name=value; Domain=localhost; HttpOnly"))); + .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) + .header(HttpHeaders.SET_COOKIE, "name=value; Domain=localhost; HttpOnly") + .header("Keep-Alive", "timeout=60") + .header("Connection", "keep-alive"))); } @Test - public void preprocessedRequest() { + void preprocessedRequest(RestDocumentationContextProvider restDocumentation) { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .header("a", "alpha") .header("b", "bravo") .contentType("application/json") @@ -332,7 +333,7 @@ public void preprocessedRequest() { .filter(document("original-request")) .filter(document("preprocessed-request", preprocessRequest(prettyPrint(), replacePattern(pattern, "\"<>\""), modifyUris().removePort(), - removeHeaders("a", HttpHeaders.CONTENT_LENGTH)))) + modifyHeaders().remove("a").remove(HttpHeaders.CONTENT_LENGTH)))) .get("/") .then() .statusCode(200); @@ -340,7 +341,7 @@ public void preprocessedRequest() { .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("a", "alpha") .header("b", "bravo") .header("Accept", MediaType.APPLICATION_JSON_VALUE) - .header("Content-Type", "application/json; charset=UTF-8") + .header("Content-Type", "application/json") .header("Host", "localhost:" + tomcat.getPort()) .header("Content-Length", "13") .content("{\"a\":\"alpha\"}"))); @@ -348,18 +349,18 @@ public void preprocessedRequest() { assertThat(new File("build/generated-snippets/preprocessed-request/http-request.adoc")) .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("b", "bravo") .header("Accept", MediaType.APPLICATION_JSON_VALUE) - .header("Content-Type", "application/json; charset=UTF-8") + .header("Content-Type", "application/json") .header("Host", "localhost") .content(prettyPrinted))); } @Test - public void defaultPreprocessedRequest() { + void defaultPreprocessedRequest(RestDocumentationContextProvider restDocumentation) { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .filter(documentationConfiguration(restDocumentation).operationPreprocessors() .withRequestDefaults(prettyPrint(), replacePattern(pattern, "\"<>\""), modifyUris().removePort(), - removeHeaders("a", HttpHeaders.CONTENT_LENGTH))) + modifyHeaders().remove("a").remove(HttpHeaders.CONTENT_LENGTH))) .header("a", "alpha") .header("b", "bravo") .contentType("application/json") @@ -373,20 +374,22 @@ public void defaultPreprocessedRequest() { assertThat(new File("build/generated-snippets/default-preprocessed-request/http-request.adoc")) .has(content(httpRequest(TemplateFormats.asciidoctor(), RequestMethod.GET, "/").header("b", "bravo") .header("Accept", MediaType.APPLICATION_JSON_VALUE) - .header("Content-Type", "application/json; charset=UTF-8") + .header("Content-Type", "application/json") .header("Host", "localhost") .content(prettyPrinted))); } @Test - public void preprocessedResponse() { + void preprocessedResponse(RestDocumentationContextProvider restDocumentation) { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("original-response")) - .filter(document("preprocessed-response", preprocessResponse(prettyPrint(), maskLinks(), - removeHeaders("a", "Transfer-Encoding", "Date", "Server"), replacePattern(pattern, "\"<>\""), - modifyUris().scheme("https").host("api.example.com").removePort()))) + .filter(document("preprocessed-response", + preprocessResponse(prettyPrint(), maskLinks(), + modifyHeaders().remove("a").remove("Transfer-Encoding").remove("Date").remove("Server"), + replacePattern(pattern, "\"<>\""), + modifyUris().scheme("https").host("api.example.com").removePort()))) .get("/") .then() .statusCode(200); @@ -396,17 +399,19 @@ public void preprocessedResponse() { .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) .header("Foo", "https://api.example.com/foo/bar") .header("Content-Type", "application/json;charset=UTF-8") + .header("Keep-Alive", "timeout=60") + .header("Connection", "keep-alive") .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) .content(prettyPrinted))); } @Test - public void defaultPreprocessedResponse() { + void defaultPreprocessedResponse(RestDocumentationContextProvider restDocumentation) { Pattern pattern = Pattern.compile("(\"alpha\")"); given().port(tomcat.getPort()) - .filter(documentationConfiguration(this.restDocumentation).operationPreprocessors() + .filter(documentationConfiguration(restDocumentation).operationPreprocessors() .withResponseDefaults(prettyPrint(), maskLinks(), - removeHeaders("a", "Transfer-Encoding", "Date", "Server"), + modifyHeaders().remove("a").remove("Transfer-Encoding").remove("Date").remove("Server"), replacePattern(pattern, "\"<>\""), modifyUris().scheme("https").host("api.example.com").removePort())) .filter(document("default-preprocessed-response")) @@ -419,12 +424,14 @@ public void defaultPreprocessedResponse() { .has(content(httpResponse(TemplateFormats.asciidoctor(), HttpStatus.OK) .header("Foo", "https://api.example.com/foo/bar") .header("Content-Type", "application/json;charset=UTF-8") + .header("Keep-Alive", "timeout=60") + .header("Connection", "keep-alive") .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) .content(prettyPrinted))); } @Test - public void customSnippetTemplate() throws MalformedURLException { + void customSnippetTemplate(RestDocumentationContextProvider restDocumentation) throws MalformedURLException { ClassLoader classLoader = new URLClassLoader( new URL[] { new File("src/test/resources/custom-snippet-templates").toURI().toURL() }, getClass().getClassLoader()); @@ -433,7 +440,7 @@ public void customSnippetTemplate() throws MalformedURLException { try { given().port(tomcat.getPort()) .accept("application/json") - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .filter(document("custom-snippet-template")) .get("/") .then() @@ -447,7 +454,7 @@ public void customSnippetTemplate() throws MalformedURLException { } @Test - public void exceptionShouldBeThrownWhenCallDocumentRequestSpecificationNotConfigured() { + void exceptionShouldBeThrownWhenCallDocumentRequestSpecificationNotConfigured() { assertThatThrownBy(() -> given().port(tomcat.getPort()).filter(document("default")).get("/")) .isInstanceOf(IllegalStateException.class) .hasMessage("REST Docs configuration not found. Did you forget to add a " @@ -455,7 +462,7 @@ public void exceptionShouldBeThrownWhenCallDocumentRequestSpecificationNotConfig } @Test - public void exceptionShouldBeThrownWhenCallDocumentSnippetsRequestSpecificationNotConfigured() { + void exceptionShouldBeThrownWhenCallDocumentSnippetsRequestSpecificationNotConfigured() { RestDocumentationFilter documentation = document("{method-name}-{step}"); assertThatThrownBy(() -> given().port(tomcat.getPort()) .filter(documentation.document(responseHeaders(headerWithName("a").description("one")))) @@ -473,13 +480,15 @@ private void assertExpectedSnippetFilesExist(File directory, String... snippets) } private Condition content(final Condition delegate) { - return new Condition() { + return new Condition<>() { @Override public boolean matches(File value) { try { - return delegate.matches(FileCopyUtils - .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8))); + String copyToString = FileCopyUtils + .copyToString(new InputStreamReader(new FileInputStream(value), StandardCharsets.UTF_8)); + System.out.println(copyToString); + return delegate.matches(copyToString); } catch (IOException ex) { fail("Failed to read '" + value + "'", ex); diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/TomcatServer.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/TomcatServer.java new file mode 100644 index 000000000..f91e1943c --- /dev/null +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured/TomcatServer.java @@ -0,0 +1,172 @@ +/* + * Copyright 2014-2025 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.restdocs.restassured; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.catalina.Context; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.startup.Tomcat; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; + +import org.springframework.http.MediaType; +import org.springframework.util.FileCopyUtils; + +/** + * {@link Extension} that starts and stops a Tomcat server. + * + * @author Andy Wilkinson + */ +class TomcatServer implements BeforeAllCallback, AfterAllCallback { + + private int port; + + @Override + public void beforeAll(ExtensionContext extensionContext) { + Store store = extensionContext.getStore(Namespace.create(TomcatServer.class)); + store.getOrComputeIfAbsent(Tomcat.class, (key) -> { + Tomcat tomcat = new Tomcat(); + tomcat.getConnector().setPort(0); + Context context = tomcat.addContext("/", null); + tomcat.addServlet("/", "test", new TestServlet()); + context.addServletMappingDecoded("/", "test"); + tomcat.addServlet("/", "set-cookie", new CookiesServlet()); + context.addServletMappingDecoded("/set-cookie", "set-cookie"); + tomcat.addServlet("/", "query-parameter", new QueryParameterServlet()); + context.addServletMappingDecoded("/query-parameter", "query-parameter"); + tomcat.addServlet("/", "form-url-encoded", new FormUrlEncodedServlet()); + context.addServletMappingDecoded("/form-url-encoded", "form-url-encoded"); + try { + tomcat.start(); + } + catch (Exception ex) { + throw new RuntimeException(ex); + } + this.port = tomcat.getConnector().getLocalPort(); + return tomcat; + }); + } + + @Override + public void afterAll(ExtensionContext extensionContext) throws LifecycleException { + Store store = extensionContext.getStore(Namespace.create(TomcatServer.class)); + Tomcat tomcat = store.get(Tomcat.class, Tomcat.class); + if (tomcat != null) { + tomcat.stop(); + } + } + + int getPort() { + return this.port; + } + + /** + * {@link HttpServlet} used to handle requests in the tests. + */ + private static final class TestServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + respondWithJson(response); + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + respondWithJson(response); + } + + private void respondWithJson(HttpServletResponse response) throws IOException, JsonProcessingException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + Map content = new HashMap<>(); + content.put("a", "alpha"); + Map link = new HashMap<>(); + link.put("rel", "rel"); + link.put("href", "href"); + content.put("links", Arrays.asList(link)); + response.getWriter().println(new ObjectMapper().writeValueAsString(content)); + response.setHeader("a", "alpha"); + response.setHeader("Foo", "http://localhost:12345/foo/bar"); + response.flushBuffer(); + } + + } + + /** + * {@link HttpServlet} used to handle cookies-related requests in the tests. + */ + private static final class CookiesServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + Cookie cookie = new Cookie("name", "value"); + cookie.setDomain("localhost"); + cookie.setHttpOnly(true); + + resp.addCookie(cookie); + } + + } + + private static final class QueryParameterServlet extends HttpServlet { + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (!req.getQueryString().equals("a=alpha&a=apple&b=bravo")) { + throw new ServletException("Incorrect query string"); + } + resp.setStatus(200); + } + + } + + private static final class FormUrlEncodedServlet extends HttpServlet { + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (!MediaType.APPLICATION_FORM_URLENCODED + .isCompatibleWith(MediaType.parseMediaType(req.getContentType()))) { + throw new ServletException("Incorrect Content-Type"); + } + String content = FileCopyUtils.copyToString(new InputStreamReader(req.getInputStream())); + if (!"a=alpha&a=apple&b=bravo".equals(content)) { + throw new ServletException("Incorrect body content"); + } + resp.setStatus(200); + } + + } + +} diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/TomcatServer.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/TomcatServer.java deleted file mode 100644 index 3f252bd35..000000000 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/TomcatServer.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2014-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.restdocs.restassured3; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.catalina.Context; -import org.apache.catalina.LifecycleException; -import org.apache.catalina.startup.Tomcat; -import org.junit.rules.ExternalResource; - -/** - * {@link ExternalResource} that starts and stops a Tomcat server. - * - * @author Andy Wilkinson - */ -class TomcatServer extends ExternalResource { - - private Tomcat tomcat; - - private int port; - - @Override - protected void before() throws LifecycleException { - this.tomcat = new Tomcat(); - this.tomcat.getConnector().setPort(0); - Context context = this.tomcat.addContext("/", null); - this.tomcat.addServlet("/", "test", new TestServlet()); - context.addServletMappingDecoded("/", "test"); - this.tomcat.addServlet("/", "set-cookie", new CookiesServlet()); - context.addServletMappingDecoded("/set-cookie", "set-cookie"); - this.tomcat.start(); - this.port = this.tomcat.getConnector().getLocalPort(); - } - - @Override - protected void after() { - try { - this.tomcat.stop(); - } - catch (LifecycleException ex) { - throw new RuntimeException(ex); - } - } - - int getPort() { - return this.port; - } - - /** - * {@link HttpServlet} used to handle requests in the tests. - */ - private static final class TestServlet extends HttpServlet { - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - respondWithJson(response); - } - - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - respondWithJson(response); - } - - private void respondWithJson(HttpServletResponse response) throws IOException, JsonProcessingException { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json"); - Map content = new HashMap<>(); - content.put("a", "alpha"); - Map link = new HashMap<>(); - link.put("rel", "rel"); - link.put("href", "href"); - content.put("links", Arrays.asList(link)); - response.getWriter().println(new ObjectMapper().writeValueAsString(content)); - response.setHeader("a", "alpha"); - response.setHeader("Foo", "http://localhost:12345/foo/bar"); - response.flushBuffer(); - } - - } - - /** - * {@link HttpServlet} used to handle cookies-related requests in the tests. - */ - private static final class CookiesServlet extends HttpServlet { - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - Cookie cookie = new Cookie("name", "value"); - cookie.setDomain("localhost"); - cookie.setHttpOnly(true); - - resp.addCookie(cookie); - } - - } - -} diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java deleted file mode 100644 index 122fee427..000000000 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright 2014-2023 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.restdocs.restassured3.operation.preprocess; - -import java.net.URI; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.restdocs.operation.OperationRequest; -import org.springframework.restdocs.operation.OperationRequestFactory; -import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.OperationRequestPartFactory; -import org.springframework.restdocs.operation.OperationResponse; -import org.springframework.restdocs.operation.OperationResponseFactory; -import org.springframework.restdocs.operation.Parameters; -import org.springframework.restdocs.operation.RequestCookie; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link UriModifyingOperationPreprocessor}. - * - * @author Andy Wilkinson - */ -@Deprecated -public class UriModifyingOperationPreprocessorTests { - - private final OperationRequestFactory requestFactory = new OperationRequestFactory(); - - private final OperationResponseFactory responseFactory = new OperationResponseFactory(); - - private final UriModifyingOperationPreprocessor preprocessor = new UriModifyingOperationPreprocessor(); - - @Test - public void requestUriSchemeCanBeModified() { - this.preprocessor.scheme("https"); - OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("http://localhost:12345")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345")); - } - - @Test - public void requestUriHostCanBeModified() { - this.preprocessor.host("api.example.com"); - OperationRequest processed = this.preprocessor.preprocess(createRequestWithUri("https://api.foo.com:12345")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:12345")); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:12345"); - } - - @Test - public void requestUriPortCanBeModified() { - this.preprocessor.port(23456); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com:23456")); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com:23456"); - } - - @Test - public void requestUriPortCanBeRemoved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com")); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)).isEqualTo("api.example.com"); - } - - @Test - public void requestUriPathIsPreserved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345/foo/bar")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com/foo/bar")); - } - - @Test - public void requestUriQueryIsPreserved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345?foo=bar")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com?foo=bar")); - } - - @Test - public void requestUriAnchorIsPreserved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("https://api.example.com:12345#foo")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://api.example.com#foo")); - } - - @Test - public void requestContentUriSchemeCanBeModified() { - this.preprocessor.scheme("https"); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'https://localhost:12345' should be used"); - } - - @Test - public void requestContentUriHostCanBeModified() { - this.preprocessor.host("api.example.com"); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'https://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); - } - - @Test - public void requestContentUriPortCanBeModified() { - this.preprocessor.port(23456); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost:23456' should be used"); - } - - @Test - public void requestContentUriPortCanBeRemoved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost' should be used"); - } - - @Test - public void multipleRequestContentUrisCanBeModified() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor.preprocess(createRequestWithContent( - "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); - assertThat(new String(processed.getContent())) - .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); - } - - @Test - public void requestContentUriPathIsPreserved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used"); - } - - @Test - public void requestContentUriQueryIsPreserved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used"); - } - - @Test - public void requestContentUriAnchorIsPreserved() { - this.preprocessor.removePort(); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithContent("The uri 'http://localhost:12345#foo' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used"); - } - - @Test - public void responseContentUriSchemeCanBeModified() { - this.preprocessor.scheme("https"); - OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'https://localhost:12345' should be used"); - } - - @Test - public void responseContentUriHostCanBeModified() { - this.preprocessor.host("api.example.com"); - OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'https://localhost:12345' should be used")); - assertThat(new String(processed.getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); - } - - @Test - public void responseContentUriPortCanBeModified() { - this.preprocessor.port(23456); - OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost:23456' should be used"); - } - - @Test - public void responseContentUriPortCanBeRemoved() { - this.preprocessor.removePort(); - OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost' should be used"); - } - - @Test - public void multipleResponseContentUrisCanBeModified() { - this.preprocessor.removePort(); - OperationResponse processed = this.preprocessor.preprocess(createResponseWithContent( - "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); - assertThat(new String(processed.getContent())) - .isEqualTo("Use 'http://localhost' or 'https://localhost' to access the service"); - } - - @Test - public void responseContentUriPathIsPreserved() { - this.preprocessor.removePort(); - OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345/foo/bar' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost/foo/bar' should be used"); - } - - @Test - public void responseContentUriQueryIsPreserved() { - this.preprocessor.removePort(); - OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345?foo=bar' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost?foo=bar' should be used"); - } - - @Test - public void responseContentUriAnchorIsPreserved() { - this.preprocessor.removePort(); - OperationResponse processed = this.preprocessor - .preprocess(createResponseWithContent("The uri 'http://localhost:12345#foo' should be used")); - assertThat(new String(processed.getContent())).isEqualTo("The uri 'http://localhost#foo' should be used"); - } - - @Test - public void urisInRequestHeadersCanBeModified() { - OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithHeader("Foo", "https://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); - assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com"); - } - - @Test - public void urisInResponseHeadersCanBeModified() { - OperationResponse processed = this.preprocessor.host("api.example.com") - .preprocess(createResponseWithHeader("Foo", "https://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo")).isEqualTo("https://api.example.com:12345"); - } - - @Test - public void urisInRequestPartHeadersCanBeModified() { - OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithPartWithHeader("Foo", "https://locahost:12345")); - assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) - .isEqualTo("https://api.example.com:12345"); - } - - @Test - public void urisInRequestPartContentCanBeModified() { - OperationRequest processed = this.preprocessor.host("api.example.com") - .preprocess(createRequestWithPartWithContent("The uri 'https://localhost:12345' should be used")); - assertThat(new String(processed.getParts().iterator().next().getContent())) - .isEqualTo("The uri 'https://api.example.com:12345' should be used"); - } - - @Test - public void modifiedUriDoesNotGetDoubleEncoded() { - this.preprocessor.scheme("https"); - OperationRequest processed = this.preprocessor - .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); - assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); - - } - - @Test - public void resultingRequestHasCookiesFromOriginalRequst() { - List cookies = Arrays.asList(new RequestCookie("a", "alpha")); - OperationRequest request = this.requestFactory.create(URI.create("http://localhost:12345"), HttpMethod.GET, - new byte[0], new HttpHeaders(), new Parameters(), Collections.emptyList(), - cookies); - OperationRequest processed = this.preprocessor.preprocess(request); - assertThat(processed.getCookies().size()).isEqualTo(1); - } - - private OperationRequest createRequestWithUri(String uri) { - return this.requestFactory.create(URI.create(uri), HttpMethod.GET, new byte[0], new HttpHeaders(), - new Parameters(), Collections.emptyList()); - } - - private OperationRequest createRequestWithContent(String content) { - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, content.getBytes(), - new HttpHeaders(), new Parameters(), Collections.emptyList()); - } - - private OperationRequest createRequestWithHeader(String name, String value) { - HttpHeaders headers = new HttpHeaders(); - headers.add(name, value); - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], headers, - new Parameters(), Collections.emptyList()); - } - - private OperationRequest createRequestWithPartWithHeader(String name, String value) { - HttpHeaders headers = new HttpHeaders(); - headers.add(name, value); - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), - Arrays.asList(new OperationRequestPartFactory().create("part", "fileName", new byte[0], headers))); - } - - private OperationRequest createRequestWithPartWithContent(String content) { - return this.requestFactory.create(URI.create("http://localhost"), HttpMethod.GET, new byte[0], - new HttpHeaders(), new Parameters(), Arrays.asList(new OperationRequestPartFactory().create("part", - "fileName", content.getBytes(), new HttpHeaders()))); - } - - private OperationResponse createResponseWithContent(String content) { - return this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), content.getBytes()); - } - - private OperationResponse createResponseWithHeader(String name, String value) { - HttpHeaders headers = new HttpHeaders(); - headers.add(name, value); - return this.responseFactory.create(HttpStatus.OK, headers, new byte[0]); - } - -} diff --git a/spring-restdocs-webtestclient/build.gradle b/spring-restdocs-webtestclient/build.gradle index 616cba80f..7675c0d6c 100644 --- a/spring-restdocs-webtestclient/build.gradle +++ b/spring-restdocs-webtestclient/build.gradle @@ -1,5 +1,4 @@ plugins { - id "io.spring.compatibility-test" version "0.0.2" id "java-library" id "maven-publish" } @@ -11,27 +10,17 @@ dependencies { api("org.springframework:spring-test") api("org.springframework:spring-webflux") + compileOnly("org.hamcrest:hamcrest-core") + internal(platform(project(":spring-restdocs-platform"))) + testCompileOnly("org.hamcrest:hamcrest-core") + testImplementation(testFixtures(project(":spring-restdocs-core"))) - testImplementation("junit:junit") - testImplementation("org.assertj:assertj-core") - testImplementation("org.hamcrest:hamcrest-library") - testImplementation("org.mockito:mockito-core") testRuntimeOnly("org.springframework:spring-context") - testRuntimeOnly("org.synchronoss.cloud:nio-multipart-parser") -} - -compatibilityTest { - dependency("Spring Framework") { springFramework -> - springFramework.groupId = "org.springframework" - springFramework.versions = ["5.1.+", "5.2.+", "5.3.+"] - } } -project.afterEvaluate { - configurations.getByName("testRuntimeClasspath_spring_framework_5.3.+") { - exclude group: "org.synchronoss.cloud", module: "nio-multipart-parser" - } +tasks.named("test") { + useJUnitPlatform(); } diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java index 1f697dc5a..7fef86918 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverter.java @@ -30,27 +30,21 @@ import org.springframework.core.io.buffer.DefaultDataBuffer; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; import org.springframework.http.ReactiveHttpInputMessage; -import org.springframework.http.codec.FormHttpMessageReader; import org.springframework.http.codec.HttpMessageReader; +import org.springframework.http.codec.multipart.DefaultPartHttpMessageReader; import org.springframework.http.codec.multipart.FilePart; import org.springframework.http.codec.multipart.MultipartHttpMessageReader; import org.springframework.http.codec.multipart.Part; -import org.springframework.http.codec.multipart.SynchronossPartHttpMessageReader; import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.operation.OperationRequestFactory; import org.springframework.restdocs.operation.OperationRequestPart; import org.springframework.restdocs.operation.OperationRequestPartFactory; -import org.springframework.restdocs.operation.Parameters; -import org.springframework.restdocs.operation.QueryStringParser; import org.springframework.restdocs.operation.RequestConverter; import org.springframework.restdocs.operation.RequestCookie; import org.springframework.test.web.reactive.server.ExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.util.ClassUtils; import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; /** * A {@link RequestConverter} for creating an {@link OperationRequest} derived from an @@ -60,20 +54,11 @@ */ class WebTestClientRequestConverter implements RequestConverter { - private static final String DEFAULT_PART_HTTP_MESSAGE_READER = "org.springframework.http.codec.multipart.DefaultPartHttpMessageReader"; - - private static final ResolvableType FORM_DATA_TYPE = ResolvableType.forClassWithGenerics(MultiValueMap.class, - String.class, String.class); - - private final QueryStringParser queryStringParser = new QueryStringParser(); - - private final FormHttpMessageReader formDataReader = new FormHttpMessageReader(); - @Override public OperationRequest convert(ExchangeResult result) { HttpHeaders headers = extractRequestHeaders(result); return new OperationRequestFactory().create(result.getUrl(), result.getMethod(), result.getRequestBodyContent(), - headers, extractParameters(result), extractRequestParts(result), extractCookies(headers)); + headers, extractRequestParts(result), extractCookies(headers)); } private HttpHeaders extractRequestHeaders(ExchangeResult result) { @@ -83,22 +68,8 @@ private HttpHeaders extractRequestHeaders(ExchangeResult result) { return extracted; } - private Parameters extractParameters(ExchangeResult result) { - Parameters parameters = new Parameters(); - parameters.addAll(this.queryStringParser.parse(result.getUrl())); - if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(result.getRequestHeaders().getContentType())) { - parameters.addAll(this.formDataReader - .readMono(FORM_DATA_TYPE, new ExchangeResultReactiveHttpInputMessage(result), null) - .block()); - } - return parameters; - } - private List extractRequestParts(ExchangeResult result) { - HttpMessageReader partHttpMessageReader = findPartHttpMessageReader(); - if (partHttpMessageReader == null) { - return Collections.emptyList(); - } + HttpMessageReader partHttpMessageReader = new DefaultPartHttpMessageReader(); return new MultipartHttpMessageReader(partHttpMessageReader) .readMono(ResolvableType.forClass(Part.class), new ExchangeResultReactiveHttpInputMessage(result), Collections.emptyMap()) @@ -110,25 +81,6 @@ private List extractRequestParts(ExchangeResult result) { .collect(Collectors.toList()); } - @SuppressWarnings("unchecked") - private HttpMessageReader findPartHttpMessageReader() { - if (ClassUtils.isPresent(DEFAULT_PART_HTTP_MESSAGE_READER, getClass().getClassLoader())) { - try { - return (HttpMessageReader) Class - .forName(DEFAULT_PART_HTTP_MESSAGE_READER, true, getClass().getClassLoader()) - .newInstance(); - } - catch (Exception ex) { - // Continue - } - } - if (ClassUtils.isPresent("org.synchronoss.cloud.nio.multipart.NioMultipartParserListener", - getClass().getClassLoader())) { - return new SynchronossPartHttpMessageReader(); - } - return null; - } - private OperationRequestPart createOperationRequestPart(Part part) { ByteArrayOutputStream content = readPartBodyContent(part); return new OperationRequestPartFactory().create(part.name(), @@ -171,8 +123,9 @@ public HttpHeaders getHeaders() { @Override public Flux getBody() { - DefaultDataBuffer buffer = new DefaultDataBufferFactory().allocateBuffer(); - buffer.write(this.result.getRequestBodyContent()); + byte[] requestBodyContent = this.result.getRequestBodyContent(); + DefaultDataBuffer buffer = new DefaultDataBufferFactory().allocateBuffer(requestBodyContent.length); + buffer.write(requestBodyContent); return Flux.fromArray(new DataBuffer[] { buffer }); } diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java index a336616c6..5a8416bd4 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -17,12 +17,14 @@ package org.springframework.restdocs.webtestclient; import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; import org.springframework.http.HttpHeaders; -import org.springframework.http.ResponseCookie; import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.ResponseConverter; +import org.springframework.restdocs.operation.ResponseCookie; import org.springframework.test.web.reactive.server.ExchangeResult; import org.springframework.util.StringUtils; @@ -31,27 +33,20 @@ * {@link ExchangeResult}. * * @author Andy Wilkinson + * @author Clyde Stubbs */ class WebTestClientResponseConverter implements ResponseConverter { @Override public OperationResponse convert(ExchangeResult result) { - return new OperationResponseFactory().create(extractStatus(result), extractHeaders(result), - result.getResponseBodyContent()); - } - - private int extractStatus(ExchangeResult result) { - try { - return (int) result.getClass().getMethod("getRawStatusCode").invoke(result); - } - catch (Throwable ex) { - return result.getStatus().value(); - } + Collection cookies = extractCookies(result); + return new OperationResponseFactory().create(result.getStatus(), extractHeaders(result), + result.getResponseBodyContent(), cookies); } private HttpHeaders extractHeaders(ExchangeResult result) { HttpHeaders headers = result.getResponseHeaders(); - if (result.getResponseCookies().isEmpty() || headers.containsKey(HttpHeaders.SET_COOKIE)) { + if (result.getResponseCookies().isEmpty() || headers.containsHeader(HttpHeaders.SET_COOKIE)) { return headers; } result.getResponseCookies() @@ -62,7 +57,7 @@ private HttpHeaders extractHeaders(ExchangeResult result) { return headers; } - private String generateSetCookieHeader(ResponseCookie cookie) { + private String generateSetCookieHeader(org.springframework.http.ResponseCookie cookie) { StringBuilder header = new StringBuilder(); header.append(cookie.getName()); header.append('='); @@ -83,12 +78,25 @@ private String generateSetCookieHeader(ResponseCookie cookie) { return header.toString(); } + private Collection extractCookies(ExchangeResult result) { + return result.getResponseCookies() + .values() + .stream() + .flatMap(List::stream) + .map(this::createResponseCookie) + .collect(Collectors.toSet()); + } + private void appendIfAvailable(StringBuilder header, String value) { if (StringUtils.hasText(value)) { header.append(value); } } + private ResponseCookie createResponseCookie(org.springframework.http.ResponseCookie original) { + return new ResponseCookie(original.getName(), original.getValue()); + } + private void appendIfAvailable(StringBuilder header, String name, String value) { if (StringUtils.hasText(value)) { header.append(name); diff --git a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java index e6d5299dc..fb3f4d507 100644 --- a/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java +++ b/spring-restdocs-webtestclient/src/main/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurer.java @@ -94,7 +94,7 @@ public Mono filter(ClientRequest request, ExchangeFunction next) private ClientRequest applyUriDefaults(ClientRequest request) { URI requestUri = request.url(); - if (!StringUtils.isEmpty(requestUri.getHost())) { + if (StringUtils.hasLength(requestUri.getHost())) { return request; } try { diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java index 228ffa66a..1087ea411 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -17,9 +17,10 @@ package org.springframework.restdocs.webtestclient; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.ContentDisposition; @@ -38,6 +39,7 @@ import org.springframework.web.reactive.function.server.ServerResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; @@ -46,12 +48,12 @@ * * @author Andy Wilkinson */ -public class WebTestClientRequestConverterTests { +class WebTestClientRequestConverterTests { private final WebTestClientRequestConverter converter = new WebTestClientRequestConverter(); @Test - public void httpRequest() { + void httpRequest() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) .configureClient() .baseUrl("http://localhost") @@ -67,7 +69,7 @@ public void httpRequest() { } @Test - public void httpRequestWithCustomPort() { + void httpRequestWithCustomPort() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) .configureClient() .baseUrl("http://localhost:8080") @@ -83,7 +85,7 @@ public void httpRequestWithCustomPort() { } @Test - public void requestWithHeaders() { + void requestWithHeaders() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/"), (req) -> null)) .configureClient() .baseUrl("http://localhost") @@ -98,12 +100,12 @@ public void requestWithHeaders() { OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); - assertThat(request.getHeaders()).containsEntry("a", Arrays.asList("alpha", "apple")); - assertThat(request.getHeaders()).containsEntry("b", Arrays.asList("bravo")); + assertThat(request.getHeaders().headerSet()).contains(entry("a", Arrays.asList("alpha", "apple")), + entry("b", Arrays.asList("bravo"))); } @Test - public void httpsRequest() { + void httpsRequest() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) .configureClient() .baseUrl("https://localhost") @@ -119,7 +121,7 @@ public void httpsRequest() { } @Test - public void httpsRequestWithCustomPort() { + void httpsRequestWithCustomPort() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) .configureClient() .baseUrl("https://localhost:8443") @@ -135,7 +137,7 @@ public void httpsRequestWithCustomPort() { } @Test - public void getRequestWithQueryStringPopulatesParameters() { + void getRequestWithQueryString() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) .configureClient() .baseUrl("http://localhost") @@ -147,14 +149,11 @@ public void getRequestWithQueryStringPopulatesParameters() { .returnResult(); OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); - assertThat(request.getParameters()).hasSize(2); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); - assertThat(request.getParameters()).containsEntry("b", Arrays.asList("bravo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test - public void postRequestWithFormDataParameters() { + void postRequestWithFormDataParameters() { MultiValueMap parameters = new LinkedMultiValueMap<>(); parameters.addAll("a", Arrays.asList("alpha", "apple")); parameters.addAll("b", Arrays.asList("br&vo")); @@ -174,13 +173,15 @@ public void postRequestWithFormDataParameters() { OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); - assertThat(request.getParameters()).hasSize(2); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); - assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); + assertThat(request.getContentAsString()).isEqualTo("a=alpha&a=apple&b=br%26vo"); + assertThat(request.getHeaders().getContentType()).satisfiesAnyOf( + (mediaType) -> assertThat(mediaType) + .isEqualTo(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, StandardCharsets.UTF_8)), + (mediaType) -> assertThat(mediaType).isEqualTo(new MediaType(MediaType.APPLICATION_FORM_URLENCODED))); } @Test - public void postRequestWithQueryStringParameters() { + void postRequestWithQueryStringParameters() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { req.body(BodyExtractors.toFormData()).block(); return null; @@ -196,13 +197,10 @@ public void postRequestWithQueryStringParameters() { OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); - assertThat(request.getParameters()).hasSize(2); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); - assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test - public void postRequestWithQueryStringAndFormDataParameters() { + void postRequestWithQueryStringAndFormDataParameters() { MultiValueMap parameters = new LinkedMultiValueMap<>(); parameters.addAll("a", Arrays.asList("apple")); ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> { @@ -221,13 +219,15 @@ public void postRequestWithQueryStringAndFormDataParameters() { OperationRequest request = this.converter.convert(result); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo?a=alpha&b=br%26vo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); - assertThat(request.getParameters()).hasSize(2); - assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha", "apple")); - assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); + assertThat(request.getContentAsString()).isEqualTo("a=apple"); + assertThat(request.getHeaders().getContentType()).satisfiesAnyOf( + (mediaType) -> assertThat(mediaType) + .isEqualTo(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, StandardCharsets.UTF_8)), + (mediaType) -> assertThat(mediaType).isEqualTo(new MediaType(MediaType.APPLICATION_FORM_URLENCODED))); } @Test - public void postRequestWithNoContentType() { + void postRequestWithNoContentType() { ExchangeResult result = WebTestClient .bindToRouterFunction(RouterFunctions.route(POST("/foo"), (req) -> ServerResponse.ok().build())) .configureClient() @@ -244,7 +244,7 @@ public void postRequestWithNoContentType() { } @Test - public void multipartUpload() { + void multipartUpload() { MultiValueMap multipartData = new LinkedMultiValueMap<>(); multipartData.add("file", new byte[] { 1, 2, 3, 4 }); ExchangeResult result = WebTestClient @@ -267,14 +267,14 @@ public void multipartUpload() { OperationRequestPart part = request.getParts().iterator().next(); assertThat(part.getName()).isEqualTo("file"); assertThat(part.getSubmittedFileName()).isNull(); - assertThat(part.getHeaders()).hasSize(2); + assertThat(part.getHeaders().size()).isEqualTo(2); assertThat(part.getHeaders().getContentLength()).isEqualTo(4L); assertThat(part.getHeaders().getContentDisposition().getName()).isEqualTo("file"); assertThat(part.getContent()).containsExactly(1, 2, 3, 4); } @Test - public void multipartUploadFromResource() { + void multipartUploadFromResource() { MultiValueMap multipartData = new LinkedMultiValueMap<>(); multipartData.add("file", new ByteArrayResource(new byte[] { 1, 2, 3, 4 }) { @@ -304,7 +304,7 @@ public String getFilename() { OperationRequestPart part = request.getParts().iterator().next(); assertThat(part.getName()).isEqualTo("file"); assertThat(part.getSubmittedFileName()).isEqualTo("image.png"); - assertThat(part.getHeaders()).hasSize(3); + assertThat(part.getHeaders().size()).isEqualTo(3); assertThat(part.getHeaders().getContentLength()).isEqualTo(4); ContentDisposition contentDisposition = part.getHeaders().getContentDisposition(); assertThat(contentDisposition.getName()).isEqualTo("file"); @@ -314,7 +314,7 @@ public String getFilename() { } @Test - public void requestWithCookies() { + void requestWithCookies() { ExchangeResult result = WebTestClient.bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> null)) .configureClient() .baseUrl("http://localhost") diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java index ce330203c..e50fc5a5d 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,23 +18,21 @@ import java.util.Collections; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.MediaType; -import org.springframework.http.ResponseCookie; import org.springframework.restdocs.operation.OperationResponse; +import org.springframework.restdocs.operation.ResponseCookie; import org.springframework.test.web.reactive.server.ExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.util.ReflectionUtils; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assume.assumeThat; +import static org.assertj.core.api.Assertions.entry; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; /** @@ -42,15 +40,15 @@ * * @author Andy Wilkinson */ -public class WebTestClientResponseConverterTests { +class WebTestClientResponseConverterTests { private final WebTestClientResponseConverter converter = new WebTestClientResponseConverter(); @Test - public void basicResponse() { + void basicResponse() { ExchangeResult result = WebTestClient .bindToRouterFunction( - RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.ok().syncBody("Hello, World!"))) + RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.ok().bodyValue("Hello, World!"))) .configureClient() .baseUrl("http://localhost") .build() @@ -68,11 +66,14 @@ public void basicResponse() { } @Test - public void responseWithCookie() { + void responseWithCookie() { ExchangeResult result = WebTestClient .bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.ok() - .cookie(ResponseCookie.from("name", "value").domain("localhost").httpOnly(true).build()) + .cookie(org.springframework.http.ResponseCookie.from("name", "value") + .domain("localhost") + .httpOnly(true) + .build()) .build())) .configureClient() .baseUrl("http://localhost") @@ -83,14 +84,15 @@ public void responseWithCookie() { .expectBody() .returnResult(); OperationResponse response = this.converter.convert(result); - assertThat(response.getHeaders()).hasSize(1); - assertThat(response.getHeaders()).containsEntry(HttpHeaders.SET_COOKIE, - Collections.singletonList("name=value; Domain=localhost; HttpOnly")); + assertThat(response.getHeaders().headerSet()).containsOnly( + entry(HttpHeaders.SET_COOKIE, Collections.singletonList("name=value; Domain=localhost; HttpOnly"))); + assertThat(response.getCookies()).hasSize(1); + assertThat(response.getCookies()).first().extracting(ResponseCookie::getName).isEqualTo("name"); + assertThat(response.getCookies()).first().extracting(ResponseCookie::getValue).isEqualTo("value"); } @Test - public void responseWithNonStandardStatusCode() { - assumeThat(ExchangeResult.class, hasMethod("getRawStatusCode")); + void responseWithNonStandardStatusCode() { ExchangeResult result = WebTestClient .bindToRouterFunction(RouterFunctions.route(GET("/foo"), (req) -> ServerResponse.status(210).build())) .configureClient() @@ -102,34 +104,7 @@ public void responseWithNonStandardStatusCode() { .expectBody() .returnResult(); OperationResponse response = this.converter.convert(result); - assertThat(response.getStatusCode()).isEqualTo(210); - } - - private HasMethodMatcher hasMethod(String name) { - return new HasMethodMatcher(name); - } - - private static final class HasMethodMatcher extends BaseMatcher> { - - private final String methodName; - - private HasMethodMatcher(String methodName) { - this.methodName = methodName; - } - - @Override - public boolean matches(Object item) { - if (!(item instanceof Class)) { - return false; - } - return ReflectionUtils.findMethod((Class) item, this.methodName) != null; - } - - @Override - public void describeTo(Description description) { - description.appendText("method '" + this.methodName + "' to exist on class"); - } - + assertThat(response.getStatus()).isEqualTo(HttpStatusCode.valueOf(210)); } } diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java index aaf873166..efa22ebfb 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -18,12 +18,14 @@ import java.net.URI; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.springframework.http.HttpMethod; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.client.ClientRequest; import org.springframework.web.reactive.function.client.ExchangeFunction; @@ -38,16 +40,19 @@ * * @author Andy Wilkinson */ -public class WebTestClientRestDocumentationConfigurerTests { +@ExtendWith(RestDocumentationExtension.class) +class WebTestClientRestDocumentationConfigurerTests { - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); + private WebTestClientRestDocumentationConfigurer configurer; - private final WebTestClientRestDocumentationConfigurer configurer = new WebTestClientRestDocumentationConfigurer( - this.restDocumentation); + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { + this.configurer = new WebTestClientRestDocumentationConfigurer(restDocumentation); + + } @Test - public void configurationCanBeRetrievedButOnlyOnce() { + void configurationCanBeRetrievedButOnlyOnce() { ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1") .build(); @@ -58,7 +63,7 @@ public void configurationCanBeRetrievedButOnlyOnce() { } @Test - public void requestUriHasDefaultsAppliedWhenItHasNoHost() { + void requestUriHasDefaultsAppliedWhenItHasNoHost() { ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test?foo=bar#baz")) .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1") .build(); @@ -70,7 +75,7 @@ public void requestUriHasDefaultsAppliedWhenItHasNoHost() { } @Test - public void requestUriIsNotChangedWhenItHasAHost() { + void requestUriIsNotChangedWhenItHasAHost() { ClientRequest request = ClientRequest .create(HttpMethod.GET, URI.create("https://api.example.com:4567/test?foo=bar#baz")) .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1") diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java index 2344372ce..30db5c4a6 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2023 the original author or authors. + * Copyright 2014-2025 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. @@ -30,15 +30,16 @@ import java.util.stream.Stream; import org.assertj.core.api.Condition; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseCookie; -import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.testfixtures.SnippetConditions; @@ -64,31 +65,29 @@ import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; /** * Integration tests for using Spring REST Docs with Spring Framework's WebTestClient. * * @author Andy Wilkinson */ +@ExtendWith(RestDocumentationExtension.class) public class WebTestClientRestDocumentationIntegrationTests { - @Rule - public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); - private WebTestClient webTestClient; - @Before - public void setUp() { + @BeforeEach + void setUp(RestDocumentationContextProvider restDocumentation) { RouterFunction route = RouterFunctions .route(RequestPredicates.GET("/"), - (request) -> ServerResponse.status(HttpStatus.OK).body(fromObject(new Person("Jane", "Doe")))) + (request) -> ServerResponse.status(HttpStatus.OK).body(fromValue(new Person("Jane", "Doe")))) .andRoute(RequestPredicates.GET("/{foo}/{bar}"), - (request) -> ServerResponse.status(HttpStatus.OK).body(fromObject(new Person("Jane", "Doe")))) + (request) -> ServerResponse.status(HttpStatus.OK).body(fromValue(new Person("Jane", "Doe")))) .andRoute(RequestPredicates.POST("/upload"), (request) -> request.body(BodyExtractors.toMultipartData()) .map((parts) -> ServerResponse.status(HttpStatus.OK).build().block())) @@ -99,12 +98,12 @@ public void setUp() { this.webTestClient = WebTestClient.bindToRouterFunction(route) .configureClient() .baseUrl("https://api.example.com") - .filter(documentationConfiguration(this.restDocumentation)) + .filter(documentationConfiguration(restDocumentation)) .build(); } @Test - public void defaultSnippetGeneration() { + void defaultSnippetGeneration() { File outputDir = new File("build/generated-snippets/default-snippets"); FileSystemUtils.deleteRecursively(outputDir); this.webTestClient.get() @@ -119,7 +118,7 @@ public void defaultSnippetGeneration() { } @Test - public void pathParametersSnippet() { + void pathParametersSnippet() { this.webTestClient.get() .uri("/{foo}/{bar}", "1", "2") .exchange() @@ -136,24 +135,24 @@ public void pathParametersSnippet() { } @Test - public void requestParametersSnippet() { + void queryParametersSnippet() { this.webTestClient.get() .uri("/?a=alpha&b=bravo") .exchange() .expectStatus() .isOk() .expectBody() - .consumeWith(document("request-parameters", - requestParameters(parameterWithName("a").description("Alpha description"), + .consumeWith(document("query-parameters", + queryParameters(parameterWithName("a").description("Alpha description"), parameterWithName("b").description("Bravo description")))); - assertThat(new File("build/generated-snippets/request-parameters/request-parameters.adoc")) + assertThat(new File("build/generated-snippets/query-parameters/query-parameters.adoc")) .has(content(tableWithHeader(TemplateFormats.asciidoctor(), "Parameter", "Description") .row("`a`", "Alpha description") .row("`b`", "Bravo description"))); } @Test - public void multipart() { + void multipart() { MultiValueMap multipartData = new LinkedMultiValueMap<>(); multipartData.add("a", "alpha"); multipartData.add("b", "bravo"); @@ -173,7 +172,7 @@ public void multipart() { } @Test - public void responseWithSetCookie() { + void responseWithSetCookie() { this.webTestClient.get() .uri("/set-cookie") .exchange() @@ -187,7 +186,7 @@ public void responseWithSetCookie() { } @Test - public void curlSnippetWithCookies() { + void curlSnippetWithCookies() { this.webTestClient.get() .uri("/") .cookie("cookieName", "cookieVal") @@ -204,7 +203,7 @@ public void curlSnippetWithCookies() { } @Test - public void curlSnippetWithEmptyParameterQueryString() { + void curlSnippetWithEmptyParameterQueryString() { this.webTestClient.get() .uri("/?a=") .accept(MediaType.APPLICATION_JSON) @@ -220,7 +219,7 @@ public void curlSnippetWithEmptyParameterQueryString() { } @Test - public void httpieSnippetWithCookies() { + void httpieSnippetWithCookies() { this.webTestClient.get() .uri("/") .cookie("cookieName", "cookieVal") @@ -237,7 +236,7 @@ public void httpieSnippetWithCookies() { } @Test - public void illegalStateExceptionShouldBeThrownWhenCallDocumentWebClientNotConfigured() { + void illegalStateExceptionShouldBeThrownWhenCallDocumentWebClientNotConfigured() { assertThatThrownBy(() -> this.webTestClient .mutateWith((builder, httpHandlerBuilder, connector) -> builder.filters(List::clear).build()) .get() @@ -258,7 +257,7 @@ private void assertExpectedSnippetFilesExist(File directory, String... snippets) } private Condition content(final Condition delegate) { - return new Condition() { + return new Condition<>() { @Override public boolean matches(File value) {