diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 1ac4a488..00000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,7 +0,0 @@ -version: 2 -updates: -- package-ecosystem: gradle - directory: "/" - schedule: - interval: weekly - open-pull-requests-limit: 10 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d34ddcc..19e8735d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: Template CI +name: Java CI on: pull_request: @@ -14,10 +14,10 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - name: Set up JDK 11 - uses: actions/setup-java@v1 + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 with: - java-version: 11 + distribution: 'temurin' + java-version: '17' - name: Build run: ./gradlew check diff --git a/README.md b/README.md index cc67643e..e8119736 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ -# Document Generator +# Private Law Document Generator Service [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Build Status](https://travis-ci.org/hmcts/prl-dgs-api.svg?branch=master)](https://travis-ci.org/hmcts/prl-dgs-api) -[![codecov](https://codecov.io/gh/hmcts/prl-dgs-api/branch/master/graph/badge.svg)](https://app.codecov.io/gh/hmcts/prl-dgs-api) [![Documentation](https://img.shields.io/static/v1?label=Documentation&message=DGS&color=informational&logo=confluence)](https://tools.hmcts.net/confluence/display/PL/PDF+document+generator) This is a document generation and template management service. This allows to generate documents based on a @@ -12,23 +10,20 @@ Document Management Store (via Case Document AM). The service provides a single RESTful endpoint that will generate the document, store it in Evidence Management Store and return the link to the stored data. -Updated with master code base until 2.1 +## Dynamic file name -### Dynamic file name -You must pass **dynamic_fileName** key in the **placeholders** map to get a dynamic file name +You must pass `dynamic_fileName` key in the `placeholders` map to get a dynamic file name -### Setup +## Setup -**Prerequisites** +### Prerequisites - [JDK 17](https://openjdk.java.net/) - [Docker](https://www.docker.com) +### Building -***Building*** - -The project uses [Gradle](https://gradle.org) as a build tool but you don't have to install it locally since there is a -`./gradlew` wrapper script. +The project uses [Gradle](https://gradle.org) as a build tool. To build project please execute the following command: @@ -36,7 +31,7 @@ To build project please execute the following command: ./gradlew build ``` -**Running** +### Running First you need to create distribution by executing following command: @@ -56,7 +51,7 @@ After it has finished downloaded run: az login ``` -This should open a browser window for you to login, use your HMCTS account +This should open a browser window for you to log in, use your HMCTS account After logging in run the following command: @@ -74,32 +69,34 @@ docker-compose up ``` As a result the following container(s) will get created and started: - - long living container for API application exposing port `4007` + +- long living container for API application exposing port `4007` #### Troubleshooting ### Managing Preview environment PODs -Make sure you have added the label 'enable_keep_helm' while creating the PR. Otherwise, add the label and re-trigger the build. + +Make sure you have added the label `enable_keep_helm` while creating the PR. Otherwise, add the label and re-trigger the build. ## Testing -**Integration tests** +### Integration tests To run all integration tests locally: -* Make a copy of `src/main/resources/example-application-aat.yml` as `src/main/resources/application-aat.yml` -* Make a copy of `src/integrationTest/resources/example-application-local.properties` as `src/integrationTest/resources/application-local.properties` -* Replace the `replace_me` secrets in the _newly created_ files. You can get the values from SCM and Azure secrets key vault (the new files are in .gitignore and should ***not*** be committed to git) -* Assuming you use IntelliJ, run your application -* And then run your gradle functional tests task -* Or if using command line: - * Start the app with AAT config using `./gradlew clean bootRunAat` - * Start the test with AAT config using `./gradlew clean functional` +- Make a copy of `src/main/resources/example-application-aat.yml` as `src/main/resources/application-aat.yml` +- Make a copy of `src/integrationTest/resources/example-application-local.properties` as `src/integrationTest/resources/application-local.properties` +- Replace the `replace_me` secrets in the _newly created_ files. You can get the values from SCM and Azure secrets key vault (the new files are in .gitignore and should _**not**_ be committed to git) +- Assuming you use IntelliJ, run your application +- And then run your gradle functional tests task +- Or if using command line: + - Start the app with AAT config using `./gradlew clean bootRunAat` + - Start the test with AAT config using `./gradlew clean functional` If you update content in [templates](https://github.com/hmcts/rdo-docmosis-templates), you can re-generate the PDFs by running the ignored test `PDFGenerationTest.ignoreMe_updateGeneratedPdfs`. The test will output generated PDFs to the folder `src/integrationTest/resources/documentgenerator/documents/regenerated` -**Unit tests** +### Unit tests To run all unit tests please execute following command: @@ -107,7 +104,7 @@ To run all unit tests please execute following command: ./gradlew test ``` -**Coding style tests** +### Coding style tests To run all checks (including unit tests) please execute following command: @@ -115,35 +112,22 @@ To run all checks (including unit tests) please execute following command: ./gradlew check ``` -**Mutation tests** - -To run all mutation tests execute the following command: - -```bash -./gradlew pitest -``` - ## Developing -**Flow Diagram** +### Flow Diagram ![diagram](docs/DataFlow.png) -**API documentation** +### API documentation API documentation is provided with Swagger: - - `http://localhost:4007/swagger-ui.html` - UI to interact with the API resources -**Versioning** +- `http://localhost:4007/swagger-ui.html` - UI to interact with the API resources -We use [SemVer](http://semver.org/) for versioning. -For the versions available, see the tags on this repository. - -**Standard API** +### Standard API We follow [RESTful API standards](https://hmcts.github.io/restful-api-standards/). ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details. - diff --git a/build.gradle b/build.gradle index dc54e11d..a827ab3d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,84 +1,56 @@ import org.springframework.boot.gradle.tasks.run.BootRun -buildscript { - ext { - springBootVersion = '2.7.18' - } - repositories { - mavenLocal() - jcenter() - } - dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") - classpath("net.serenity-bdd:serenity-gradle-plugin:2.4.34") - } -} - plugins { id 'application' - id 'checkstyle' - id 'com.github.ben-manes.versions' version '0.51.0' - id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'uk.gov.hmcts.java' version '0.12.65' + id 'com.github.ben-manes.versions' version '0.52.0' + id 'io.spring.dependency-management' version '1.1.7' id 'jacoco' - id 'org.owasp.dependencycheck' version '9.0.4' - id 'org.sonarqube' version '5.0.0.4638' - id 'org.springframework.boot' version '2.7.0' - id 'info.solidsoft.pitest' version '1.7.4' - id 'au.com.dius.pact' version '4.1.7' + id 'org.sonarqube' version '6.1.0.5360' + id 'org.springframework.boot' version '2.7.18' + id 'au.com.dius.pact' version '4.6.17' } -apply plugin: 'net.serenity-bdd.aggregator' -apply plugin: 'com.github.ben-manes.versions' - -group = 'uk.gov.hmcts.reform.prl' -version = '3.0.0' +application { + group = 'uk.gov.hmcts.reform.prl' + mainClass = 'uk.gov.hmcts.reform.prl.documentgenerator.DocumentGeneratorApplication' + version = '0.0.1' +} java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } } -sourceSets { - integrationTest { - java { - compileClasspath += main.output + test.output - runtimeClasspath += main.output + test.output - srcDirs = ['src/integrationTest/java'] - } - resources { - srcDirs = ['src/integrationTest/resources'] - } - } - functionalTest { - java { - compileClasspath += main.output + test.output - runtimeClasspath += main.output + test.output - srcDirs = ['src/functionalTest/java'] - } - resources { - srcDirs = ['src/functionalTest/resources'] - } - } - contractTest { - java { - compileClasspath += main.output - runtimeClasspath += main.output - srcDir file('src/contractTest/java') +repositories { + mavenLocal() + mavenCentral() + maven { url = 'https://jitpack.io' } +} + +def configureSourceSet(String name) { + sourceSets.create(name) { sourceSet -> + sourceSet.java { + compileClasspath += sourceSets.main.output + sourceSets.test.output + runtimeClasspath += sourceSets.main.output + sourceSets.test.output + srcDir "src/${name}/java" } - resources.srcDir file('src/contractTest/resources') + sourceSet.resources.srcDir "src/${name}/resources" } } +['smokeTest', 'integrationTest', 'functionalTest', 'contractTest'].each { configureSourceSet(it) } + configurations { + smokeTestImplementation.extendsFrom testImplementation + smokeTestRuntime.extendsFrom testRuntime integrationTestImplementation.extendsFrom testImplementation integrationTestRuntime.extendsFrom testRuntime functionalTestImplementation.extendsFrom testImplementation functionalTestRuntime.extendsFrom testRuntime contractTestImplementation.extendsFrom testImplementation contractTestRuntime.extendsFrom testRuntime - smokeTestImplementation.extendsFrom testImplementation - smokeTestRuntime.extendsFrom testRuntime } bootJar { @@ -86,11 +58,9 @@ bootJar { attributes 'Implementation-Title': project.name, 'Implementation-Version': project.version } - archiveName 'prl-dgs-api.jar' + archiveFileName = 'prl-dgs-api.jar' } -mainClassName = 'uk.gov.hmcts.reform.prl.documentgenerator.DocumentGeneratorApplication' - compileJava { options.compilerArgs << '-parameters' << '-Xlint:deprecation' } @@ -99,24 +69,6 @@ compileTestJava { options.compilerArgs << '-Xlint:deprecation' } -repositories { - mavenLocal() - jcenter() - - maven { - url "http://repo.maven.apache.org/maven2" - allowInsecureProtocol = true - } - maven { - url 'https://repo.spring.io/libs-milestone' - allowInsecureProtocol = true - } - maven { - url 'https://jitpack.io' - allowInsecureProtocol = true - } -} - distributions { main { contents { @@ -127,400 +79,194 @@ distributions { } } -tasks.withType(JavaCompile) { +tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' } -checkstyle { - toolVersion = '9.2.1' - configFile = project(':').file('checkstyle.xml') - configProperties = ["suppressionFile": project(':').file('suppressions.xml')] -} - -// make build fail on Checkstyle issues (https://github.com/gradle/gradle/issues/881) -tasks.withType(Checkstyle).each { checkstyleTask -> - checkstyleTask.doLast { - reports.all { report -> - def outputFile = report.destination - if (outputFile.exists() && outputFile.text.contains(" + systemProperty 'spring.profiles.active', 'aat' } - resources.srcDir file('src/smokeTest/resources') - } } -dependencies { - integrationTestImplementation(sourceSets.test.output) - integrationTestAnnotationProcessor group: 'org.projectlombok', name: 'lombok', version: versions.lombok - functionalTestImplementation(sourceSets.test.output) - functionalTestAnnotationProcessor group: 'org.projectlombok', name: 'lombok', version: versions.lombok +tasks.register('fortifyScan', JavaExec) { + mainClass = "uk.gov.hmcts.fortifyclient.FortifyClientMainApp" + classpath += sourceSets.test.runtimeClasspath + jvmArgs = ['--add-opens=java.base/java.lang.reflect=ALL-UNNAMED'] } -task smoke(type: Test, description: 'Runs the smoke tests.', group: 'Verification') { - useJUnitPlatform() - - setTestClassesDirs(sourceSets.smokeTest.output.classesDirs) - setClasspath(sourceSets.smokeTest.runtimeClasspath) +tasks.withType(Test).configureEach { + useJUnitPlatform() } -task bootRunAat(type: BootRun, description: 'Runs the app using AAT config', dependsOn: 'classes', group: 'Application') { - main = 'uk.gov.hmcts.reform.prl.documentgenerator.DocumentGeneratorApplication' - doFirst() { - classpath = sourceSets.main.runtimeClasspath - systemProperties = System.properties - systemProperty 'spring.profiles.active', 'aat' - } +tasks.register('smoke', Test) { + description = 'Runs the smoke tests.' + group = 'Verification' + setTestClassesDirs(sourceSets.smokeTest.output.classesDirs) + setClasspath(sourceSets.smokeTest.runtimeClasspath) } -task functional(type: Test, description: 'Runs the functional tests.', group: 'Verification') { - useJUnitPlatform() +tasks.register('functional', Test) { + description = 'Runs the functional tests.' + group = 'Verification' setTestClassesDirs(sourceSets.functionalTest.output.classesDirs) setClasspath(sourceSets.functionalTest.runtimeClasspath) - - finalizedBy aggregate } -task integration(type: Test, description: 'Runs the integration tests.', group: 'Verification') { - setTestClassesDirs(sourceSets.integrationTest.output.classesDirs) - setClasspath(sourceSets.integrationTest.runtimeClasspath) - - finalizedBy aggregate +tasks.register('integration', Test) { + description = 'Runs the integration tests.' + group = 'Verification' + setTestClassesDirs(sourceSets.integrationTest.output.classesDirs) + setClasspath(sourceSets.integrationTest.runtimeClasspath) } -task contract(type: Test) { - group = 'Delivery pipeline' - description = 'Runs the consumer Pact tests' - useJUnitPlatform() +tasks.register('contract', Test) { + description = 'Runs the contract tests.' + group = 'Verification' testClassesDirs = sourceSets.contractTest.output.classesDirs classpath = sourceSets.contractTest.runtimeClasspath - systemProperty 'pact.rootDir', "pacts" + systemProperty 'pact.rootDir', "src/contractTest/resources/pacts" } +tasks.register('runAndPublishConsumerPactTests', Test) { + description = 'Runs the contract tests and publishes pacts to the broker.' + logger.lifecycle("Runs the pact Tests") + dependsOn 'contract' + finalizedBy 'pactPublish' + testClassesDirs = sourceSets.contractTest.output.classesDirs + classpath = sourceSets.contractTest.runtimeClasspath +} -task printVersion { - doLast { - print project.version - } +processIntegrationTestResources { + duplicatesStrategy = DuplicatesStrategy.INCLUDE } -pitest { - targetClasses = ['uk.gov.hmcts.reform.prl.documentgenerator.*'] - excludedClasses = ['uk.gov.hmcts.reform.prl.documentgenerator.config.*', - 'uk.gov.hmcts.reform.prl.documentgenerator.domain.*', - 'uk.gov.hmcts.reform.prl.documentgenerator.exception.*'] - threads = 10 - outputFormats = ['XML', 'HTML'] - timestampedReports = true - mutationThreshold = 80 +processFunctionalTestResources { + duplicatesStrategy = DuplicatesStrategy.INCLUDE +} + +processContractTestResources { + duplicatesStrategy = DuplicatesStrategy.INCLUDE } -task developAddRelaseSuffix() { - version = "${version}-SNAPSHOT" +jacoco { + toolVersion = "0.8.12" } jacocoTestReport { executionData(test) reports { - xml.enabled = true - html.enabled = true - xml.destination file("${buildDir}/reports/jacoco/test/jacocoTestReport.xml") + xml.getRequired().set(true) + html.getRequired().set(true) + xml.outputLocation = file("${layout.buildDirectory.get()}/reports/jacoco/test/jacocoTestReport.xml") } } @@ -534,8 +280,6 @@ jacocoTestCoverageVerification { } } -project.tasks['sonarqube'].dependsOn jacocoTestReport - def sonarExclusions = [ '**uk/gov/hmcts/reform/prl/documentgenerator/domain/**/*', '**uk/gov/hmcts/reform/prl/documentgenerator/exception/*', @@ -543,46 +287,28 @@ def sonarExclusions = [ '**uk/gov/hmcts/reform/prl/documentgenerator/DocumentGeneratorApplication.java' ] +tasks.sonarqube.dependsOn(jacocoTestReport) + sonarqube { properties { property "sonar.projectName", "Family Private Law :: prl-dgs" property "sonar.projectKey", "prl-dgs-api" property "sonar.exclusions", sonarExclusions.join(", ") - property "sonar.coverage.jacoco.xmlReportPaths", "${jacocoTestReport.reports.xml.destination.path}" - property "sonar.pitest.mode", "reuseReport" - property "sonar.pitest.reportsDirectory", "build/reports/pitest" + property "sonar.coverage.jacoco.xmlReportPaths", "${jacocoTestReport.reports.xml.outputLocation.get()}" } } -def debug = System.getProperty("debug") -run { - if (debug == 'true') { - jvmArgs = ['-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5010'] - } +static def getCheckedOutGitCommitHash() { + 'git rev-parse --verify --short HEAD'.execute().text.trim() } project.ext { - pactVersion = getCheckedOutGitCommitHash() -} - -task runAndPublishConsumerPactTests(type: Test){ - logger.lifecycle("Runs pact Tests") - testClassesDirs = sourceSets.contractTest.output.classesDirs - classpath = sourceSets.contractTest.runtimeClasspath - -} - -runAndPublishConsumerPactTests.dependsOn contract - -runAndPublishConsumerPactTests.finalizedBy pactPublish - -def getCheckedOutGitCommitHash() { - 'git rev-parse --verify --short HEAD'.execute().text.trim() + pactVersion = getCheckedOutGitCommitHash() } pact { publish { - pactDirectory = 'pacts' + pactDirectory = 'src/contractTest/resources/pacts' pactBrokerUrl = System.getenv("PACT_BROKER_FULL_URL") ?: 'http://localhost:80' tags = [System.getenv("PACT_BRANCH_NAME") ?:'Dev'] version = project.pactVersion diff --git a/checkstyle.xml b/checkstyle.xml deleted file mode 100644 index 8c12645c..00000000 --- a/checkstyle.xml +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml deleted file mode 100644 index 25743d96..00000000 --- a/config/checkstyle/checkstyle.xml +++ /dev/null @@ -1,251 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/owasp/suppressions.xml b/config/owasp/suppressions.xml index fbf9371b..fe989add 100644 --- a/config/owasp/suppressions.xml +++ b/config/owasp/suppressions.xml @@ -1,3 +1,35 @@ + + + ^pkg:maven/net\.minidev/json-smart@.*$ + CVE-2023-1370 + + + Vulnerability in spring boot 2.x.x> + CVE-2023-20873 + CVE-2023-20883 + CVE-2023-34055 + + + + ^pkg:maven/com\.fasterxml\.jackson\.core/jackson-databind@.*$ + CVE-2023-35116 + + + Vulnerability in logback> + CVE-2023-6378 + CVE-2023-6481 + + + + ^pkg:maven/org\.yaml/snakeyaml@.*$ + CVE-2022-1471 + CVE-2022-25857 + CVE-2022-38749 + CVE-2022-38751 + CVE-2022-38752 + CVE-2022-41854 + CVE-2022-38750 + diff --git a/config/pmd/ruleset.xml b/config/pmd/ruleset.xml deleted file mode 100644 index 03b66c19..00000000 --- a/config/pmd/ruleset.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - HMCTS PMD rule set - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dependency-check-suppressions.xml b/dependency-check-suppressions.xml deleted file mode 100644 index e69de29b..00000000 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 5c2d1cf0..9bbc975c 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 263b8f24..37f853b1 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Mon Feb 10 11:27:21 GMT 2020 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip diff --git a/gradlew b/gradlew index 9e23ef4a..faf93008 100755 --- a/gradlew +++ b/gradlew @@ -1,13 +1,13 @@ -#!/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. # You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# 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, @@ -15,80 +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="" +# 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 + # 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 @@ -97,92 +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" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# 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\"" + 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=$((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" -# 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")" +# 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" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 8bc24402..9d21a218 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -5,7 +5,7 @@ @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 http://www.apache.org/licenses/LICENSE-2.0 +@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, @@ -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,25 +27,29 @@ 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% +@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= +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 +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 @@ -51,48 +57,36 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +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 -: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% +"%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 +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/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/CdamApiConsumerTest.java b/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/CdamApiConsumerTest.java index 79e66102..9f62f0a2 100644 --- a/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/CdamApiConsumerTest.java +++ b/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/CdamApiConsumerTest.java @@ -1,7 +1,6 @@ package uk.gov.hmcts.reform.prl.documentgenerator; import au.com.dius.pact.consumer.MockServer; -import au.com.dius.pact.consumer.dsl.PactDslJsonBody; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.consumer.junit5.PactConsumerTestExt; import au.com.dius.pact.consumer.junit5.PactTestFor; @@ -13,7 +12,7 @@ import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.json.JSONException; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -25,47 +24,41 @@ import static org.junit.jupiter.api.Assertions.assertEquals; - @ExtendWith(PactConsumerTestExt.class) @ExtendWith(SpringExtension.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @PactTestFor(providerName = "CCD_CASE_DOCS_AM_API", port = "5170") -@PactFolder("pacts") -@SpringBootTest({ - "CCD_CASE_DOCS_AM_API:http://localhost:5170" -}) +@PactFolder("src/contractTest/resources/pacts") +@SpringBootTest("CCD_CASE_DOCS_AM_API = http://localhost:5170") public class CdamApiConsumerTest { - private static final String SERVICE_AUTHORIZATION_HEADER = "ServiceAuthorization"; - private static final String someServiceAuthToken = "someServiceAuthToken"; - private static final String invalidServiceAuthToken = "invalidServiceAuthToken"; + private static final String SERVICE_AUTH_TOKEN = "someServiceAuthToken"; + private static final String INVALID_SERVICE_AUTH_TOKEN = "invalidServiceAuthToken"; private static final String AUTHORIZATION_HEADER = "Authorization"; - private static final String someAuthToken = "someAuthToken"; - private static final String someDocumentId = "456c0976-3178-46dd-b9ce-5ab5d47c625a"; - + private static final String SOME_AUTH_TOKEN = "someAuthToken"; + private static final String SOME_DOCUMENT_ID = "456c0976-3178-46dd-b9ce-5ab5d47c625a"; @BeforeEach - public void setUpEachTest() throws InterruptedException, IOException { + public void setUpEachTest() throws InterruptedException { Thread.sleep(2000); } - @After + @AfterEach void teardown() { Executor.closeIdleConnections(); } @Pact(provider = "CCD_CASE_DOCS_AM_API", consumer = "prl-dgs-api") - RequestResponsePact downloadDocument(PactDslWithProvider builder) throws JSONException, IOException { - // @formatter:off + RequestResponsePact downloadDocument(PactDslWithProvider builder) throws JSONException { return builder .given("A request to download a document") .uponReceiving("a request to download a valid document") .method("GET") - .headers(SERVICE_AUTHORIZATION_HEADER, someServiceAuthToken) - .headers(AUTHORIZATION_HEADER, someAuthToken) - .path("/cases/documents/" + someDocumentId) + .headers(SERVICE_AUTHORIZATION_HEADER, SERVICE_AUTH_TOKEN) + .headers(AUTHORIZATION_HEADER, SOME_AUTH_TOKEN) + .path("/cases/documents/" + SOME_DOCUMENT_ID) .willRespondWith() .matchHeader(org.springframework.http.HttpHeaders.CONTENT_TYPE, "application/vnd.uk.gov.hmcts.dm.document.v1+hal+json;charset=UTF-8") @@ -77,25 +70,25 @@ RequestResponsePact downloadDocument(PactDslWithProvider builder) throws JSONExc @PactTestFor(pactMethod = "downloadDocument") public void verifyDownloadDocument(MockServer mockServer) throws IOException { - HttpResponse downloadDocumentResponse = Request.Get(mockServer.getUrl() + "/cases/documents/" + someDocumentId) - .addHeader(SERVICE_AUTHORIZATION_HEADER, someServiceAuthToken) - .addHeader(AUTHORIZATION_HEADER, someAuthToken) + HttpResponse downloadDocumentResponse = Request.Get( + mockServer.getUrl() + "/cases/documents/" + SOME_DOCUMENT_ID + ) + .addHeader(SERVICE_AUTHORIZATION_HEADER, SERVICE_AUTH_TOKEN) + .addHeader(AUTHORIZATION_HEADER, SOME_AUTH_TOKEN) .execute().returnResponse(); - assertEquals(200, downloadDocumentResponse.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, downloadDocumentResponse.getStatusLine().getStatusCode()); } - @Pact(provider = "CCD_CASE_DOCS_AM_API", consumer = "prl-dgs-api") - RequestResponsePact noAuthDownloadDocument(PactDslWithProvider builder) throws JSONException, IOException { - // @formatter:off + RequestResponsePact noAuthDownloadDocument(PactDslWithProvider builder) throws JSONException { return builder .given("A request to download a document") .uponReceiving("a request to download a valid document with invalid authorisation") .method("GET") - .headers(SERVICE_AUTHORIZATION_HEADER, invalidServiceAuthToken) - .path("/cases/documents/" + someDocumentId) + .headers(SERVICE_AUTHORIZATION_HEADER, INVALID_SERVICE_AUTH_TOKEN) + .path("/cases/documents/" + SOME_DOCUMENT_ID) .willRespondWith() .matchHeader(org.springframework.http.HttpHeaders.CONTENT_TYPE, "application/vnd.uk.gov.hmcts.dm.document.v1+hal+json;charset=UTF-8") @@ -103,33 +96,26 @@ RequestResponsePact noAuthDownloadDocument(PactDslWithProvider builder) throws J .toPact(); } - @Test @PactTestFor(pactMethod = "noAuthDownloadDocument") public void verifyNoAuthDownloadDocument(MockServer mockServer) throws IOException { - HttpResponse downloadDocumentResponse = Request.Get(mockServer.getUrl() + "/cases/documents/" + someDocumentId) - .addHeader(SERVICE_AUTHORIZATION_HEADER, invalidServiceAuthToken).execute().returnResponse(); - - assertEquals(500, downloadDocumentResponse.getStatusLine().getStatusCode()); + HttpResponse downloadDocumentResponse = Request.Get( + mockServer.getUrl() + "/cases/documents/" + SOME_DOCUMENT_ID + ) + .addHeader(SERVICE_AUTHORIZATION_HEADER, INVALID_SERVICE_AUTH_TOKEN).execute().returnResponse(); + assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, downloadDocumentResponse.getStatusLine().getStatusCode()); } @Pact(provider = "CCD_CASE_DOCS_AM_API", consumer = "prl-dgs-api") - RequestResponsePact uploadDocument(PactDslWithProvider builder) throws JSONException, IOException { - // @formatter:off - - PactDslJsonBody body = new PactDslJsonBody() - .stringMatcher("caseTypeId", "PRLAPPS") - .stringMatcher("jurisdictionId", "PRIVATELAW") - .asBody(); - + RequestResponsePact uploadDocument(PactDslWithProvider builder) throws JSONException { return builder .given("A request to upload a document") .uponReceiving("a request to upload a document with valid authorization") .method("POST") - .headers(SERVICE_AUTHORIZATION_HEADER, someServiceAuthToken) - .headers(AUTHORIZATION_HEADER, someAuthToken) + .headers(SERVICE_AUTHORIZATION_HEADER, SERVICE_AUTH_TOKEN) + .headers(AUTHORIZATION_HEADER, SOME_AUTH_TOKEN) .path("/cases/documents") .willRespondWith() .status(HttpStatus.SC_OK) @@ -140,12 +126,12 @@ RequestResponsePact uploadDocument(PactDslWithProvider builder) throws JSONExcep @PactTestFor(pactMethod = "uploadDocument") public void verifyUploadDocument(MockServer mockServer) throws IOException { - HttpResponse downloadDocumentResponse = Request.Post(mockServer.getUrl() + "/cases/documents" ) - .addHeader(SERVICE_AUTHORIZATION_HEADER, someServiceAuthToken) - .addHeader(AUTHORIZATION_HEADER, someAuthToken) + HttpResponse downloadDocumentResponse = Request.Post(mockServer.getUrl() + "/cases/documents") + .addHeader(SERVICE_AUTHORIZATION_HEADER, SERVICE_AUTH_TOKEN) + .addHeader(AUTHORIZATION_HEADER, SOME_AUTH_TOKEN) .execute().returnResponse(); - assertEquals(200, downloadDocumentResponse.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, downloadDocumentResponse.getStatusLine().getStatusCode()); } } diff --git a/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/PdfGenerationServiceConsumerTest.java b/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/PdfGenerationServiceConsumerTest.java index 68c1746e..625c65d5 100644 --- a/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/PdfGenerationServiceConsumerTest.java +++ b/src/contractTest/java/uk/gov/hmcts/reform/prl/documentgenerator/PdfGenerationServiceConsumerTest.java @@ -17,25 +17,17 @@ import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.json.JSONException; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.util.ResourceUtils; -import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; import uk.gov.hmcts.reform.prl.documentgenerator.domain.request.GenerateDocumentRequest; -import uk.gov.hmcts.reform.prl.documentgenerator.service.TemplateManagementService; -import uk.gov.hmcts.reform.prl.documentgenerator.service.impl.DocmosisPDFGenerationServiceImpl; -import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; -import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -44,49 +36,36 @@ @ExtendWith(SpringExtension.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @PactTestFor(providerName = "rpePdfService_PDFGenerationEndpointV2", port = "8891") -@PactFolder("pacts") -@SpringBootTest({ - "service.pdf-service.uri : http://localhost:8891/pdfs" -}) +@PactFolder("src/contractTest/resources/pacts") +@SpringBootTest("service.pdf-service.uri = http://localhost:8891/pdfs") public class PdfGenerationServiceConsumerTest { - private static final String SERVICE_AUTHORIZATION_HEADER = "ServiceAuthorization"; - - - @Autowired - DocmosisPDFGenerationServiceImpl docmosisPDFGenerationService; - @Autowired ObjectMapper objectMapper; - @MockBean - private AuthTokenGenerator serviceTokenGenerator; - @MockBean - private TemplateManagementService templateManagementService; - private final String someServiceAuthToken = "someServiceAuthToken"; - private final String template = "
Case number: {{ caseNo }}
"; - private Map placeholders = Map.of("caseNo", "12345"); + private static final String SERVICE_AUTHORIZATION_HEADER = "ServiceAuthorization"; + private static final String SERVICE_AUTH_TOKEN = "someServiceAuthToken"; + private static final String TEMPLATE = "
Case number: {{ caseNo }}
"; + private final Map placeholders = Map.of("caseNo", "12345"); @BeforeEach - public void setUpEachTest() throws InterruptedException, IOException { + public void setUpEachTest() throws InterruptedException { Thread.sleep(2000); } - @After + @AfterEach void teardown() { Executor.closeIdleConnections(); } @Pact(provider = "rpePdfService_PDFGenerationEndpointV2", consumer = "prl_documentGeneratorClient") RequestResponsePact generatePdfFromTemplate(PactDslWithProvider builder) throws JSONException, IOException { - // @formatter:off - return builder .given("A request to generate a pdf document") .uponReceiving("a request to generate a pdf document with a template") .method("POST") - .headers(SERVICE_AUTHORIZATION_HEADER, someServiceAuthToken) - .body(createJsonObject(new GenerateDocumentRequest(template, placeholders)), + .headers(SERVICE_AUTHORIZATION_HEADER, SERVICE_AUTH_TOKEN) + .body(createJsonObject(new GenerateDocumentRequest(TEMPLATE, placeholders)), "application/vnd.uk.gov.hmcts.pdf-service.v2+json;charset=UTF-8") .path("/pdfs") .willRespondWith() @@ -99,21 +78,11 @@ RequestResponsePact generatePdfFromTemplate(PactDslWithProvider builder) throws @Test @PactTestFor(pactMethod = "generatePdfFromTemplate") public void verifyGeneratePdfFromTemplatePact(MockServer mockServer) throws IOException, JSONException { - //Map placeholders = new HashMap<>(); - //placeholders.put(CASE_DETAILS, new HashMap<>(ImmutableMap.of( - // "case_data", new HashMap<>() - //))); - // - //when(templateManagementService.getTemplateByName("someTemplateName")).thenReturn(template.getBytes()); - //when(serviceTokenGenerator.generate()).thenReturn(someServiceAuthToken); - // - //byte[] response = docmosisPDFGenerationService.generate("someTemplateName", placeholders); - HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(mockServer.getUrl() + "/pdfs"); - StringEntity json = new StringEntity(createJsonObject(new GenerateDocumentRequest(template, placeholders))); - request.addHeader(SERVICE_AUTHORIZATION_HEADER, someServiceAuthToken); + StringEntity json = new StringEntity(createJsonObject(new GenerateDocumentRequest(TEMPLATE, placeholders))); + request.addHeader(SERVICE_AUTHORIZATION_HEADER, SERVICE_AUTH_TOKEN); request.addHeader("content-type", "application/vnd.uk.gov.hmcts.pdf-service.v2+json;charset=UTF-8"); request.setEntity(json); @@ -121,23 +90,13 @@ public void verifyGeneratePdfFromTemplatePact(MockServer mockServer) throws IOEx String responseContentType = generateDocumentResponse.getEntity().getContentType().toString(); - assertEquals(200, generateDocumentResponse.getStatusLine().getStatusCode()); + assertEquals(HttpStatus.SC_OK, generateDocumentResponse.getStatusLine().getStatusCode()); assertEquals("Content-Type: application/pdf", responseContentType); } - private File getFile(String fileName) throws FileNotFoundException { - return ResourceUtils.getFile(this.getClass().getResource("/json/" + fileName)); - } - protected String createJsonObject(Object obj) throws JSONException, IOException { return objectMapper.writeValueAsString(obj); } - private GenerateDocumentRequest buildGenerateDocumentRequest() { - Map placeholders = new HashMap<>(); - placeholders.put("caseNo", "12345"); - - return new GenerateDocumentRequest(template, placeholders); - } } diff --git a/pacts/prl-dgs-api-CCD_CASE_DOCS_AM_API.json b/src/contractTest/resources/pacts/prl-dgs-api-CCD_CASE_DOCS_AM_API.json similarity index 90% rename from pacts/prl-dgs-api-CCD_CASE_DOCS_AM_API.json rename to src/contractTest/resources/pacts/prl-dgs-api-CCD_CASE_DOCS_AM_API.json index abd6f195..7a0782d2 100644 --- a/pacts/prl-dgs-api-CCD_CASE_DOCS_AM_API.json +++ b/src/contractTest/resources/pacts/prl-dgs-api-CCD_CASE_DOCS_AM_API.json @@ -19,7 +19,7 @@ "response": { "status": 200, "headers": { - "Content-Type": "application/vnd\u63AFuk\u98E0gov\u8E83hmcts\uED68dm\u347Adocument\u7C16v1haljson;charset=UTF-8" + "Content-Type": "application/vnd\uB91Auk\uDF6Dgov\u8E2Dhmcts\u9024dm\u8C79document\u32B4v11halljson;charset=UTF-8" }, "matchingRules": { "header": { @@ -53,7 +53,7 @@ "response": { "status": 500, "headers": { - "Content-Type": "application/vnd\uF5A0uk\uE1D7gov\u0205hmcts\u0E15dm\uCDCDdocument\u0B01v111haljson;charset=UTF-8" + "Content-Type": "application/vnd\u054Auk\uD76Cgov\uCC92hmcts\u28DDdm\uF2D3document\u9D3Ev1hallllljson;charset=UTF-8" }, "matchingRules": { "header": { diff --git a/pacts/prl_documentGeneratorClient-rpePdfService_PDFGenerationEndpointV2.json b/src/contractTest/resources/pacts/prl_documentGeneratorClient-rpePdfService_PDFGenerationEndpointV2.json similarity index 100% rename from pacts/prl_documentGeneratorClient-rpePdfService_PDFGenerationEndpointV2.json rename to src/contractTest/resources/pacts/prl_documentGeneratorClient-rpePdfService_PDFGenerationEndpointV2.json diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateAndStoreE2ETest.java b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateAndStoreE2ETest.java index 3129aa76..47201d74 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateAndStoreE2ETest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateAndStoreE2ETest.java @@ -1,23 +1,20 @@ package uk.gov.hmcts.reform.prl.functionaltest; import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; import com.github.tomakehurst.wiremock.junit5.WireMockExtension; -import org.junit.ClassRule; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.PropertySource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import uk.gov.hmcts.reform.ccd.document.am.model.Document; @@ -33,7 +30,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -45,8 +42,11 @@ import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_HASH_TOKEN; -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = DocumentGeneratorApplication.class) +@ExtendWith(SpringExtension.class) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = DocumentGeneratorApplication.class +) @AutoConfigureMockMvc @PropertySource(value = "classpath:application.yml") public class DocumentGenerateAndStoreE2ETest { @@ -54,28 +54,25 @@ public class DocumentGenerateAndStoreE2ETest { private static final String CASE_DOCS_API_URL = "/cases/documents"; private static final String DOCMOSIS_API_URL = "/rs/render"; private static final String S2S_API_URL = "/lease"; - private static final String CASE_DETAILS = "caseDetails"; private static final String CASE_DATA = "case_data"; - private static final String TEST_EXAMPLE = "FL-DIV-GOR-ENG-00062.docx"; @Autowired private MockMvc webClient; @RegisterExtension - public static WireMockExtension caseDocsClientApiServiceServer = WireMockExtension.newInstance().options( + public static final WireMockExtension caseDocsClientApiServiceServer = WireMockExtension.newInstance().options( wireMockConfig().port(5170)).build(); @RegisterExtension - public static WireMockExtension docmosisClientServiceServer = WireMockExtension.newInstance().options( + public static final WireMockExtension docmosisClientServiceServer = WireMockExtension.newInstance().options( wireMockConfig().port(5501)).build(); @RegisterExtension - public static WireMockExtension serviceAuthServer = WireMockExtension.newInstance().options( + public static final WireMockExtension serviceAuthServer = WireMockExtension.newInstance().options( wireMockConfig().port(4502)).build(); - private void perform(String template) throws Exception { final Map values = Collections.emptyMap(); @@ -91,21 +88,21 @@ private void perform(String template) throws Exception { @ParameterizedTest @NullSource @ValueSource(strings = {" ", "nonExistingTemplate"}) - public void givenTemplateNameIsBlankOrNullOrTemplateNotFound_whenGenerateAndStoreDocument_thenReturnHttp400(String template) throws Exception { + public void givenTemplateNameIsBlankOrNullOrTemplateNotFoundWhenGenerateAndStoreDocumentThenReturnHttp400( + String template) throws Exception { perform(template); } @Test - public void givenCouldNotConnectToAuthService_whenGenerateAndStoreDocument_thenReturnHttp503() throws Exception { - Map caseData = new HashMap<>(); + public void givenCouldNotConnectToAuthServiceWhenGenerateAndStoreDocumentThenReturnHttp503() throws Exception { Map requestData = Collections.singletonMap( - CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData) + CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>()) ); final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(TEST_EXAMPLE, requestData); - mockDocmosisPdfService(HttpStatus.OK, new byte[] {1}); + mockDocmosisPdfService(new byte[] {1}); mockServiceAuthServer(HttpStatus.SERVICE_UNAVAILABLE, ""); webClient.perform(post(API_URL) @@ -116,15 +113,15 @@ public void givenCouldNotConnectToAuthService_whenGenerateAndStoreDocument_thenR } @Test - public void givenAuthServiceReturnAuthenticationError_whenGenerateAndStoreDocument_thenReturnHttp401() throws Exception { - Map caseData = new HashMap<>(); + public void givenAuthServiceReturnAuthenticationErrorWhenGenerateAndStoreDocumentThenReturnHttp401() + throws Exception { Map requestData = Collections.singletonMap( - CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData) + CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>()) ); final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(TEST_EXAMPLE, requestData); - mockDocmosisPdfService(HttpStatus.OK, new byte[] {1}); + mockDocmosisPdfService(new byte[] {1}); mockServiceAuthServer(HttpStatus.UNAUTHORIZED, ""); webClient.perform(post(API_URL) @@ -135,12 +132,12 @@ public void givenAuthServiceReturnAuthenticationError_whenGenerateAndStoreDocume } @Test - public void givenAllGoesWellForTestExample_whenGenerateAndStoreDocument_thenReturn() + public void givenAllGoesWellForTestExampleWhenGenerateAndStoreDocumentThenReturn() throws Exception { - assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(TEST_EXAMPLE); + assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(); } - private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String templateId) throws Exception { + private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments() throws Exception { //Given final Map caseData = Collections.emptyMap(); final Map values = new HashMap<>(); @@ -149,12 +146,13 @@ private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String + "3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI"; final UploadResponse uploadResponse = new UploadResponse(List.of(mockCaseDocsDocuments())); - mockDocmosisPdfService(HttpStatus.OK, new byte[]{1}); - mockCaseDocsClientApi(HttpStatus.OK, uploadResponse); + mockDocmosisPdfService(new byte[]{1}); + mockCaseDocsClientApi(uploadResponse); mockServiceAuthServer(HttpStatus.OK, s2sAuthToken); //When - final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(templateId, values); + final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest( + DocumentGenerateAndStoreE2ETest.TEST_EXAMPLE, values); MvcResult result = webClient.perform(post(API_URL) .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) .contentType(MediaType.APPLICATION_JSON) @@ -164,25 +162,26 @@ private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String //Then final GeneratedDocumentInfo generatedDocumentInfo = getGeneratedDocumentInfo(); - assertEquals(ObjectMapperTestUtil.convertObjectToJsonString(generatedDocumentInfo), result.getResponse().getContentAsString()); + assertEquals( + ObjectMapperTestUtil.convertObjectToJsonString(generatedDocumentInfo), + result.getResponse().getContentAsString() + ); } private GeneratedDocumentInfo getGeneratedDocumentInfo() { - GeneratedDocumentInfo generatedDocumentInfo = GeneratedDocumentInfo.builder() + return GeneratedDocumentInfo.builder() .url(FILE_URL) .hashToken(TEST_HASH_TOKEN) .mimeType(MIME_TYPE) .binaryUrl(BINARY_URL) .docName("TestTemplate.pdf") .build(); - - return generatedDocumentInfo; } - private void mockDocmosisPdfService(HttpStatus expectedResponse, byte[] body) { + private void mockDocmosisPdfService(byte[] body) { docmosisClientServiceServer.stubFor(WireMock.post(DOCMOSIS_API_URL) .willReturn(aResponse() - .withStatus(expectedResponse.value()) + .withStatus(HttpStatus.OK.value()) .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) .withBody(ObjectMapperTestUtil.convertObjectToJsonString(body)) )); @@ -197,10 +196,10 @@ private void mockServiceAuthServer(HttpStatus expectedResponse, String body) { )); } - private void mockCaseDocsClientApi(HttpStatus expectedResponse, UploadResponse uploadResponse) { + private void mockCaseDocsClientApi(UploadResponse uploadResponse) { caseDocsClientApiServiceServer.stubFor(WireMock.post(CASE_DOCS_API_URL) .willReturn(aResponse() - .withStatus(expectedResponse.value()) + .withStatus(HttpStatus.OK.value()) .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) .withBody(ObjectMapperTestUtil.convertObjectToJsonString(uploadResponse)) )); @@ -210,7 +209,7 @@ public static Document mockCaseDocsDocuments() { Document.Link link = new Document.Link(); Document.Link linkBinary = new Document.Link(); link.href = FILE_URL; - linkBinary.href = BINARY_URL ; + linkBinary.href = BINARY_URL; Document.Links links = new Document.Links(); links.self = link; @@ -223,4 +222,5 @@ public static Document mockCaseDocsDocuments() { .originalDocumentName(TEST_DEFAULT_NAME_FOR_PDF_FILE) .build(); } + } diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateControllerFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateControllerFunctionalTest.java index 2abe42f0..12bda425 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateControllerFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/DocumentGenerateControllerFunctionalTest.java @@ -1,24 +1,23 @@ package uk.gov.hmcts.reform.prl.functionaltest; -import groovy.util.logging.Slf4j; -import io.restassured.RestAssured; import io.restassured.specification.RequestSpecification; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.prl.documentgenerator.DocumentGeneratorApplication; -@RunWith(SpringRunner.class) +import static io.restassured.RestAssured.given; + +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = DocumentGeneratorApplication.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @PropertySource(value = "classpath:application.yml") public class DocumentGenerateControllerFunctionalTest { - private final String userToken = "Bearer testToken"; - + private static final String USER_TOKEN = "Bearer testToken"; private static final String VALID_REQUEST_BODY = "documentgenerator/da.json"; private final String targetInstance = @@ -27,14 +26,12 @@ public class DocumentGenerateControllerFunctionalTest { "http://localhost:4007" ); - private final RequestSpecification request = RestAssured.given().relaxedHTTPSValidation().baseUri(targetInstance); - + private final RequestSpecification request = given().relaxedHTTPSValidation().baseUri(targetInstance); @Test - public void givenNoRequestBodyReturn400FromGenerateAndUploadPdf() throws Exception { - String requestBody = ResourceLoader.loadJson(VALID_REQUEST_BODY); + public void givenNoRequestBodyReturn400FromGenerateAndUploadPdf() { request - .header("Authorization", userToken) + .header("Authorization", USER_TOKEN) .when() .contentType("application/json") .post("/version/1/generatePDF") @@ -43,10 +40,9 @@ public void givenNoRequestBodyReturn400FromGenerateAndUploadPdf() throws Excepti } @Test - public void givenNoRequestBodyReturn400FromGenerateAndDraftPdf() throws Exception { - String requestBody = ResourceLoader.loadJson(VALID_REQUEST_BODY); + public void givenNoRequestBodyReturn400FromGenerateAndDraftPdf() { request - .header("Authorization", userToken) + .header("Authorization", USER_TOKEN) .when() .contentType("application/json") .post("/version/1/generateDraftPDF") diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/ResourceLoader.java b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/ResourceLoader.java index 37005008..fd38779b 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/ResourceLoader.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/ResourceLoader.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URL; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; @@ -11,7 +10,7 @@ public class ResourceLoader { public static String loadJson(final String filePath) throws Exception { - return new String(loadResource(filePath), Charset.forName(StandardCharsets.UTF_8.name())); + return new String(loadResource(filePath), StandardCharsets.UTF_8); } public static byte[] loadResource(final String filePath) throws Exception { diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/RootControllerFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/RootControllerFunctionalTest.java index e273e8ef..0903ce7d 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/RootControllerFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/prl/functionaltest/RootControllerFunctionalTest.java @@ -1,14 +1,14 @@ package uk.gov.hmcts.reform.prl.functionaltest; -import io.restassured.RestAssured; import io.restassured.specification.RequestSpecification; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; -public class RootControllerFunctionalTest { +import static io.restassured.RestAssured.given; - private final String userToken = "Bearer testToken"; +public class RootControllerFunctionalTest { + private static final String USER_TOKEN = "Bearer testToken"; private final String targetInstance = StringUtils.defaultIfBlank( @@ -16,14 +16,13 @@ public class RootControllerFunctionalTest { "http://localhost:4007" ); - private final RequestSpecification request = RestAssured.given().relaxedHTTPSValidation().baseUri(targetInstance); - + private final RequestSpecification request = given().relaxedHTTPSValidation().baseUri(targetInstance); @Test - public void checkDgsRootFor200Response() throws Exception { + public void checkDgsRootFor200Response() { request - .header("Authorization", userToken) + .header("Authorization", USER_TOKEN) .when() .contentType("application/json") .get("/") diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorControllerIntegrationTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorControllerIntegrationTest.java index f95e8f42..a17cd873 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorControllerIntegrationTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorControllerIntegrationTest.java @@ -1,29 +1,25 @@ package uk.gov.hmcts.reform.prl; import io.restassured.response.Response; -import net.serenitybdd.rest.SerenityRest; import org.apache.http.HttpStatus; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Value; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; + @SpringBootTest(classes = DocumentGeneratorControllerIntegrationTest.class) @AutoConfigureMockMvc public class DocumentGeneratorControllerIntegrationTest extends IntegrationTest { private static final String VALID_INPUT_JSON = "documentgenerator/documents/jsoninput/DA-granted-letter.json"; - @Value("${prl.document.generator.uri}") - private String prlDocumentGeneratorURI; - @Test - public void givenTemplateShouldGeneratePdf_VerifyResponse() throws Exception { - + public void givenTemplateShouldGeneratePdfVerifyResponse() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); - Response response = SerenityRest.given() + Response response = given() .contentType("application/json") .header("Authorization", getAuthorizationToken()) .body(requestBody) @@ -31,14 +27,14 @@ public void givenTemplateShouldGeneratePdf_VerifyResponse() throws Exception { .post(prlDocumentGeneratorURI) .andReturn(); - Assert.assertEquals(response.getStatusCode(), HttpStatus.SC_OK); + assertEquals(HttpStatus.SC_OK, response.getStatusCode()); } @Test - public void generatePdfWithWrongURI_ShouldThrowNotFound404() throws Exception { + public void generatePdfWithWrongURIShouldThrowNotFound404() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); - Response response = SerenityRest.given() + Response response = given() .contentType("application/json") .header("Authorization", getAuthorizationToken()) .body(requestBody) @@ -46,6 +42,6 @@ public void generatePdfWithWrongURI_ShouldThrowNotFound404() throws Exception { .post(prlDocumentGeneratorURI + "/test") .andReturn(); - Assert.assertEquals(response.getStatusCode(), HttpStatus.SC_NOT_FOUND); + assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); } } diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorUtil.java b/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorUtil.java index d8cd36be..6c856ac8 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorUtil.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentGeneratorUtil.java @@ -2,7 +2,7 @@ import io.restassured.response.Response; -import static net.serenitybdd.rest.SerenityRest.given; +import static io.restassured.RestAssured.given; public class DocumentGeneratorUtil { static Response generatePDF(final String requestBody, final String generateDocURI, final String userToken) { diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentManagementServiceImplIntegrationTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentManagementServiceImplIntegrationTest.java index ab89fbf2..4a8ef503 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentManagementServiceImplIntegrationTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/prl/DocumentManagementServiceImplIntegrationTest.java @@ -1,7 +1,6 @@ package uk.gov.hmcts.reform.prl; import io.restassured.response.Response; -import net.serenitybdd.rest.SerenityRest; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -9,19 +8,20 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONObject; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.prl.documentgenerator.domain.response.GeneratedDocumentInfo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc public class DocumentManagementServiceImplIntegrationTest extends IntegrationTest { @@ -29,7 +29,6 @@ public class DocumentManagementServiceImplIntegrationTest extends IntegrationTes private static final String INVALID_TEMPLATE_DATA_JSON = "requests/invalid-template-data.json" + "-data.json"; private static final String VALID_INPUT_JSON = "requests/C100-case-data.json"; - private static final String IDAMAPI = "IDAM"; private static final String DOCMOSISAPI = "DOCMOSIS"; private static final String CCDDOCUMENTAPI = "CCDDOCUMENT"; @@ -41,60 +40,57 @@ public class DocumentManagementServiceImplIntegrationTest extends IntegrationTes private String ccdGatewayUrl; @Test - public void givenTemplateAndJsonInput_ReturnStatus200() throws Exception { - + public void givenTemplateAndJsonInputReturnStatus200() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); Response response = callPrlDocumentGenerator(requestBody); - assertEquals(200, response.getStatusCode()); + assertEquals(HttpStatus.SC_OK, response.getStatusCode()); } @Test - public void givenRequestBodyAndInvalidAuthToken_ReturnStatus401() throws Exception { - + public void givenRequestBodyAndInvalidAuthTokenReturnStatus401() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); Response response = callInvalidPrlDocumentGenerator(requestBody); - assertEquals(401, response.getStatusCode()); + assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); } @Test - public void checkStatusOfIdamApiIsUp_thenReturn200Status() throws Exception { - - Response response = SerenityRest.given() + public void checkStatusOfIdamApiIsUpThenReturn200Status() { + Response response = given() .when() .get(constructHealthUrl(IDAMAPI)) .andReturn(); - assertEquals(response.getStatusCode(), HttpStatus.SC_OK); + assertEquals(HttpStatus.SC_OK, response.getStatusCode()); } @Test - public void checkStatusOfDocmosisApiIsUp_thenReturn200Status() throws Exception { + public void checkStatusOfDocmosisApiIsUpThenReturn200Status() { - Response response = SerenityRest.given() + Response response = given() .when() .get(constructHealthUrl(DOCMOSISAPI)) .andReturn(); - assertEquals(response.getStatusCode(), HttpStatus.SC_OK); + assertEquals(HttpStatus.SC_OK, response.getStatusCode()); } @Test - public void checkStatusOfCCDCaseDocumentApiIsUp_thenReturn200Status() throws Exception { + public void checkStatusOfCCDCaseDocumentApiIsUpThenReturn200Status() { - Response response = SerenityRest.given() + Response response = given() .when() .get(constructHealthUrl(CCDDOCUMENTAPI)) .andReturn(); - assertEquals(response.getStatusCode(), HttpStatus.SC_OK); + assertEquals(HttpStatus.SC_OK, response.getStatusCode()); } @Test - public void givenInvalidTemplate_whenRequestMade_thenReturn400Response() throws Exception { + public void givenInvalidTemplateWhenRequestMadeThenReturn400Response() throws Exception { String requestBody = ResourceLoader.loadJson(INVALID_TEMPLATE_DATA_JSON); @@ -107,7 +103,7 @@ public void givenInvalidTemplate_whenRequestMade_thenReturn400Response() throws } @Test - public void givenTemplateAndJson_whenDocumentGenerated_thenCorrectFormat() throws Exception { + public void givenTemplateAndJsonWhenDocumentGeneratedThenCorrectFormat() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); Response response = callPrlDocumentGenerator(requestBody); @@ -116,11 +112,11 @@ public void givenTemplateAndJson_whenDocumentGenerated_thenCorrectFormat() throw String mimeType = generatedDocumentInfo.getMimeType(); String expectedMimeType = "application/pdf"; - assertEquals(mimeType, expectedMimeType); + assertEquals(expectedMimeType, mimeType); } @Test - public void givenValidAccessToken_whenAccessingDocumentPath_thenAccessProvided() throws Exception { + public void givenValidAccessTokenWhenAccessingDocumentPathThenAccessProvided() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); Response response = callPrlDocumentGenerator(requestBody); @@ -137,15 +133,13 @@ public void givenValidAccessToken_whenAccessingDocumentPath_thenAccessProvided() HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.AUTHORIZATION, bearerToken); - HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request ); + HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); - assertEquals( - httpResponse.getStatusLine().getStatusCode(), - HttpStatus.SC_OK); + assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine().getStatusCode()); } @Test - public void givenInvalidAccessToken_whenAccessingDocumentPath_thenNoAccessProvided() throws Exception { + public void givenInvalidAccessTokenWhenAccessingDocumentPathThenNoAccessProvided() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); Response response = callPrlDocumentGenerator(requestBody); @@ -159,7 +153,7 @@ public void givenInvalidAccessToken_whenAccessingDocumentPath_thenNoAccessProvid HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer ***INVALID***"); - HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request ); + HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); JSONObject responseJson = new JSONObject(EntityUtils.toString(httpResponse.getEntity())); String responseMessage = responseJson.get("message").toString(); @@ -170,7 +164,7 @@ public void givenInvalidAccessToken_whenAccessingDocumentPath_thenNoAccessProvid } @Test - public void givenValidTemplateAndJson_whenDocumentGenerated_thenResponseContainsHashToken() throws Exception { + public void givenValidTemplateAndJsonWhenDocumentGeneratedThenResponseContainsHashToken() throws Exception { String requestBody = ResourceLoader.loadJson(VALID_INPUT_JSON); Response response = callPrlDocumentGenerator(requestBody); @@ -181,6 +175,4 @@ public void givenValidTemplateAndJson_whenDocumentGenerated_thenResponseContains assertNotNull(hashToken); } - - } diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/prl/IdamUtils.java b/src/integrationTest/java/uk/gov/hmcts/reform/prl/IdamUtils.java index 8f71711e..1f75fa8e 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/prl/IdamUtils.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/prl/IdamUtils.java @@ -2,7 +2,6 @@ import io.restassured.response.Response; import lombok.extern.slf4j.Slf4j; -import net.serenitybdd.rest.SerenityRest; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import uk.gov.hmcts.reform.prl.model.CreateUserRequest; @@ -10,6 +9,8 @@ import java.util.Base64; +import static io.restassured.RestAssured.given; + @Slf4j public class IdamUtils { @@ -57,7 +58,7 @@ private void createUserInIdam(String username, String password) { .roles(new UserCode[]{UserCode.builder().code("citizen").build()}) .build(); - SerenityRest.given() + given() .header("Content-Type", "application/json") .body(ResourceLoader.objectToJson(userRequest)) .post(idamCreateUrl()); @@ -72,7 +73,7 @@ public void createCaseworkerUserInIdam(String username, String password) { .roles(new UserCode[]{UserCode.builder().code("caseworker-privatelaw-solicitor").build()}) .build(); - SerenityRest.given() + given() .header("Content-Type", "application/json") .body(ResourceLoader.objectToJson(userRequest)) .post(idamCreateUrl()); @@ -81,9 +82,8 @@ public void createCaseworkerUserInIdam(String username, String password) { public String generateUserTokenWithNoRoles(String username, String password) { String userLoginDetails = String.join(":", username, password); final String authHeader = "Basic " + new String(Base64.getEncoder().encode(userLoginDetails.getBytes())); - Response response = null; - response = SerenityRest.given() + Response response = given() .header("Authorization", authHeader) .header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE) .relaxedHTTPSValidation() @@ -96,7 +96,7 @@ public String generateUserTokenWithNoRoles(String username, String password) { + " body: " + response.getBody().prettyPrint()); } - response = SerenityRest.given() + response = given() .header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE) .relaxedHTTPSValidation() .post(idamTokenUrl(response.getBody().path("code"))); @@ -125,12 +125,6 @@ private String idamCreateUrl() { } private String idamCodeUrl() { - - System.out.println(idamUserBaseUrl + idamAuthorizeContextPath - + "?response_type=code" - + "&client_id=" + idamAuthClientID - + "&redirect_uri=" + idamRedirectUri); - return idamUserBaseUrl + idamAuthorizeContextPath + "?response_type=code" + "&client_id=" + idamAuthClientID @@ -138,21 +132,12 @@ private String idamCodeUrl() { } private String idamTokenUrl(String code) { - - System.out.println(idamUserBaseUrl + idamTokenContextPath - + "?code=" + code - + "&client_id=" + idamAuthClientID - + "&client_secret=" + idamSecret - + "&redirect_uri=" + idamRedirectUri - + "&grant_type=authorization_code"); - return idamUserBaseUrl + idamTokenContextPath + "?code=" + code + "&client_id=" + idamAuthClientID + "&client_secret=" + idamSecret + "&redirect_uri=" + idamRedirectUri + "&grant_type=authorization_code"; - } } diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/prl/IntegrationTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/prl/IntegrationTest.java index 78427300..c2b7cb11 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/prl/IntegrationTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/prl/IntegrationTest.java @@ -2,14 +2,12 @@ import io.restassured.response.Response; import lombok.extern.slf4j.Slf4j; -import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule; import org.assertj.core.util.Strings; -import org.junit.Rule; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; import java.io.IOException; @@ -20,7 +18,7 @@ import javax.annotation.PostConstruct; @Slf4j -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {ServiceContextConfiguration.class}) public abstract class IntegrationTest { @@ -45,16 +43,9 @@ public abstract class IntegrationTest { @Autowired private IdamUtils idamTestSupportUtil; - @Rule - public SpringIntegrationMethodRule springMethodIntegration; - private static String userToken = null; private String username; - public IntegrationTest() { - this.springMethodIntegration = new SpringIntegrationMethodRule(); - } - @PostConstruct public void init() { if (!Strings.isNullOrEmpty(httpProxy)) { @@ -75,11 +66,8 @@ public Response callInvalidPrlDocumentGenerator(String requestBody) { } private String getToken() { - String authHeaderToken = null; String userLoginDetails = String.join(":", username, aatPassword); - authHeaderToken = "Bearer " + new String(Base64.getEncoder().encode((userLoginDetails).getBytes())); - - return authHeaderToken; + return "Bearer " + new String(Base64.getEncoder().encode((userLoginDetails).getBytes())); } private synchronized String getUserToken() { @@ -95,8 +83,7 @@ private synchronized String getUserToken() { } public String getAuthorizationToken() { - String authToken = getUserToken(); - return authToken; + return getUserToken(); } public String getStoredUserToken() { @@ -104,9 +91,7 @@ public String getStoredUserToken() { } public String constructHealthUrl(String apiName) { - String url = null; - url = idamTestSupportUtil.generateUrlForValidMicroservice(apiName); - return url; + return idamTestSupportUtil.generateUrlForValidMicroservice(apiName); } private void configProxyHost() { diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/prl/ResourceLoader.java b/src/integrationTest/java/uk/gov/hmcts/reform/prl/ResourceLoader.java index e7276126..574c1809 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/prl/ResourceLoader.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/prl/ResourceLoader.java @@ -3,14 +3,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URL; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class ResourceLoader { public static String loadJson(final String filePath) throws Exception { - return new String(loadResource(filePath), Charset.forName("utf-8")); + return new String(loadResource(filePath), StandardCharsets.UTF_8); } public static byte[] loadResource(final String filePath) throws Exception { diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/DocumentGeneratorApplication.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/DocumentGeneratorApplication.java index 4085ae0c..2185ed1d 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/DocumentGeneratorApplication.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/DocumentGeneratorApplication.java @@ -2,7 +2,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.openfeign.EnableFeignClients; import uk.gov.hmcts.reform.authorisation.ServiceAuthAutoConfiguration; @SpringBootApplication( diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClient.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClient.java index 49ac055a..9c51b20c 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClient.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClient.java @@ -1,17 +1,18 @@ package uk.gov.hmcts.reform.prl.documentgenerator.config.launchdarkly; import com.launchdarkly.sdk.LDContext; -import com.launchdarkly.sdk.LDUser; import com.launchdarkly.sdk.server.interfaces.LDClientInterface; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; +@Slf4j @Service public class LaunchDarklyClient { - public static final LDUser PRL_DGS_USER = new LDUser.Builder("prl-dgs-api") + public static final LDContext PRL_DGS_USER = LDContext.builder("prl-dgs-api") .anonymous(true) .build(); @@ -28,7 +29,7 @@ public LaunchDarklyClient( } public boolean isFeatureEnabled(String feature) { - return internalClient.boolVariation(feature, LDContext.fromUser(LaunchDarklyClient.PRL_DGS_USER), false); + return internalClient.boolVariation(feature, LaunchDarklyClient.PRL_DGS_USER, false); } public boolean isFeatureEnabled(String feature, LDContext user) { @@ -39,8 +40,7 @@ private void close() { try { internalClient.close(); } catch (IOException e) { - // can't do anything clever here because things are being destroyed - e.printStackTrace(System.err); + log.warn("Failed to close LaunchDarkly client", e); } } } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorController.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorController.java index a06d6a18..063c71f1 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorController.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorController.java @@ -5,11 +5,9 @@ import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -32,64 +30,61 @@ public class DocumentGeneratorController { private final DocumentManagementService documentManagementService; @Operation(description = "Generate PDF document based on the supplied template name and placeholder " - + "texts and saves it in the evidence management.", tags = {"Document Generation"}) - @ApiResponses({ - @ApiResponse(responseCode = "200", description = "PDF was generated successfully and stored in the " - + "evidence management. Returns the url to the stored document.", content = - @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))), - @ApiResponse(responseCode = "400", description = "Returned when input parameters are invalid " - + "or template not found", content = - @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))), - @ApiResponse(responseCode = "503", description = "Returned when the PDF Service or Evidence " - + "Management Client Api cannot be reached", content = - @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))), - @ApiResponse(responseCode = "500", description = "Returned when there is an unknown server error", - content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) - }) + + "texts and saves it in the evidence management.", tags = {"Document Generation"}) + @ApiResponse(responseCode = "200", description = "PDF was generated successfully and stored in the " + + "evidence management. Returns the URL to the stored document.", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) + @ApiResponse(responseCode = "400", description = "Returned when input parameters are invalid " + + "or template not found", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) + @ApiResponse(responseCode = "503", description = "Returned when the PDF Service or Evidence " + + "Management Client API cannot be reached", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) + @ApiResponse(responseCode = "500", description = "Returned when there is an unknown server error", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) @PostMapping("/generatePDF") public GeneratedDocumentInfo generateAndUploadPdf( @RequestHeader(value = "Authorization", required = false) - String authorizationToken, + String authorizationToken, @Parameter(name = "GenerateDocumentRequest",description = "JSON object containing " - + "the templateName and the placeholder text map", required = true) + + "the templateName and the placeholder text map", required = true) @RequestBody @Valid - GenerateDocumentRequest templateData) { + GenerateDocumentRequest templateData) { //This service is internal to PRL system. No need to do service authentication here - log.info("Document generation requested with templateName [{}], placeholders map of size[{}]", - templateData.getTemplate(), templateData.getValues().size()); - return documentManagementService.generateAndStoreDocument(templateData.getTemplate(), templateData.getValues(), - authorizationToken); + + log.info("Generating PDF document with templateName [{}] and [{}] placeholders", + templateData.getTemplate(), templateData.getValues().size()); + return documentManagementService.generateAndStoreDocument( + templateData.getTemplate(), templateData.getValues(), authorizationToken + ); } @Operation(description = "Generate draft PDF document based on the supplied template name and placeholder texts " - + "and saves it in the evidence management.", tags = {"Document Generation"}) - @ApiResponses({ - @ApiResponse(responseCode = "200", description = "PDF was generated successfully and stored in the " - + "evidence management. Returns the url to the stored document.",content = - @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))), - @ApiResponse(responseCode = "400", description = "Returned when input parameters are invalid or " - + "template not found", content = - @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))), - @ApiResponse(responseCode = "503", description = "Returned when the PDF Service or Evidence Management " - + "Client Api cannot be reached", content = - @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))), - @ApiResponse(responseCode = "500", description = "Returned when there is an unknown server error", - content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) - }) + + "and saves it in the evidence management.", tags = {"Document Generation"}) + @ApiResponse(responseCode = "200", description = "PDF was generated successfully and stored in the " + + "evidence management. Returns the URL to the stored document.", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) + @ApiResponse(responseCode = "400", description = "Returned when input parameters are invalid or " + + "template not found", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) + @ApiResponse(responseCode = "503", description = "Returned when the PDF Service or Evidence Management " + + "Client API cannot be reached", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) + @ApiResponse(responseCode = "500", description = "Returned when there is an unknown server error", + content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))) @PostMapping("/generateDraftPDF") public GeneratedDocumentInfo generateAndUploadDraftPdf( @RequestHeader(value = "Authorization", required = false) - String authorizationToken, + String authorizationToken, @Parameter(name = "GenerateDocumentRequest",description = "JSON object containing the " - + "templateName and the placeholder text map", required = true) + + "templateName and the placeholder text map", required = true) @RequestBody @Valid - GenerateDocumentRequest templateData) { + GenerateDocumentRequest templateData) { //This service is internal to Divorce system. No need to do service authentication here - log.info("Document generation requested with templateName [{}], placeholders map of size[{}]", - templateData.getTemplate(), templateData.getValues().size() - ); + log.info("Generating draft PDF with templateName [{}] and [{}] placeholders", + templateData.getTemplate(), templateData.getValues().size()); return documentManagementService.generateAndStoreDraftDocument(templateData.getTemplate(), templateData.getValues(), authorizationToken ); @@ -107,8 +102,7 @@ public GeneratedDocumentInfo convertDocumentToPdf( GenerateDocumentRequest templateData) { //This service is internal to Divorce system. No need to do service authentication here log.info("convertDocumentToPdf is getting called"); - return documentManagementService.converToPdf( - templateData.getValues(), authorizationToken, fileName); + return documentManagementService.convertToPdf(templateData.getValues(), authorizationToken, fileName); } } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandler.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandler.java index 0a9358db..4fe33b54 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandler.java @@ -31,13 +31,13 @@ public ResponseEntity handleTemplateLoadingException(ErrorLoadingTemplat public ResponseEntity handleDocumentStorageAndPDFGenerationException(Exception exception) { log.error(exception.getMessage(), exception); - if (exception.getCause() instanceof HttpClientErrorException) { - HttpStatus httpClientErrorException = ((HttpClientErrorException) exception.getCause()).getStatusCode(); + if (exception.getCause() instanceof HttpClientErrorException httpClientErrorException) { + HttpStatus statusCode = httpClientErrorException.getStatusCode(); - if (httpClientErrorException == HttpStatus.BAD_REQUEST) { + if (statusCode == HttpStatus.BAD_REQUEST) { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(exception.getMessage()); } else { - return ResponseEntity.status(httpClientErrorException).body(exception.getMessage()); + return ResponseEntity.status(statusCode).body(exception.getMessage()); } } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/DocumentManagementService.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/DocumentManagementService.java index 745edc15..bc87b984 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/DocumentManagementService.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/DocumentManagementService.java @@ -15,5 +15,5 @@ GeneratedDocumentInfo generateAndStoreDraftDocument(String templateName, Map placeholders); - GeneratedDocumentInfo converToPdf(Map placeholders, String authorizationToken, String filename); + GeneratedDocumentInfo convertToPdf(Map placeholders, String authorizationToken, String filename); } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/PDFGenerationService.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/PDFGenerationService.java index a10d2795..c37c70cd 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/PDFGenerationService.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/PDFGenerationService.java @@ -6,6 +6,6 @@ public interface PDFGenerationService { byte[] generate(String templateName, Map placeholders); - byte[] converToPdf(Map placeholders, String fileName); + byte[] convertToPdf(Map placeholders, String fileName); } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPDFGenerationServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPDFGenerationServiceImpl.java index 7227f2eb..99fcb429 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPDFGenerationServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPDFGenerationServiceImpl.java @@ -5,7 +5,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; @@ -88,7 +87,7 @@ private PdfDocumentRequest request(String templateName, Map plac } @Override - public byte[] converToPdf(Map placeholders, String fileName) { + public byte[] convertToPdf(Map placeholders, String fileName) { try { String filename = FilenameUtils.getBaseName(fileName) + ".pdf"; @@ -107,7 +106,6 @@ public byte[] converToPdf(Map placeholders, String fileName) { } catch (IOException e) { throw new PDFGenerationException("Failed to convertToPdf: " + e.getMessage(), e); } - } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImpl.java b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImpl.java index b984c4c1..6a81dd6c 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImpl.java @@ -17,8 +17,8 @@ import java.text.SimpleDateFormat; import java.time.Clock; -import java.util.Arrays; import java.util.Date; +import java.util.List; import java.util.Locale; import java.util.Map; @@ -32,7 +32,6 @@ public class DocumentManagementServiceImpl implements DocumentManagementService private static final String CURRENT_DATE_KEY = "current_date"; private static final String DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ss.SSS"; - private static final String DRAFT_PREFIX = "Draft"; private static final String IS_DRAFT = "isDraft"; public static final String DYNAMIC_FILE_NAME = "dynamic_fileName"; @@ -53,7 +52,7 @@ public class DocumentManagementServiceImpl implements DocumentManagementService @Override public GeneratedDocumentInfo generateAndStoreDocument(String templateName, Map placeholders, String authorizationToken) { - String fileName = ""; + String fileName; if (placeholders.containsKey(DYNAMIC_FILE_NAME)) { fileName = String.valueOf(placeholders.get(DYNAMIC_FILE_NAME)); } else { @@ -66,7 +65,7 @@ public GeneratedDocumentInfo generateAndStoreDocument(String templateName, Map placeholders, String authorizationToken) { - String fileName = ""; + String fileName; if (placeholders.containsKey(DYNAMIC_FILE_NAME)) { fileName = String.valueOf(placeholders.get(DYNAMIC_FILE_NAME)); } else { @@ -84,7 +83,7 @@ private GeneratedDocumentInfo getGeneratedDocumentInfo(String templateName, Map< String authorizationToken, String fileName) { String caseId = getCaseId(placeholders); if (caseId == null) { - log.warn("caseId is null for template \"" + templateName + "\""); + log.warn("caseId is null for template \"{}\"", templateName); } log.info("Generating document for case Id {}", caseId); @@ -111,7 +110,7 @@ public GeneratedDocumentInfo storeDocument(byte[] document, String authorization serviceAuthToken, "PRLAPPS", "PRIVATELAW", - Arrays.asList(new InMemoryMultipartFile("files", fileName, APPLICATION_PDF_VALUE, document + List.of(new InMemoryMultipartFile("files", fileName, APPLICATION_PDF_VALUE, document )) ); @@ -129,25 +128,31 @@ public GeneratedDocumentInfo storeDocument(byte[] document, String authorization @Override public byte[] generateDocument(String templateName, Map placeholders) { log.debug("Generate document requested with templateName [{}], placeholders of size[{}]", - templateName, placeholders.size() + templateName, + placeholders.size() ); return generatorService.generate(templateName, placeholders); } private String getCaseId(Map placeholders) { + @SuppressWarnings("unchecked") Map caseDetails = (Map) placeholders.getOrDefault("caseDetails", emptyMap()); return (String) caseDetails.get("id"); } @Override - public GeneratedDocumentInfo converToPdf(Map placeholders, String authorizationToken, String fileName) { + public GeneratedDocumentInfo convertToPdf( + Map placeholders, + String authorizationToken, + String fileName) { log.debug( - "Generate document requested with templateName [{}], placeholders of size[{}]", + "Generate pdf document requested with templateName [{}], placeholders of size[{}]", + fileName, placeholders.size() ); - byte[] generatedDocument = generatorService.converToPdf(placeholders, fileName); + byte[] generatedDocument = generatorService.convertToPdf(placeholders, fileName); return storeDocument(generatedDocument, authorizationToken, FilenameUtils.getBaseName(fileName) + ".pdf"); } } diff --git a/src/smokeTest/java/uk/gov/hmcts/reform/prl/DgsApiSmokeTests.java b/src/smokeTest/java/uk/gov/hmcts/reform/prl/DgsApiSmokeTests.java index c2b5d24b..315d5d13 100644 --- a/src/smokeTest/java/uk/gov/hmcts/reform/prl/DgsApiSmokeTests.java +++ b/src/smokeTest/java/uk/gov/hmcts/reform/prl/DgsApiSmokeTests.java @@ -1,20 +1,17 @@ package uk.gov.hmcts.reform.prl; import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; import com.github.tomakehurst.wiremock.junit5.WireMockExtension; -import org.junit.ClassRule; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.PropertySource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import uk.gov.hmcts.reform.ccd.document.am.model.Document; @@ -30,7 +27,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -41,9 +38,11 @@ import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_DEFAULT_NAME_FOR_PDF_FILE; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_HASH_TOKEN; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = DocumentGeneratorApplication.class) +@ExtendWith(SpringExtension.class) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = DocumentGeneratorApplication.class +) @AutoConfigureMockMvc @PropertySource(value = "classpath:application.yml") public class DgsApiSmokeTests { @@ -73,7 +72,7 @@ public class DgsApiSmokeTests { wireMockConfig().port(4502)).build(); @Test - public void givenTemplateNameIsNull_whenGenerateAndStoreDocument_thenReturnHttp400() throws Exception { + public void givenTemplateNameIsNullWhenGenerateAndStoreDocumentThenReturnHttp400() throws Exception { final String template = null; final Map values = Collections.emptyMap(); @@ -87,7 +86,7 @@ public void givenTemplateNameIsNull_whenGenerateAndStoreDocument_thenReturnHttp4 } @Test - public void givenTemplateNameIsBlank_whenGenerateAndStoreDocument_thenReturnHttp400() throws Exception { + public void givenTemplateNameIsBlankWhenGenerateAndStoreDocumentThenReturnHttp400() throws Exception { final String template = " "; final Map values = Collections.emptyMap(); @@ -101,7 +100,7 @@ public void givenTemplateNameIsBlank_whenGenerateAndStoreDocument_thenReturnHttp } @Test - public void givenTemplateNotFound_whenGenerateAndStoreDocument_thenReturnHttp400() throws Exception { + public void givenTemplateNotFoundWhenGenerateAndStoreDocumentThenReturnHttp400() throws Exception { final String template = "nonExistingTemplate"; final Map values = Collections.emptyMap(); @@ -115,11 +114,10 @@ public void givenTemplateNotFound_whenGenerateAndStoreDocument_thenReturnHttp400 } @Test - public void givenCouldNotConnectToAuthService_whenGenerateAndStoreDocument_thenReturnHttp503() throws Exception { - Map caseData = new HashMap<>(); + public void givenCouldNotConnectToAuthServiceWhenGenerateAndStoreDocumentThenReturnHttp503() throws Exception { Map requestData = Collections.singletonMap( - CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData) + CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>()) ); final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(TEST_EXAMPLE, requestData); @@ -135,10 +133,10 @@ public void givenCouldNotConnectToAuthService_whenGenerateAndStoreDocument_thenR } @Test - public void givenAuthServiceReturnAuthenticationError_whenGenerateAndStoreDocument_thenReturnHttp401() throws Exception { - Map caseData = new HashMap<>(); + public void givenAuthServiceReturnAuthenticationErrorWhenGenerateAndStoreDocumentThenReturnHttp401() + throws Exception { Map requestData = Collections.singletonMap( - CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData) + CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>()) ); final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(TEST_EXAMPLE, requestData); @@ -154,12 +152,13 @@ public void givenAuthServiceReturnAuthenticationError_whenGenerateAndStoreDocume } @Test - public void givenAllGoesWellForTestExample_whenGenerateAndStoreDocument_thenReturn() + public void givenAllGoesWellForTestExampleWhenGenerateAndStoreDocumentThenReturn() throws Exception { assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(TEST_EXAMPLE); } - private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String templateId) throws Exception { + private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String templateId) + throws Exception { //Given final Map caseData = Collections.emptyMap(); final Map values = new HashMap<>(); @@ -175,7 +174,9 @@ private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String //When final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(templateId, values); MvcResult result = webClient.perform(post(API_URL) - .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) + .content(ObjectMapperTestUtil.convertObjectToJsonString( + generateDocumentRequest) + ) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) @@ -183,7 +184,10 @@ private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String //Then final GeneratedDocumentInfo generatedDocumentInfo = getGeneratedDocumentInfo(); - assertEquals(ObjectMapperTestUtil.convertObjectToJsonString(generatedDocumentInfo), result.getResponse().getContentAsString()); + assertEquals( + ObjectMapperTestUtil.convertObjectToJsonString(generatedDocumentInfo), + result.getResponse().getContentAsString() + ); } private GeneratedDocumentInfo getGeneratedDocumentInfo() { @@ -192,19 +196,24 @@ private GeneratedDocumentInfo getGeneratedDocumentInfo() { .hashToken(TEST_HASH_TOKEN) .mimeType(MIME_TYPE) .binaryUrl(BINARY_URL) - .docName("TestTemplate.pdf") //added for filename + .docName("TestTemplate.pdf") .build(); return generatedDocumentInfo; } private void mockDocmosisPdfService(HttpStatus expectedResponse, byte[] body) { - docmosisClientServiceServer.stubFor(WireMock.post(DOCMOSIS_API_URL) - .willReturn(aResponse() - .withStatus(expectedResponse.value()) - .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) - .withBody(ObjectMapperTestUtil.convertObjectToJsonString(body)) - )); + docmosisClientServiceServer.stubFor( + WireMock.post(DOCMOSIS_API_URL) + .willReturn( + aResponse() + .withStatus(expectedResponse.value()) + .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) + .withBody( + ObjectMapperTestUtil.convertObjectToJsonString(body) + ) + ) + ); } private void mockServiceAuthServer(HttpStatus expectedResponse, String body) { @@ -221,7 +230,11 @@ private void mockCaseDocsClientApi(HttpStatus expectedResponse, UploadResponse u .willReturn(aResponse() .withStatus(expectedResponse.value()) .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) - .withBody(ObjectMapperTestUtil.convertObjectToJsonString(uploadResponse)) + .withBody( + ObjectMapperTestUtil.convertObjectToJsonString( + uploadResponse + ) + ) )); } @@ -229,7 +242,7 @@ public static Document mockCaseDocsDocuments() { Document.Link link = new Document.Link(); Document.Link linkBinary = new Document.Link(); link.href = FILE_URL; - linkBinary.href = BINARY_URL ; + linkBinary.href = BINARY_URL; Document.Links links = new Document.Links(); links.self = link; diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/TemplatesConfigurationTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/TemplatesConfigurationTest.java index 7d007171..95a11e7b 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/TemplatesConfigurationTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/TemplatesConfigurationTest.java @@ -4,37 +4,38 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeAll; +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.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import java.util.Arrays; import java.util.Set; import static java.lang.String.format; -import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static uk.gov.hmcts.reform.prl.documentgenerator.domain.TemplateConstants.DOCMOSIS_TYPE; import static uk.gov.hmcts.reform.prl.documentgenerator.domain.TemplateConstants.TEST_TEMPLATE; import static uk.gov.hmcts.reform.prl.documentgenerator.domain.TemplateConstants.TEST_TEMPLATE_NAME_FOR_PDF; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest @Slf4j -public class TemplatesConfigurationTest { +class TemplatesConfigurationTest { @Autowired private TemplatesConfiguration classUnderTest; private static Set> expectedTemplateConfigs; - @BeforeClass - public static void setUp() { + @SuppressWarnings("unchecked") + @BeforeAll + static void setUp() { expectedTemplateConfigs = Sets.newHashSet( new ImmutableTriple<>(TEST_TEMPLATE, TEST_TEMPLATE_NAME_FOR_PDF, DOCMOSIS_TYPE) @@ -42,7 +43,7 @@ public static void setUp() { } @Test - public void shouldRetrieveFileName_AndPdfGeneratorName_ByTemplateName() { + void shouldRetrieveFileName_AndPdfGeneratorName_ByTemplateName() { expectedTemplateConfigs.forEach( expectedTemplateConfig -> { String templateName = expectedTemplateConfig.getLeft(); @@ -61,28 +62,30 @@ public void shouldRetrieveFileName_AndPdfGeneratorName_ByTemplateName() { } @Test - public void shouldThrowExceptionWhenUnknownTemplateIsRequested() { + void shouldThrowExceptionWhenUnknownTemplateIsRequested() { String templateName = "unknown-template"; - IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class, () -> { - classUnderTest.getFileNameByTemplateName(templateName); - }); + IllegalArgumentException illegalArgumentException = assertThrows( + IllegalArgumentException.class, + () -> classUnderTest.getFileNameByTemplateName(templateName) + ); + assertThat(illegalArgumentException.getMessage(), containsString("Unknown template: " + templateName)); } @Test - public void shouldReturnDefaultGeneratorForNonExistentTemplate() { + void shouldReturnDefaultGeneratorForNonExistentTemplate() { assertThat(classUnderTest.getGeneratorServiceNameByTemplateName("non-existent-template"), is(DOCMOSIS_TYPE)); } - @Test(expected = Exception.class) - public void shouldThrowAnExceptionWhenTemplateNameIsDuplicated() { + @Test + void shouldThrowAnExceptionWhenTemplateNameIsDuplicated() { TemplatesConfiguration templatesConfiguration = new TemplatesConfiguration(); - templatesConfiguration.setConfigurationList(asList( + templatesConfiguration.setConfigurationList(Arrays.asList( new TemplateConfiguration("thisName", null, null), new TemplateConfiguration("thisName", null, null) )); - templatesConfiguration.init(); + assertThrows(Exception.class, templatesConfiguration::init); } } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LDClientFactoryTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LDClientFactoryTest.java index 5ecac58b..ed54eed0 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LDClientFactoryTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LDClientFactoryTest.java @@ -1,22 +1,21 @@ package uk.gov.hmcts.reform.prl.documentgenerator.config.launchdarkly; import com.launchdarkly.sdk.server.interfaces.LDClientInterface; -import org.junit.Before; -import org.junit.Test; -import uk.gov.hmcts.reform.prl.documentgenerator.config.launchdarkly.LDClientFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; -public class LDClientFactoryTest { +class LDClientFactoryTest { private LDClientFactory factory; - @Before - public void setUp() { + @BeforeEach + void setUp() { factory = new LDClientFactory(); } @Test - public void testCreate() { + void testCreate() { LDClientInterface client = factory.create("test key", true); assertNotNull(client); } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClientTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClientTest.java index e787b104..33d9a96d 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClientTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/config/launchdarkly/LaunchDarklyClientTest.java @@ -1,15 +1,12 @@ package uk.gov.hmcts.reform.prl.documentgenerator.config.launchdarkly; import com.launchdarkly.sdk.LDContext; -import com.launchdarkly.sdk.LDUser; import com.launchdarkly.sdk.server.interfaces.LDClientInterface; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import uk.gov.hmcts.reform.prl.documentgenerator.config.launchdarkly.LDClientFactory; -import uk.gov.hmcts.reform.prl.documentgenerator.config.launchdarkly.LaunchDarklyClient; +import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -18,8 +15,8 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class LaunchDarklyClientTest { +@ExtendWith(MockitoExtension.class) +class LaunchDarklyClientTest { private static final String SDK_KEY = "fake key"; private static final String FAKE_FEATURE = "fake feature"; @@ -34,20 +31,20 @@ public class LaunchDarklyClientTest { private LaunchDarklyClient launchDarklyClient; - @Before - public void setUp() { + @BeforeEach + void setUp() { when(ldClientFactory.create(eq(SDK_KEY), anyBoolean())).thenReturn(ldClient); launchDarklyClient = new LaunchDarklyClient(ldClientFactory, SDK_KEY, true); } @Test - public void testFeatureEnabled() { + void testFeatureEnabled() { when(ldClient.boolVariation(eq(FAKE_FEATURE), any(LDContext.class), anyBoolean())).thenReturn(true); assertTrue(launchDarklyClient.isFeatureEnabled(FAKE_FEATURE, ldUser)); } @Test - public void testFeatureDisabled() { + void testFeatureDisabled() { when(ldClient.boolVariation(eq(FAKE_FEATURE), any(LDContext.class), anyBoolean())).thenReturn(false); assertFalse(launchDarklyClient.isFeatureEnabled(FAKE_FEATURE, ldUser)); } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorControllerUTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorControllerUTest.java index 99716ed7..ac566ba2 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorControllerUTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/DocumentGeneratorControllerUTest.java @@ -1,10 +1,10 @@ package uk.gov.hmcts.reform.prl.documentgenerator.controller; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.prl.documentgenerator.domain.request.GenerateDocumentRequest; import uk.gov.hmcts.reform.prl.documentgenerator.domain.response.GeneratedDocumentInfo; import uk.gov.hmcts.reform.prl.documentgenerator.service.DocumentManagementService; @@ -13,14 +13,13 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class DocumentGeneratorControllerUTest { - +@ExtendWith(MockitoExtension.class) +class DocumentGeneratorControllerUTest { @Mock private DocumentManagementService documentManagementService; @@ -28,7 +27,7 @@ public class DocumentGeneratorControllerUTest { private DocumentGeneratorController classUnderTest; @Test - public void whenGeneratePDF_thenReturnGeneratedPDFDocumentInfo() { + void whenGeneratePDFThenReturnGeneratedPDFDocumentInfo() { final String templateName = "templateName"; final Map placeholder = Collections.emptyMap(); @@ -47,7 +46,7 @@ public void whenGeneratePDF_thenReturnGeneratedPDFDocumentInfo() { } @Test - public void whenGeneratePDF_thenReturnGeneratedDraftPDFDocumentInfo() { + void whenGeneratePDFThenReturnGeneratedDraftPDFDocumentInfo() { final String templateName = "templateName"; final Map placeholder = Collections.emptyMap(); @@ -66,13 +65,13 @@ public void whenGeneratePDF_thenReturnGeneratedDraftPDFDocumentInfo() { } @Test - public void whenConvertPDF_thenReturnConvertedPDFDocumentInfo() { + void whenConvertPDFThenReturnConvertedPDFDocumentInfo() { final String templateName = "templateName"; Map placeholder = new HashMap<>(); final GeneratedDocumentInfo expected = GeneratedDocumentInfo.builder().build(); - when(documentManagementService.converToPdf(placeholder, "authToken","fileName")) + when(documentManagementService.convertToPdf(placeholder, "authToken","fileName")) .thenReturn(expected); GeneratedDocumentInfo actual = classUnderTest @@ -81,7 +80,7 @@ public void whenConvertPDF_thenReturnConvertedPDFDocumentInfo() { assertEquals(expected, actual); verify(documentManagementService, times(1)) - .converToPdf(placeholder, "authToken","fileName"); + .convertToPdf(placeholder, "authToken","fileName"); } } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/RootControllerTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/RootControllerTest.java index c8e35d61..7db01fb8 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/RootControllerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/RootControllerTest.java @@ -1,13 +1,12 @@ package uk.gov.hmcts.reform.prl.documentgenerator.controller; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; @@ -17,24 +16,24 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc -public class RootControllerTest { +class RootControllerTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; - @Before - public void setup() { + @BeforeEach + void setup() { DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac); this.mockMvc = builder.build(); } @Test - public void getShouldReturn200() throws Exception { + void getShouldReturn200() throws Exception { ResultMatcher ok = MockMvcResultMatchers.status() .isOk(); diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandlerUTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandlerUTest.java index 8cff87c5..6e9b7df7 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandlerUTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/controller/helper/GlobalExceptionHandlerUTest.java @@ -1,23 +1,20 @@ package uk.gov.hmcts.reform.prl.documentgenerator.controller.helper; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import uk.gov.hmcts.reform.prl.documentgenerator.exception.ErrorLoadingTemplateException; import uk.gov.hmcts.reform.prl.documentgenerator.exception.PDFGenerationException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(BlockJUnit4ClassRunner.class) -public class GlobalExceptionHandlerUTest { +class GlobalExceptionHandlerUTest { private final GlobalExceptionHandler classUnderTest = new GlobalExceptionHandler(); @Test - public void whenHandleBadRequestException_thenReturnBadRequest() { + void whenHandleBadRequestExceptionThenReturnBadRequest() { final Exception exception = new Exception(); ResponseEntity response = classUnderTest.handleBadRequestException(exception); @@ -26,7 +23,7 @@ public void whenHandleBadRequestException_thenReturnBadRequest() { } @Test - public void whenHandleTemplateLoadingException_thenReturnBadRequest() { + void whenHandleTemplateLoadingExceptionThenReturnBadRequest() { final String message = "some message"; final Exception exception = new Exception(); final ErrorLoadingTemplateException errorLoadingTemplateException = @@ -39,7 +36,7 @@ public void whenHandleTemplateLoadingException_thenReturnBadRequest() { } @Test - public void givenHttpClientErrorExceptionWrappedIn_whenHandleDocumentStorageAndPDFGenerationException_thenReturnStatusCodeOfHttpClientErrorException() { + void whenHandleDocStorageAndPdfGenExceptionThenReturnHttpClientErrorStatus() { final HttpStatus httpStatus = HttpStatus.MOVED_PERMANENTLY; final HttpClientErrorException httpClientErrorException = new HttpClientErrorException(httpStatus); @@ -56,7 +53,7 @@ public void givenHttpClientErrorExceptionWrappedIn_whenHandleDocumentStorageAndP } @Test - public void givenHttpClientErrorResponseCode200_whenHandleDocumentStorageAndPDFGenerationException_thenReturnStatus503() { + void givenHttpClientError200WhenHandleDocStorageAndPdfGenExceptionThenReturn503() { final HttpStatus httpStatus = HttpStatus.BAD_REQUEST; final HttpClientErrorException httpClientErrorException = new HttpClientErrorException(httpStatus); @@ -73,7 +70,7 @@ public void givenHttpClientErrorResponseCode200_whenHandleDocumentStorageAndPDFG } @Test - public void givenWrappedInExceptionIsNull_whenHandleDocumentStorageAndPDFGenerationException_thenReturnInternalServerError() { + void givenNullWrappedInExceptionWhenHandleDocStorageAndPdfGenThenReturn500() { final String message = "some message"; PDFGenerationException pdfGenerationException = new PDFGenerationException(message, null); @@ -86,7 +83,7 @@ public void givenWrappedInExceptionIsNull_whenHandleDocumentStorageAndPDFGenerat } @Test - public void givenWrappedInIsNotHttpClientErrorException_whenHandleDocumentStorageAndPDFGenerationException_thenReturnInternalServerError() { + void givenNonHttpClientErrorWrappedInWhenHandleDocStorageAndPdfGenExceptionThenReturn500() { final String message = "some message"; final Exception exception = new Exception(); diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/functionaltest/DocumentGenerateAndStoreE2ETest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/functionaltest/DocumentGenerateAndStoreE2ETest.java index ac94c667..0e6a8976 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/functionaltest/DocumentGenerateAndStoreE2ETest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/functionaltest/DocumentGenerateAndStoreE2ETest.java @@ -1,19 +1,21 @@ package uk.gov.hmcts.reform.prl.documentgenerator.functionaltest; +import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +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.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.contract.wiremock.WireMockSpring; import org.springframework.context.annotation.PropertySource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import uk.gov.hmcts.reform.ccd.document.am.model.Document; @@ -28,7 +30,7 @@ import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -39,193 +41,205 @@ import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_DEFAULT_NAME_FOR_PDF_FILE; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_HASH_TOKEN; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = DocumentGeneratorApplication.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @PropertySource(value = "classpath:application.yml") @AutoConfigureMockMvc - public class DocumentGenerateAndStoreE2ETest { private static final String API_URL = "/version/1/generatePDF"; private static final String CASE_DOCS_API_URL = "/cases/documents"; private static final String DOCMOSIS_API_URL = "/rs/render"; private static final String S2S_API_URL = "/lease"; - private static final String CASE_DETAILS = "caseDetails"; private static final String CASE_DATA = "case_data"; - private static final String TEST_EXAMPLE = "FL-DIV-GOR-ENG-00062.docx"; @Autowired private MockMvc webClient; - @ClassRule - public static WireMockClassRule caseDocsClientApiServiceServer = new WireMockClassRule(5170); + private static WireMockServer caseDocsClientApiServiceServer; + private static WireMockServer docmosisClientServiceServer; + private static WireMockServer serviceAuthServer; + + @BeforeAll + static void setUpClass() { + caseDocsClientApiServiceServer = new WireMockServer(buildWireMockConfig(5170)); + docmosisClientServiceServer = new WireMockServer(buildWireMockConfig(5501)); + serviceAuthServer = new WireMockServer(buildWireMockConfig(4502)); + + caseDocsClientApiServiceServer.start(); + docmosisClientServiceServer.start(); + serviceAuthServer.start(); + } - @ClassRule - public static WireMockClassRule docmosisClientServiceServer = new WireMockClassRule(5501); + @AfterAll + static void tearDownClass() { + caseDocsClientApiServiceServer.stop(); + docmosisClientServiceServer.stop(); + serviceAuthServer.stop(); + } - @ClassRule - public static WireMockClassRule serviceAuthServer = new WireMockClassRule(4502); + private static WireMockConfiguration buildWireMockConfig(int port) { + return WireMockSpring + .options() + .port(port) + .jettyStopTimeout(20L) + .extensions(new ConnectionCloseExtension()); + } @Test - public void givenTemplateNameIsNull_whenGenerateAndStoreDocument_thenReturnHttp400() throws Exception { - final String template = null; + void givenTemplateNameIsNullWhenGenerateAndStoreDocumentThenReturnHttp400() throws Exception { final Map values = Collections.emptyMap(); - - final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(template, values); + final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(null, values); webClient.perform(post(API_URL) - .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test - public void givenTemplateNameIsBlank_whenGenerateAndStoreDocument_thenReturnHttp400() throws Exception { + void givenTemplateNameIsBlankWhenGenerateAndStoreDocumentThenReturnHttp400() throws Exception { final String template = " "; final Map values = Collections.emptyMap(); - final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(template, values); webClient.perform(post(API_URL) - .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test - public void givenTemplateNotFound_whenGenerateAndStoreDocument_thenReturnHttp400() throws Exception { + void givenTemplateNotFoundWhenGenerateAndStoreDocumentThenReturnHttp400() throws Exception { final String template = "nonExistingTemplate"; final Map values = Collections.emptyMap(); - final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(template, values); webClient.perform(post(API_URL) - .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test - public void givenCouldNotConnectToAuthService_whenGenerateAndStoreDocument_thenReturnHttp503() throws Exception { - Map caseData = new HashMap<>(); - + void givenCouldNotConnectToAuthServiceWhenGenerateAndStoreDocumentThenReturnHttp503() throws Exception { Map requestData = Collections.singletonMap( - CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData) - ); - + CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>())); final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(TEST_EXAMPLE, requestData); - mockDocmosisPdfService(HttpStatus.OK, new byte[] {1}); + mockDocmosisPdfService(new byte[] {1}); mockServiceAuthServer(HttpStatus.SERVICE_UNAVAILABLE, ""); webClient.perform(post(API_URL) - .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isServiceUnavailable()); } @Test - public void givenAuthServiceReturnAuthenticationError_whenGenerateAndStoreDocument_thenReturnHttp401() throws Exception { - Map caseData = new HashMap<>(); + void givenAuthServiceReturnAuthenticationErrorWhenGenerateAndStoreDocumentThenReturnHttp401() throws Exception { Map requestData = Collections.singletonMap( - CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData) - ); - + CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>())); final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(TEST_EXAMPLE, requestData); - mockDocmosisPdfService(HttpStatus.OK, new byte[] {1}); + mockDocmosisPdfService(new byte[] {1}); mockServiceAuthServer(HttpStatus.UNAUTHORIZED, ""); webClient.perform(post(API_URL) - .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isUnauthorized()); } @Test - public void givenAllGoesWellForTestExample_whenGenerateAndStoreDocument_thenReturn() - throws Exception { - assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(TEST_EXAMPLE); + void givenAllGoesWellForTestExampleWhenGenerateAndStoreDocumentThenReturn() throws Exception { + assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(); } - private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments(String templateId) throws Exception { - //Given + private void assertReturnWhenAllGoesWellForGeneratingAndStoringDocuments() throws Exception { + // Given final Map caseData = Collections.emptyMap(); final Map values = new HashMap<>(); values.put(CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData)); - final String s2sAuthToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI" - + "3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI"; + final String s2sAuthToken = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiY" + + "WRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI"; final UploadResponse uploadResponse = new UploadResponse(List.of(mockCaseDocsDocuments())); - mockDocmosisPdfService(HttpStatus.OK, new byte[]{1}); - mockCaseDocsClientApi(HttpStatus.OK, uploadResponse); + mockDocmosisPdfService(new byte[]{1}); + mockCaseDocsClientApi(uploadResponse); mockServiceAuthServer(HttpStatus.OK, s2sAuthToken); - //When - final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest(templateId, values); - MvcResult result = webClient.perform(post(API_URL) - .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + // When + final GenerateDocumentRequest generateDocumentRequest = new GenerateDocumentRequest( + DocumentGenerateAndStoreE2ETest.TEST_EXAMPLE, values); + MvcResult result = webClient.perform( + post(API_URL) + .content(ObjectMapperTestUtil.convertObjectToJsonString(generateDocumentRequest)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); - //Then + // Then final GeneratedDocumentInfo generatedDocumentInfo = getGeneratedDocumentInfo(); - assertEquals(ObjectMapperTestUtil.convertObjectToJsonString(generatedDocumentInfo), result.getResponse().getContentAsString()); + assertEquals( + ObjectMapperTestUtil.convertObjectToJsonString(generatedDocumentInfo), + result.getResponse().getContentAsString() + ); } private GeneratedDocumentInfo getGeneratedDocumentInfo() { - GeneratedDocumentInfo generatedDocumentInfo = GeneratedDocumentInfo.builder() + return GeneratedDocumentInfo.builder() .url(FILE_URL) .hashToken(TEST_HASH_TOKEN) .mimeType(MIME_TYPE) .binaryUrl(BINARY_URL) .docName("TestTemplate.pdf") .build(); - - return generatedDocumentInfo; } - private void mockDocmosisPdfService(HttpStatus expectedResponse, byte[] body) { - docmosisClientServiceServer.stubFor(WireMock.post(DOCMOSIS_API_URL) - .willReturn(aResponse() - .withStatus(expectedResponse.value()) - .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) - .withBody(ObjectMapperTestUtil.convertObjectToJsonString(body)) - )); + private void mockDocmosisPdfService(byte[] body) { + docmosisClientServiceServer.stubFor( + WireMock.post(DOCMOSIS_API_URL) + .willReturn(aResponse() + .withStatus(HttpStatus.OK.value()) + .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) + .withBody(ObjectMapperTestUtil.convertObjectToJsonString(body)) + )); } private void mockServiceAuthServer(HttpStatus expectedResponse, String body) { serviceAuthServer.stubFor(WireMock.post(S2S_API_URL) - .willReturn(aResponse() - .withStatus(expectedResponse.value()) - .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) - .withBody(ObjectMapperTestUtil.convertObjectToJsonString(body)) - )); + .willReturn(aResponse() + .withStatus(expectedResponse.value()) + .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) + .withBody(ObjectMapperTestUtil.convertObjectToJsonString(body)) + )); } - private void mockCaseDocsClientApi(HttpStatus expectedResponse, UploadResponse uploadResponse) { - caseDocsClientApiServiceServer.stubFor(WireMock.post(CASE_DOCS_API_URL) - .willReturn(aResponse() - .withStatus(expectedResponse.value()) - .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) - .withBody(ObjectMapperTestUtil.convertObjectToJsonString(uploadResponse)) - )); + private void mockCaseDocsClientApi(UploadResponse uploadResponse) { + caseDocsClientApiServiceServer.stubFor( + WireMock.post(CASE_DOCS_API_URL) + .willReturn(aResponse() + .withStatus(HttpStatus.OK.value()) + .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) + .withBody(ObjectMapperTestUtil.convertObjectToJsonString(uploadResponse)) + )); } public static Document mockCaseDocsDocuments() { Document.Link link = new Document.Link(); Document.Link linkBinary = new Document.Link(); link.href = FILE_URL; - linkBinary.href = BINARY_URL ; + linkBinary.href = BINARY_URL; Document.Links links = new Document.Links(); links.self = link; @@ -238,4 +252,5 @@ public static Document mockCaseDocsDocuments() { .originalDocumentName(TEST_DEFAULT_NAME_FOR_PDF_FILE) .build(); } + } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/HealthCheckITest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/HealthCheckITest.java index 5a2f2fe8..67434f2f 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/HealthCheckITest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/HealthCheckITest.java @@ -1,7 +1,7 @@ package uk.gov.hmcts.reform.prl.documentgenerator.management.monitoring.health; +import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockClassRule; import com.jayway.jsonpath.JsonPath; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; @@ -10,15 +10,14 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.contract.wiremock.WireMockSpring; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; @@ -27,7 +26,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.prl.documentgenerator.DocumentGeneratorApplication; import uk.gov.hmcts.reform.prl.documentgenerator.functionaltest.ConnectionCloseExtension; @@ -39,10 +38,10 @@ import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ContextConfiguration( - classes = {DocumentGeneratorApplication.class, HealthCheckITest.LocalRibbonClientConfiguration.class}) + classes = {DocumentGeneratorApplication.class, HealthCheckITest.LocalRibbonClientConfiguration.class}) @PropertySource(value = "classpath:application.properties") @TestPropertySource(properties = { "management.endpoint.health.cache.time-to-live=0", @@ -50,7 +49,8 @@ "eureka.client.enabled=false", }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -public class HealthCheckITest { +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class HealthCheckITest { private static final String HEALTH_UP_RESPONSE = "{ \"status\": \"UP\"}"; private static final String HEALTH_DOWN_RESPONSE = "{ \"status\": \"DOWN\"}"; @@ -58,14 +58,9 @@ public class HealthCheckITest { @Value("${local.server.port}") private int port; - @ClassRule - public static WireMockClassRule serviceAuthServer = new WireMockClassRule(buildWireMockConfig(4502)); - - @ClassRule - public static WireMockClassRule docmosisService = new WireMockClassRule(buildWireMockConfig(5501)); - - @ClassRule - public static WireMockClassRule caseDocService = new WireMockClassRule(buildWireMockConfig(5170)); + private WireMockServer serviceAuthServer; + private WireMockServer docmosisService; + private WireMockServer caseDocService; private String healthUrl; private final HttpClient httpClient = HttpClients.createMinimal(); @@ -77,14 +72,24 @@ private HttpResponse getHealth() throws Exception { return httpClient.execute(request); } - @Before - public void setUp() { - healthUrl = "http://localhost:" + String.valueOf(port) + "/health"; + @BeforeAll + void setUp() { + serviceAuthServer = new WireMockServer(buildWireMockConfig(4502)); + docmosisService = new WireMockServer(buildWireMockConfig(5501)); + caseDocService = new WireMockServer(buildWireMockConfig(5170)); + + serviceAuthServer.start(); + docmosisService.start(); + caseDocService.start(); + + healthUrl = "http://localhost:" + port + "/health"; } - @After - public void tearDown() { - resetAllMockServices(); + @AfterAll + void tearDown() { + serviceAuthServer.stop(); + docmosisService.stop(); + caseDocService.stop(); } private static WireMockConfiguration buildWireMockConfig(int port) { @@ -96,7 +101,7 @@ private static WireMockConfiguration buildWireMockConfig(int port) { } @Test - public void givenAllDependenciesAreUp_whenCheckHealth_thenReturnStatusUp() throws Exception { + void givenAllDependenciesAreUpWhenCheckHealthThenReturnStatusUp() throws Exception { stubEndpointAndResponse(serviceAuthServer, true); stubEndpointAndResponse(docmosisService, true); stubEndpointAndResponse(caseDocService, true); @@ -106,19 +111,19 @@ public void givenAllDependenciesAreUp_whenCheckHealth_thenReturnStatusUp() throw assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.OK.value())); assertThat(JsonPath.read(body, "$.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.serviceAuthProviderHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.docmosisHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.caseDocumentHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.diskSpace.status").toString(), - equalTo("UP")); + equalTo("UP")); } @Test - public void givenAllDependenciesAreDown_whenCheckHealth_thenReturnStatusDown() throws Exception { + void givenAllDependenciesAreDownWhenCheckHealthThenReturnStatusDown() throws Exception { stubEndpointAndResponse(serviceAuthServer, false); stubEndpointAndResponse(docmosisService, false); stubEndpointAndResponse(caseDocService, false); @@ -128,19 +133,19 @@ public void givenAllDependenciesAreDown_whenCheckHealth_thenReturnStatusDown() t assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SERVICE_UNAVAILABLE.value())); assertThat(JsonPath.read(body, "$.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.serviceAuthProviderHealthCheck.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.docmosisHealthCheck.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.caseDocumentHealthCheck.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.diskSpace.status").toString(), - equalTo("UP")); + equalTo("UP")); } @Test - public void givenDocmosisServiceIsDown_whenCheckHealth_thenReturnStatusDown() throws Exception { + void givenDocmosisServiceIsDownWhenCheckHealthThenReturnStatusDown() throws Exception { stubEndpointAndResponse(serviceAuthServer, true); stubEndpointAndResponse(docmosisService, false); stubEndpointAndResponse(caseDocService, true); @@ -150,19 +155,19 @@ public void givenDocmosisServiceIsDown_whenCheckHealth_thenReturnStatusDown() th assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SERVICE_UNAVAILABLE.value())); assertThat(JsonPath.read(body, "$.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.serviceAuthProviderHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.docmosisHealthCheck.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.caseDocumentHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.diskSpace.status").toString(), - equalTo("UP")); + equalTo("UP")); } @Test - public void givenCaseDocumentsClientIsDown_whenCheckHealth_thenReturnStatusDown() throws Exception { + void givenCaseDocumentsClientIsDownWhenCheckHealthThenReturnStatusDown() throws Exception { stubEndpointAndResponse(serviceAuthServer, true); stubEndpointAndResponse(docmosisService, true); stubEndpointAndResponse(caseDocService, false); @@ -172,19 +177,19 @@ public void givenCaseDocumentsClientIsDown_whenCheckHealth_thenReturnStatusDown( assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SERVICE_UNAVAILABLE.value())); assertThat(JsonPath.read(body, "$.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.serviceAuthProviderHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.docmosisHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.caseDocumentHealthCheck.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.diskSpace.status").toString(), - equalTo("UP")); + equalTo("UP")); } @Test - public void givenAuthServiceIsDown_whenCheckHealth_thenReturnStatusDown() throws Exception { + void givenAuthServiceIsDownWhenCheckHealthThenReturnStatusDown() throws Exception { stubEndpointAndResponse(serviceAuthServer, false); stubEndpointAndResponse(docmosisService, true); stubEndpointAndResponse(caseDocService, true); @@ -194,35 +199,32 @@ public void givenAuthServiceIsDown_whenCheckHealth_thenReturnStatusDown() throws assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SERVICE_UNAVAILABLE.value())); assertThat(JsonPath.read(body, "$.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.serviceAuthProviderHealthCheck.status").toString(), - equalTo("DOWN")); + equalTo("DOWN")); assertThat(JsonPath.read(body, "$.components.docmosisHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.caseDocumentHealthCheck.status").toString(), - equalTo("UP")); + equalTo("UP")); assertThat(JsonPath.read(body, "$.components.diskSpace.status").toString(), - equalTo("UP")); + equalTo("UP")); } - private void stubEndpointAndResponse(WireMockClassRule mockServer, boolean serviceUp) { - mockServer.stubFor(get(urlEqualTo("/health")) - .willReturn(aResponse() - .withStatus(serviceUp ? HttpStatus.OK.value() : HttpStatus.SERVICE_UNAVAILABLE.value()) - .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) - .withBody(serviceUp ? HEALTH_UP_RESPONSE : HEALTH_DOWN_RESPONSE))); - } - - protected final void resetAllMockServices() { - serviceAuthServer.resetAll(); - docmosisService.resetAll(); + private void stubEndpointAndResponse(WireMockServer mockServer, boolean serviceUp) { + mockServer.stubFor( + get(urlEqualTo("/health")) + .willReturn(aResponse() + .withStatus(serviceUp ? HttpStatus.OK.value() : HttpStatus.SERVICE_UNAVAILABLE.value()) + .withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE) + .withBody(serviceUp ? HEALTH_UP_RESPONSE : HEALTH_DOWN_RESPONSE))); } @TestConfiguration - public static class LocalRibbonClientConfiguration { + static class LocalRibbonClientConfiguration { @Bean - public ServerList ribbonServerList(@Value("${auth.provider.service.client.port}") int serverPort) { + ServerList ribbonServerList(@Value("${auth.provider.service.client.port}") int serverPort) { return new StaticServerList<>(new Server("localhost", serverPort)); } } + } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/WebServiceHealthCheckUTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/WebServiceHealthCheckUTest.java index a0a7526e..c7df9bdd 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/WebServiceHealthCheckUTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/management/monitoring/health/WebServiceHealthCheckUTest.java @@ -1,10 +1,8 @@ package uk.gov.hmcts.reform.prl.documentgenerator.management.monitoring.health; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.actuate.health.Health; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; @@ -18,15 +16,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class WebServiceHealthCheckUTest { - private static final String URI = "http://example.com"; +@ExtendWith(MockitoExtension.class) +class WebServiceHealthCheckUTest { + private static final String URI = "https://example.com"; private final RestTemplate restTemplate = mock(RestTemplate.class); private final HttpEntityFactory httpEntityFactory = mock(HttpEntityFactory.class); @@ -34,7 +31,7 @@ public class WebServiceHealthCheckUTest { URI); @Test - public void givenServiceReturnsOk_whenHealth_thenReturnUp() { + void givenServiceReturnsOkWhenHealthThenReturnUp() { final HttpEntity httpEntity = new HttpEntity<>(null); final ResponseEntity responseEntity = new ResponseEntity<>(HttpStatus.OK); @@ -53,12 +50,14 @@ public void givenServiceReturnsOk_whenHealth_thenReturnUp() { } @Test - public void givenServiceReturnsServiceUnavailable_whenHealth_thenReturnDown() { + void givenServiceReturnsServiceUnavailableWhenHealthThenReturnDown() { final HttpEntity httpEntity = new HttpEntity<>(null); when(httpEntityFactory.createRequestEntityForHealthCheck()).thenReturn(httpEntity); - HttpServerErrorException exception = new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE,"unknown error"); + HttpServerErrorException exception = new HttpServerErrorException( + HttpStatus.SERVICE_UNAVAILABLE,"unknown error" + ); doThrow(exception).when(restTemplate) .exchange(URI, HttpMethod.GET, httpEntity, Object.class, new HashMap<>()); @@ -73,7 +72,7 @@ public void givenServiceReturnsServiceUnavailable_whenHealth_thenReturnDown() { } @Test - public void whenResourceAccessExceptionIsThrown_whenHealth_thenReturnDown() { + void whenResourceAccessExceptionIsThrownWhenHealthThenReturnDown() { final HttpEntity httpEntity = new HttpEntity<>(null); when(httpEntityFactory.createRequestEntityForHealthCheck()).thenReturn(httpEntity); @@ -93,7 +92,7 @@ public void whenResourceAccessExceptionIsThrown_whenHealth_thenReturnDown() { } @Test - public void givenExceptionIsThrown_whenHealth_thenReturnUnknown() { + void givenExceptionIsThrownWhenHealthThenReturnUnknown() { final HttpEntity httpEntity = new HttpEntity<>(null); when(httpEntityFactory.createRequestEntityForHealthCheck()).thenReturn(httpEntity); @@ -113,7 +112,7 @@ public void givenExceptionIsThrown_whenHealth_thenReturnUnknown() { } @Test - public void givenUpstreamStatusIsNot200or503_whenHealth_thenReturnUnknownStatus() { + void givenUpstreamStatusIsNot200or503WhenHealthThenReturnUnknownStatus() { final HttpEntity httpEntity = new HttpEntity<>(null); ResponseEntity responseEntity = new ResponseEntity<>(HttpStatus.MOVED_PERMANENTLY); diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/mapper/TemplateDataMapperTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/mapper/TemplateDataMapperTest.java index 5bae62b1..53a1e0c1 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/mapper/TemplateDataMapperTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/mapper/TemplateDataMapperTest.java @@ -1,13 +1,13 @@ package uk.gov.hmcts.reform.prl.documentgenerator.mapper; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.prl.documentgenerator.config.DocmosisBasePdfConfig; import uk.gov.hmcts.reform.prl.documentgenerator.exception.PDFGenerationException; @@ -15,20 +15,16 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.prl.documentgenerator.domain.TemplateConstants.CASE_DATA; import static uk.gov.hmcts.reform.prl.documentgenerator.domain.TemplateConstants.CASE_DETAILS; import static uk.gov.hmcts.reform.prl.documentgenerator.domain.TemplateConstants.TEMP_PARTY_NAMES_KEY; -@RunWith(MockitoJUnitRunner.class) -public class TemplateDataMapperTest { +@ExtendWith(MockitoExtension.class) +class TemplateDataMapperTest { - // Test Values - private static final String TEST_COURT_ADDRESS = "Placeholder Court"; - - // Docmosis Base Config Constants private static final String TEMPLATE_KEY = "templateKey"; private static final String TEMPLATE_VAL = "templateVal"; private static final String FAMILY_IMG_KEY = "familyImgKey"; @@ -48,8 +44,8 @@ public class TemplateDataMapperTest { private Map expectedData; - @Before - public void setup() { + @BeforeEach + void setup() { // Mock docmosisBasePdfConfig mockDocmosisPdfBaseConfig(); @@ -61,11 +57,9 @@ public void setup() { } @Test - public void givenEmptyRequest_whenTemplateDataMapperIsCalled_returnBaseData() { - Map caseData = new HashMap<>(); - + void givenEmptyRequestWhenTemplateDataMapperIsCalled_returnBaseData() { Map requestData = Collections.singletonMap( - CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData) + CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>()) ); Map actual = templateDataMapper.map(requestData); @@ -74,7 +68,7 @@ public void givenEmptyRequest_whenTemplateDataMapperIsCalled_returnBaseData() { } @Test - public void putAllDataInmMap() { + void putAllDataInmMap() { Map caseData = new HashMap<>(); Map actual = templateDataMapper.map(caseData); @@ -83,11 +77,10 @@ public void putAllDataInmMap() { } @Test - public void putAllPartyNamesInMap() { - Map caseData = new HashMap<>(); + void putAllPartyNamesInMap() { Map partyNamesMap = new HashMap<>(); Map requestData = new HashMap<>(); - requestData.put(CASE_DETAILS, Collections.singletonMap(CASE_DATA, caseData)); + requestData.put(CASE_DETAILS, Collections.singletonMap(CASE_DATA, new HashMap<>())); requestData.put(TEMP_PARTY_NAMES_KEY, partyNamesMap); Map actual = templateDataMapper.map(requestData); @@ -96,29 +89,29 @@ public void putAllPartyNamesInMap() { } @Test - public void formatDateFromCCD_exception() { + void formatDateFromCCD_exception() { String ccdDate = "15-03-2022"; - assertThrows(PDFGenerationException.class, () -> { - templateDataMapper.formatDateFromCCD(ccdDate); - }); + assertThrows(PDFGenerationException.class, + () -> templateDataMapper.formatDateFromCCD(ccdDate) + ); } @Test - public void formatDateFromCCD_success() { + void formatDateFromCCD_success() { String ccdDate = "2022-12-03"; assertEquals("03 December 2022", templateDataMapper.formatDateFromCCD(ccdDate)); } @Test - public void formatDateTimeFromCCD_exception() { + void formatDateTimeFromCCD_exception() { String ccdDate = "15-03-2022"; - assertThrows(PDFGenerationException.class, () -> { - templateDataMapper.formatDateTimeFromCCD(ccdDate); - }); + assertThrows(PDFGenerationException.class, + () -> templateDataMapper.formatDateTimeFromCCD(ccdDate) + ); } @Test - public void formatDateTimeFromCCD_success() { + void formatDateTimeFromCCD_success() { String ccdDate = "2017-11-22T10:10:15.455"; assertEquals("22 November 2017", templateDataMapper.formatDateTimeFromCCD(ccdDate)); } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPdfGenerationServiceImplUTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPdfGenerationServiceImplUTest.java index e4bbebf7..2908fa4b 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPdfGenerationServiceImplUTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocmosisPdfGenerationServiceImplUTest.java @@ -1,21 +1,17 @@ package uk.gov.hmcts.reform.prl.documentgenerator.service.impl; -import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.reflect.FieldUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.http.HttpHeaders; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; @@ -23,15 +19,18 @@ import uk.gov.hmcts.reform.prl.documentgenerator.mapper.TemplateDataMapper; import uk.gov.hmcts.reform.prl.documentgenerator.util.NullOrEmptyValidator; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(MockitoJUnitRunner.class) -public class DocmosisPdfGenerationServiceImplUTest { +@ExtendWith(MockitoExtension.class) +class DocmosisPdfGenerationServiceImplUTest { @Mock private RestTemplate restTemplate; @@ -39,31 +38,23 @@ public class DocmosisPdfGenerationServiceImplUTest { @Mock private TemplateDataMapper templateDataMapper; - @Mock - ObjectMapper objectMapper; - - @InjectMocks @Spy private DocmosisPDFGenerationServiceImpl classUnderTest; - @Before - public void before() throws IllegalAccessException { + @BeforeEach + void before() throws IllegalAccessException { FieldUtils.writeField(classUnderTest, "docmosisPdfServiceEndpoint", "test", true); FieldUtils.writeField(classUnderTest, "docmosisPdfConvertEndpoint", "test", true); FieldUtils.writeField(classUnderTest, "docmosisPdfServiceAccessKey", "test", true); - } @Test - public void givenHttpClientErrorExceptionThrown_whenGenerateCalled_thenThrowPdfGenerationException() - throws Exception { + void givenHttpClientErrorExceptionThrownWhenGenerateCalledThenThrowPdfGenerationException() { final String template = "1"; final Map placeholders = Collections.emptyMap(); final HttpClientErrorException httpClientErrorException = Mockito.mock(HttpClientErrorException.class); - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); Mockito.doThrow(httpClientErrorException).when(restTemplate).exchange(Mockito.anyString(), ArgumentMatchers.any(HttpMethod.class), ArgumentMatchers.any(), @@ -78,19 +69,16 @@ public void givenHttpClientErrorExceptionThrown_whenGenerateCalled_thenThrowPdfG NullOrEmptyValidator.requireNonBlank(template); } - @Test - public void givenHttpRequestGoesThrough_whenGenerateFromHtml_thenReturnProperResponse() throws Exception { + void givenHttpRequestGoesThroughWhenGenerateFromHtmlThenReturnProperResponse() { final String template = "1"; final Map placeholders = Collections.emptyMap(); byte[] test = "Any String you want".getBytes(); - ResponseEntity myEntity = new ResponseEntity(test,HttpStatus.ACCEPTED); + ResponseEntity myEntity = new ResponseEntity<>(test, HttpStatus.ACCEPTED); - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); Mockito.when(restTemplate.exchange(ArgumentMatchers.any(String.class), ArgumentMatchers.any(HttpMethod.class), ArgumentMatchers.any(), @@ -98,25 +86,30 @@ public void givenHttpRequestGoesThrough_whenGenerateFromHtml_thenReturnProperRes byte[] expected = classUnderTest.generate(template, placeholders); - Assert.assertNotNull(expected); + assertNotNull(expected); } @Test - public void givenFileNAme_whenConvertPDf_thenReturnProperResponse() throws Exception { + void givenFileNameWhenConvertPdfThenReturnProperResponse() throws Exception { final Map placeholders = new HashMap<>(); byte[] test = "Any String you want".getBytes(); - placeholders.put("fileName",test); + placeholders.put("fileName", test); - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); - Mockito.when(restTemplate.postForObject(ArgumentMatchers.any(String.class), - ArgumentMatchers.any(), - ArgumentMatchers.>any())).thenReturn(test); + Mockito.when(restTemplate.postForObject( + ArgumentMatchers.any(String.class), + ArgumentMatchers.any(), + ArgumentMatchers.>any())) + .thenReturn(test); - byte[] expected = classUnderTest.converToPdf(placeholders,"testFile"); + String outputFile = "testFile.pdf"; - Assert.assertNotNull(expected); + try { + byte[] expected = classUnderTest.convertToPdf(placeholders, outputFile); + assertNotNull(expected); + } finally { + Files.deleteIfExists(Path.of(outputFile)); + } } } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplTest.java index 3b24f7bf..321cdf58 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplTest.java @@ -1,18 +1,18 @@ package uk.gov.hmcts.reform.prl.documentgenerator.service.impl; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; import uk.gov.hmcts.reform.ccd.document.am.feign.CaseDocumentClient; import uk.gov.hmcts.reform.ccd.document.am.model.UploadResponse; import uk.gov.hmcts.reform.prl.documentgenerator.config.TemplatesConfiguration; +import uk.gov.hmcts.reform.prl.documentgenerator.functionaltest.DocumentGenerateAndStoreE2ETest; import uk.gov.hmcts.reform.prl.documentgenerator.service.PDFGenerationService; import java.util.HashMap; @@ -21,19 +21,18 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.verify; -import static uk.gov.hmcts.reform.prl.documentgenerator.functionaltest.DocumentGenerateAndStoreE2ETest.mockCaseDocsDocuments; -@RunWith(MockitoJUnitRunner.class) -public class DocumentManagementServiceImplTest { +@ExtendWith(MockitoExtension.class) +class DocumentManagementServiceImplTest { private static final String IS_DRAFT = "isDraft"; private static final String MINI_PETITION_NAME_FOR_WELSH_PDF_FILE = "DivorcePetitionWelsh.pdf"; private static final String DRAFT_MINI_PETITION_NAME_FOR_PDF_FILE = "DraftDivorcePetition.pdf"; private static final String D8_PETITION_WELSH_TEMPLATE = "FL-DIV-GNO-WEL-00256.docx"; - private static final String DRAFT_MINI_PETITION_TEMPLATE_ID = "divorcedraftminipetition"; private static final String FINAL_MINI_PETITION_TEMPLATE_ID = "divorcedraftminipetition"; @@ -56,22 +55,24 @@ public class DocumentManagementServiceImplTest { ArgumentCaptor> placeHolderCaptor; static final Map placeholderMap = new HashMap<>(); - static final String authToken = "userAuthToken"; - static final String s2sToken = "s2sAuthToken"; + static final String AUTH_TOKEN = "userAuthToken"; + static final String S2S_TOKEN = "s2sAuthToken"; static final byte[] data = {126}; - static final UploadResponse uploadResponse = new UploadResponse(List.of(mockCaseDocsDocuments())); + static final UploadResponse uploadResponse = new UploadResponse( + List.of(DocumentGenerateAndStoreE2ETest.mockCaseDocsDocuments()) + ); @Test - public void testGenerateAndStoreDraftDocumentMock() { - Mockito.when(authTokenGenerator.generate()).thenReturn(s2sToken); + void testGenerateAndStoreDraftDocumentMock() { + Mockito.when(authTokenGenerator.generate()).thenReturn(S2S_TOKEN); Mockito.when(pdfGenerationService.generate(D8_PETITION_WELSH_TEMPLATE, placeholderMap)).thenReturn(data); Mockito.when(templatesConfiguration.getFileNameByTemplateName(D8_PETITION_WELSH_TEMPLATE)) .thenReturn(MINI_PETITION_NAME_FOR_WELSH_PDF_FILE); - Mockito.when(caseDocumentClient.uploadDocuments(eq(authToken), - eq(s2sToken), eq("PRLAPPS"), eq("PRIVATELAW"), any())) + Mockito.when(caseDocumentClient.uploadDocuments(eq(AUTH_TOKEN), + eq(S2S_TOKEN), eq("PRLAPPS"), eq("PRIVATELAW"), any())) .thenReturn(uploadResponse); - classUnderTest.generateAndStoreDraftDocument(D8_PETITION_WELSH_TEMPLATE, placeholderMap, authToken); + classUnderTest.generateAndStoreDraftDocument(D8_PETITION_WELSH_TEMPLATE, placeholderMap, AUTH_TOKEN); verify(pdfGenerationService).generate(same(D8_PETITION_WELSH_TEMPLATE), placeHolderCaptor.capture()); Map value = placeHolderCaptor.getValue(); @@ -79,15 +80,19 @@ public void testGenerateAndStoreDraftDocumentMock() { } @Test - public void testGenerateAndStoreDraftDocumentMockWithDynamicName() { + void testGenerateAndStoreDraftDocumentMockWithDynamicName() { placeholderMap.put("dynamic_fileName","test-file.pdf"); - Mockito.when(authTokenGenerator.generate()).thenReturn(s2sToken); + Mockito.when(authTokenGenerator.generate()).thenReturn(S2S_TOKEN); Mockito.when(pdfGenerationService.generate(D8_PETITION_WELSH_TEMPLATE, placeholderMap)).thenReturn(data); - Mockito.when(caseDocumentClient.uploadDocuments(eq(authToken), - eq(s2sToken), eq("PRLAPPS"), eq("PRIVATELAW"), any())) + Mockito.when(caseDocumentClient.uploadDocuments( + eq(AUTH_TOKEN), + eq(S2S_TOKEN), + eq("PRLAPPS"), + eq("PRIVATELAW"), + any())) .thenReturn(uploadResponse); - classUnderTest.generateAndStoreDraftDocument(D8_PETITION_WELSH_TEMPLATE, placeholderMap, authToken); + classUnderTest.generateAndStoreDraftDocument(D8_PETITION_WELSH_TEMPLATE, placeholderMap, AUTH_TOKEN); verify(pdfGenerationService).generate(same(D8_PETITION_WELSH_TEMPLATE), placeHolderCaptor.capture()); Map value = placeHolderCaptor.getValue(); @@ -95,14 +100,14 @@ public void testGenerateAndStoreDraftDocumentMockWithDynamicName() { } @Test - public void testGenerateAndStoreDraftDocument_WithDraftPrefixMock() { - Mockito.when(authTokenGenerator.generate()).thenReturn(s2sToken); + void testGenerateAndStoreDraftDocument_WithDraftPrefixMock() { + Mockito.when(authTokenGenerator.generate()).thenReturn(S2S_TOKEN); Mockito.when(pdfGenerationService.generate(DRAFT_MINI_PETITION_TEMPLATE_ID, placeholderMap)).thenReturn(data); - Mockito.when(caseDocumentClient.uploadDocuments(eq(authToken), - eq(s2sToken), eq("PRLAPPS"), eq("PRIVATELAW"), any())) + Mockito.when(caseDocumentClient.uploadDocuments(eq(AUTH_TOKEN), + eq(S2S_TOKEN), eq("PRLAPPS"), eq("PRIVATELAW"), any())) .thenReturn(uploadResponse); - classUnderTest.generateAndStoreDraftDocument(DRAFT_MINI_PETITION_TEMPLATE_ID, placeholderMap, authToken); + classUnderTest.generateAndStoreDraftDocument(DRAFT_MINI_PETITION_TEMPLATE_ID, placeholderMap, AUTH_TOKEN); verify(pdfGenerationService).generate(same(DRAFT_MINI_PETITION_TEMPLATE_ID), placeHolderCaptor.capture()); Map value = placeHolderCaptor.getValue(); @@ -110,55 +115,67 @@ public void testGenerateAndStoreDraftDocument_WithDraftPrefixMock() { } @Test - public void testConvertToPdf() { + void testConvertToPdf() { final Map placeholders = new HashMap<>(); byte[] test = "Any String you want".getBytes(); placeholders.put("fileName",test); - Mockito.when(authTokenGenerator.generate()).thenReturn(s2sToken); - Mockito.when(pdfGenerationService.converToPdf(placeholders,"fileName")).thenReturn(test); - - Mockito.when(caseDocumentClient.uploadDocuments(eq(authToken), - eq(s2sToken), eq("PRLAPPS"), eq("PRIVATELAW"), any())) + Mockito.when(authTokenGenerator.generate()).thenReturn(S2S_TOKEN); + Mockito.when(pdfGenerationService.convertToPdf(placeholders,"fileName")).thenReturn(test); + + Mockito.when(caseDocumentClient.uploadDocuments( + eq(AUTH_TOKEN), + eq(S2S_TOKEN), + eq("PRLAPPS"), + eq("PRIVATELAW"), + any())) .thenReturn(uploadResponse); - classUnderTest.converToPdf(placeholders, authToken,"fileName"); + classUnderTest.convertToPdf(placeholders, AUTH_TOKEN, "fileName"); - verify(pdfGenerationService).converToPdf(placeholders,"fileName"); + verify(pdfGenerationService).convertToPdf(placeholders,"fileName"); } @Test - public void testGenerateAndStoreFinalDocument_WithDynamicFileName() { + void testGenerateAndStoreFinalDocument_WithDynamicFileName() { placeholderMap.put("dynamic_fileName","test-file.pdf"); - Mockito.when(authTokenGenerator.generate()).thenReturn(s2sToken); + Mockito.when(authTokenGenerator.generate()).thenReturn(S2S_TOKEN); Mockito.when(pdfGenerationService.generate(FINAL_MINI_PETITION_TEMPLATE_ID, placeholderMap)).thenReturn(data); - Mockito.when(caseDocumentClient.uploadDocuments(eq(authToken), - eq(s2sToken), eq("PRLAPPS"), eq("PRIVATELAW"), any())) + Mockito.when(caseDocumentClient.uploadDocuments( + eq(AUTH_TOKEN), + eq(S2S_TOKEN), + eq("PRLAPPS"), + eq("PRIVATELAW"), + any())) .thenReturn(uploadResponse); - classUnderTest.generateAndStoreDocument(FINAL_MINI_PETITION_TEMPLATE_ID, placeholderMap, authToken); + classUnderTest.generateAndStoreDocument(FINAL_MINI_PETITION_TEMPLATE_ID, placeholderMap, AUTH_TOKEN); verify(pdfGenerationService).generate(same(FINAL_MINI_PETITION_TEMPLATE_ID), placeHolderCaptor.capture()); Map value = placeHolderCaptor.getValue(); - Assert.assertNotNull(value); + assertNotNull(value); } @Test - public void testGenerateAndStoreFinalDocument_WithOutDynamicFileName() { + void testGenerateAndStoreFinalDocument_WithOutDynamicFileName() { placeholderMap.remove("dynamic_fileName"); - Mockito.when(authTokenGenerator.generate()).thenReturn(s2sToken); + Mockito.when(authTokenGenerator.generate()).thenReturn(S2S_TOKEN); Mockito.when(pdfGenerationService.generate(FINAL_MINI_PETITION_TEMPLATE_ID, placeholderMap)).thenReturn(data); Mockito.when(templatesConfiguration.getFileNameByTemplateName(FINAL_MINI_PETITION_TEMPLATE_ID)) .thenReturn(DRAFT_MINI_PETITION_NAME_FOR_PDF_FILE); - Mockito.when(caseDocumentClient.uploadDocuments(eq(authToken), - eq(s2sToken), eq("PRLAPPS"), eq("PRIVATELAW"), any())) + Mockito.when(caseDocumentClient.uploadDocuments( + eq(AUTH_TOKEN), + eq(S2S_TOKEN), + eq("PRLAPPS"), + eq("PRIVATELAW"), + any())) .thenReturn(uploadResponse); - classUnderTest.generateAndStoreDocument(FINAL_MINI_PETITION_TEMPLATE_ID, placeholderMap, authToken); + classUnderTest.generateAndStoreDocument(FINAL_MINI_PETITION_TEMPLATE_ID, placeholderMap, AUTH_TOKEN); verify(pdfGenerationService).generate(same(FINAL_MINI_PETITION_TEMPLATE_ID), placeHolderCaptor.capture()); Map value = placeHolderCaptor.getValue(); - Assert.assertNotNull(value); + assertNotNull(value); } } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplUTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplUTest.java index 412b80c4..f6d5da79 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplUTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplUTest.java @@ -1,13 +1,12 @@ package uk.gov.hmcts.reform.prl.documentgenerator.service.impl; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; import uk.gov.hmcts.reform.ccd.document.am.feign.CaseDocumentClient; import uk.gov.hmcts.reform.ccd.document.am.model.UploadResponse; @@ -16,29 +15,26 @@ import uk.gov.hmcts.reform.prl.documentgenerator.service.PDFGenerationService; import java.util.HashMap; +import java.util.List; -import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.prl.documentgenerator.functionaltest.DocumentGenerateAndStoreE2ETest.mockCaseDocsDocuments; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.BINARY_URL; -import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.CASE_TYPE; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.FILE_URL; -import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.JURISDICTION; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.MIME_TYPE; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_AUTH_TOKEN; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_GENERATED_DOCUMENT; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_HASH_TOKEN; -import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_S2S_TOKEN; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_TEMPLATE; import static uk.gov.hmcts.reform.prl.documentgenerator.util.TestData.TEST_TEMPLATE_FILE_NAME; -@RunWith(MockitoJUnitRunner.class) -public class DocumentManagementServiceImplUTest { +@ExtendWith(MockitoExtension.class) +class DocumentManagementServiceImplUTest { @Mock private PDFGenerationService pdfGenerationService; @@ -57,14 +53,13 @@ public class DocumentManagementServiceImplUTest { private UploadResponse expectedUploadResponse; - @Before - public void setUp() { - expectedUploadResponse = new UploadResponse(asList(mockCaseDocsDocuments())); + @BeforeEach + void setUp() { + expectedUploadResponse = new UploadResponse(List.of(mockCaseDocsDocuments())); } - @Test - public void givenTemplateNameIsAosInvitation_whenGenerateAndStoreDocument_thenProceedAsExpected() { + void givenTemplateNameIsAosInvitationWhenGenerateAndStoreDocumentThenProceedAsExpected() { when(pdfGenerationService.generate(eq(TEST_TEMPLATE), any())).thenReturn(TEST_GENERATED_DOCUMENT); when(templatesConfiguration.getFileNameByTemplateName(TEST_TEMPLATE)).thenReturn(TEST_TEMPLATE_FILE_NAME); when(caseDocumentClient.uploadDocuments( @@ -78,7 +73,7 @@ public void givenTemplateNameIsAosInvitation_whenGenerateAndStoreDocument_thenPr } @Test - public void givenTemplateNameIsAosInvitation_whenGenerateAndStoreDraftDocument_thenProceedAsExpected() { + void givenTemplateNameIsAosInvitationWhenGenerateAndStoreDraftDocumentThenProceedAsExpected() { when(pdfGenerationService.generate(eq(TEST_TEMPLATE), any())).thenReturn(TEST_GENERATED_DOCUMENT); when(templatesConfiguration.getFileNameByTemplateName(TEST_TEMPLATE)).thenReturn(TEST_TEMPLATE_FILE_NAME); when(caseDocumentClient.uploadDocuments( @@ -92,15 +87,16 @@ public void givenTemplateNameIsAosInvitation_whenGenerateAndStoreDraftDocument_t } @Test - public void givenTemplateNameIsInvalid_whenGenerateAndStoreDocument_thenThrowException() { + void givenTemplateNameIsInvalidWhenGenerateAndStoreDocumentThenThrowException() { String unknownTemplateName = "unknown-template"; HashMap placeholders = new HashMap<>(); when(templatesConfiguration.getFileNameByTemplateName(unknownTemplateName)) .thenThrow(new IllegalArgumentException("Unknown template: " + unknownTemplateName)); - IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class, () -> { - classUnderTest.generateAndStoreDocument(unknownTemplateName, placeholders, "some-auth-token"); - }); + IllegalArgumentException illegalArgumentException = assertThrows( + IllegalArgumentException.class, + () -> classUnderTest.generateAndStoreDocument(unknownTemplateName, placeholders, "some-auth-token") + ); assertThat(illegalArgumentException.getMessage(), equalTo("Unknown template: " + unknownTemplateName)); } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/NullOrEmptyValidatorUTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/NullOrEmptyValidatorUTest.java index 6ecc2c23..2ea16fd5 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/NullOrEmptyValidatorUTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/NullOrEmptyValidatorUTest.java @@ -1,43 +1,48 @@ package uk.gov.hmcts.reform.prl.documentgenerator.util; import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(MockitoJUnitRunner.class) -public class NullOrEmptyValidatorUTest { +@ExtendWith(MockitoExtension.class) +class NullOrEmptyValidatorUTest { private static final String BLANK_STRING = " "; private static final String EMPTY_STRING = ""; private static final String SOME_STRING = "Some String"; @Test - public void testConstructorPrivate() throws Exception { + void testConstructorPrivate() throws Exception { Constructor constructor = NullOrEmptyValidator.class.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); } - @Test(expected = IllegalArgumentException.class) - public void givenArrayIsNull_whenRequireNonEmpty_thenThrowsIllegalArgumentException() { - NullOrEmptyValidator.requireNonEmpty(null); + @Test + void givenArrayIsNullWhenRequireNonEmptyThenThrowsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> + NullOrEmptyValidator.requireNonEmpty(null) + ); } - @Test(expected = IllegalArgumentException.class) - public void givenArrayIsEmpty_whenRequireNonEmpty_thenThrowsIllegalArgumentException() { - NullOrEmptyValidator.requireNonEmpty(ArrayUtils.EMPTY_BYTE_ARRAY); + @Test + void givenArrayIsEmptyWhenRequireNonEmptyThenThrowsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> + NullOrEmptyValidator.requireNonEmpty(ArrayUtils.EMPTY_BYTE_ARRAY) + ); } @Test - public void givenArrayIsNotEmptyOrNull_whenRequireNonEmpty_thenDoesNotThrowException() { + void givenArrayIsNotEmptyOrNullWhenRequireNonEmptyThenDoesNotThrowException() { try { NullOrEmptyValidator.requireNonEmpty(new byte[]{1}); } catch (Exception e) { @@ -45,23 +50,30 @@ public void givenArrayIsNotEmptyOrNull_whenRequireNonEmpty_thenDoesNotThrowExcep } } - @Test(expected = IllegalArgumentException.class) - public void givenTextIsNull_whenRequireNonBlank_thenThrowsIllegalArgumentException() { - NullOrEmptyValidator.requireNonBlank(null); + @Test + void givenTextIsNullWhenRequireNonBlankThenThrowsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> + NullOrEmptyValidator.requireNonBlank(null) + ); } - @Test(expected = IllegalArgumentException.class) - public void givenTextIsEmpty_whenRequireNonBlank_thenThrowsIllegalArgumentException() { - NullOrEmptyValidator.requireNonBlank(EMPTY_STRING); + @Test + void givenTextIsEmptyWhenRequireNonBlankThenThrowsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> + NullOrEmptyValidator.requireNonBlank(EMPTY_STRING) + ); } - @Test(expected = IllegalArgumentException.class) - public void givenTextIsBlank_whenRequireNonBlank_thenThrowsIllegalArgumentException() { - NullOrEmptyValidator.requireNonBlank(BLANK_STRING); + @Test + void givenTextIsBlankWhenRequireNonBlankThenThrowsIllegalArgumentException() { + assertThrows( + IllegalArgumentException.class, () -> + NullOrEmptyValidator.requireNonBlank(BLANK_STRING) + ); } @Test - public void givenTextIsNotBlank_whenRequireNonBlank_thenDoesNotThrowException() { + void givenTextIsNotBlankWhenRequireNonBlankThenDoesNotThrowException() { try { NullOrEmptyValidator.requireNonBlank(SOME_STRING); } catch (Exception e) { diff --git a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/ResourceLoaderUTest.java b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/ResourceLoaderUTest.java index 01de1cd1..abda5c22 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/ResourceLoaderUTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/util/ResourceLoaderUTest.java @@ -1,60 +1,59 @@ package uk.gov.hmcts.reform.prl.documentgenerator.util; -import org.junit.After; -import org.junit.Before; -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.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.prl.documentgenerator.exception.ErrorLoadingTemplateException; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.nio.charset.StandardCharsets; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; -@RunWith(MockitoJUnitRunner.class) -public class ResourceLoaderUTest { +@ExtendWith(MockitoExtension.class) +class ResourceLoaderUTest { private static final String NON_EXISTENT_PATH = "somePath"; private static final String EXISTING_PATH = "ResourceLoadTest.txt"; private static final String DATA_IN_FILE = "Resource Load Test"; - MockedStatic nullOrEmptyValidator ; + MockedStatic nullOrEmptyValidator; - @Before - public void beforeTest() { + @BeforeEach + void beforeTest() { nullOrEmptyValidator = Mockito.mockStatic(NullOrEmptyValidator.class); } - @After - public void afterTest() { + @AfterEach + void afterTest() { nullOrEmptyValidator.close(); } @Test - public void testConstructorPrivate() throws Exception { + void testConstructorPrivate() throws Exception { Constructor constructor = ResourceLoader.class.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); } - @Test(expected = ErrorLoadingTemplateException.class) - public void givenFileIsDoNotExists_whenLoadResource_thenThrowsErrorLoadingTemplateException() { - - nullOrEmptyValidator.verifyNoInteractions(); - ResourceLoader.loadResource(NON_EXISTENT_PATH); - NullOrEmptyValidator.requireNonBlank(NON_EXISTENT_PATH); + @Test + void givenFileDoesNotExistWhenLoadResourceThenThrowsErrorLoadingTemplateException() { + assertThrows(ErrorLoadingTemplateException.class, + () -> ResourceLoader.loadResource(NON_EXISTENT_PATH) + ); } @Test - public void givenFileExists_whenLoadResource_thenLoadFile() { + void givenFileExistsWhenLoadResourceThenLoadFile() { byte[] data = ResourceLoader.loadResource(EXISTING_PATH); nullOrEmptyValidator.verify( () -> NullOrEmptyValidator.requireNonBlank(anyString())