diff --git a/.editorconfig b/.editorconfig index 713e7657..0f3746a8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,11 +7,11 @@ max_line_length = 120 insert_final_newline = true trim_trailing_whitespace = true -[*.kt] -continuation_indent_size = 4 - -[*.{java,gradle}] -continuation_indent_size = 8 +[*.{kt,kts}] +ij_continuation_indent_size = 4 +ij_kotlin_allow_trailing_comma = true +ij_kotlin_allow_trailing_comma_on_call_site = true +ktlint_code_style = intellij_idea [*.{yml,json,conf}] indent_size = 2 diff --git a/.github/workflows/publish.yml b/.github/workflows/cd.yml similarity index 60% rename from .github/workflows/publish.yml rename to .github/workflows/cd.yml index 66e498f7..35050426 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/cd.yml @@ -5,17 +5,20 @@ on: types: [ created ] jobs: - build: + publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - name: Setup JDK - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: temurin - java-version: 8 - cache: 'gradle' + java-version: 17 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 - - name: Publish with Gradle + - name: Publish run: ./gradlew publishPlugins -Pgradle.publish.key=${{ secrets.PUBLISH_KEY }} -Pgradle.publish.secret=${{ secrets.PUBLISH_SECRET }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc1ee43d..9a9e13ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,9 @@ name: CI - -on: [push, pull_request] +on: + push: + branches: + - main + pull_request: jobs: build: @@ -10,27 +13,26 @@ jobs: os: - ubuntu-latest - windows-latest - java: [8, 11, 17] + java: [17, 21] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - name: Setup JDK - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: temurin java-version: ${{ matrix.java }} - cache: 'gradle' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 - name: Build with Gradle - if: matrix.os == 'ubuntu-latest' run: ./gradlew build --stacktrace - - name: Build with Gradle - if: matrix.os == 'windows-latest' - run: .\gradlew.bat build --stacktrace - name: Store reports - uses: actions/upload-artifact@v3 - if: always() + uses: actions/upload-artifact@v4 + if: failure() with: - name: reports-${{ runner.os }}-${{ matrix.java }} - path: build/reports + name: "Gradle Reports ${{ runner.os }} ${{ matrix.java }}" + path: "**/build/reports" diff --git a/README.md b/README.md index b4dca3a6..83f86be9 100644 --- a/README.md +++ b/README.md @@ -362,21 +362,21 @@ Additionally, these options are evaluated: ### Squit Dsl -Here is a complete example of the `Squit` dsl: +Here is a complete example of the `Squit` dsl (`.kts` syntax): -```groovy +```kotlin squit { // The jdbc drivers to use. Must be on the classpath. - jdbcDrivers = ['oracle.jdbc.driver.OracleDriver'] + jdbcDrivers = listOf("oracle.jdbc.driver.OracleDriver") // The path of your test sources. src/squit is the default. - sourceDir "src/squit" + sourceDir = "src/squit" // The path to save reports in. build/squit/reports is the default. - reportDir "build/squit/reports" + reportDir = "build/squit/reports" // The timeout in seconds for requests before squit fails. The default is 10. - timeout = 60 + requestTimeout = 60 // If Squit should only print if a tests fails. silent = false diff --git a/RELEASING.md b/RELEASING.md index 82daf8c3..e93509cc 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,4 +1,4 @@ -**The following steps are required to do a release of Squit:** +Squit will be automatically released by creating a release on GitHub. To manually release Squit: - Log into the Gradle Plugins Portal with the `login` Gradle task: diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 7040b660..00000000 --- a/build.gradle +++ /dev/null @@ -1,220 +0,0 @@ -import org.gradle.api.internal.file.FileOperations -import org.gradle.internal.jacoco.JacocoAgentJar -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile -import org.jlleitschuh.gradle.ktlint.reporter.ReporterType - -buildscript { - apply from: "./gradle/versions.gradle" - - repositories { - gradlePluginPortal() - mavenCentral() - } -} - -plugins { - id "com.gradle.plugin-publish" version "$gradlePublishVersion" - - id 'org.jetbrains.kotlin.jvm' version "$kotlinVersion" - id "org.jetbrains.dokka" version "$dokkaVersion" - - id "io.gitlab.arturbosch.detekt" version "$detektVersion" - id "org.jlleitschuh.gradle.ktlint" version "$ktlintPluginVersion" - id "com.github.ben-manes.versions" version "$gradleVersionsVersion" - - id "java-gradle-plugin" - id "java-library" - id "maven-publish" - id "jacoco" -} - -group = "de.smartsquare" -version = squitVersion - -repositories { - mavenCentral() -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" - implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" - implementation "org.jetbrains.kotlinx:kotlinx-html-jvm:$kotlinHtmlVersion" - - api "org.dom4j:dom4j:$dom4jVersion" - api "com.google.code.gson:gson:$gsonVersion" - api "com.typesafe:config:$typesafeConfigVersion" - - implementation "jaxen:jaxen:$jaxenVersion" - implementation "pull-parser:pull-parser:$pullParserVersion" - implementation "org.apache.santuario:xmlsec:$xmlSecVersion" - implementation "org.xmlunit:xmlunit-core:$xmlUnitVersion" - implementation "net.javacrumbs.json-unit:json-unit:$jsonUnitVersion" - implementation "com.squareup.okhttp3:okhttp:$okhttpVersion" - implementation "se.sawano.java:alphanumeric-comparator:$alphanumericComparatorVersion" - implementation("com.github.wumpz:diffutils:$diffUtilsVersion") { - exclude group: "org.eclipse.jgit", module: "*" - } - - implementation "org.webjars.npm:jquery:$jqueryVersion" - implementation "org.webjars.npm:bootstrap:$bootstrapVersion" - implementation "org.webjars.npm:popper.js:$popperVersion" - implementation "org.webjars:font-awesome:$fontAwesomeVersion" - implementation "org.webjars.npm:marked:$markedVersion" - implementation("org.webjars.npm:diff2html:$diff2htmlVersion") { - exclude group: "org.webjars.npm", module: "*" - } - - testImplementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" - testImplementation "org.junit.jupiter:junit-jupiter-api:$junitVersion" - testImplementation "org.junit.jupiter:junit-jupiter-params:$junitVersion" - testImplementation "org.amshove.kluent:kluent:$kluentVersion" - testImplementation "com.squareup.okhttp3:mockwebserver:$okhttpVersion" - testImplementation "com.h2database:h2:$h2Version" - testImplementation "io.mockk:mockk:$mockkVersion" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitVersion" - testRuntimeOnly "net.bytebuddy:byte-buddy:$byteBuddyVersion" -} - -sourceSets { - test { - resources { - srcDir "$buildDir/testkit" - } - } -} - -jacoco { - toolVersion = jacocoVersion -} - -kotlin { - jvmToolchain { - languageVersion = JavaLanguageVersion.of(project.ext.javaVersion.majorVersion) - } -} - -tasks.withType(KotlinCompile).all { - kotlinOptions { - freeCompilerArgs = ["-Xjsr305=strict"] - allWarningsAsErrors = true - jvmTarget = project.ext.javaVersion - } -} - -// Generates a Gradle properties file with the jacoco javaagent as a jvmarg for Gradle runner tests. -// This allows to generate coverage for code run in the forked JVM. -task generateTestkitFiles { - def jacocoJar = configurations[JacocoPlugin.AGENT_CONFIGURATION_NAME].asPath.toString() - - def jacocoAgentJar = new JacocoAgentJar(project.services.get(FileOperations)).tap { - agentConf = project.files(jacocoJar) - } - - def javaagent = jacocoAgentJar.getJar() - def destfile = new File(buildDir, "jacoco/testkit.exec") - - def jvmArgs = "org.gradle.jvmargs=-javaagent:$javaagent=destfile=$destfile".replace("\\", "\\\\") - def outputDir = file("$buildDir/testkit") - - inputs.files jacocoJar - outputs.dir outputDir - - doLast { - outputDir.mkdirs() - - file("$outputDir/testkit-gradle.properties").text = jvmArgs - } -} - -test { - useJUnitPlatform() - - dependsOn generateTestkitFiles - finalizedBy jacocoTestReport -} - -jacocoTestReport { - getExecutionData().setFrom(fileTree(buildDir).include("/jacoco/*.exec")) -} - -tasks.named("processTestResources") { - dependsOn generateTestkitFiles -} - -ktlint { - disabledRules = ["import-ordering"] - - reporters { - reporter ReporterType.CHECKSTYLE - } -} - -detekt { - config = files("${rootProject.projectDir}/detekt.yml") - input = files("$projectDir/src/main/kotlin") - buildUponDefaultConfig = true -} - -dokkaHtml { - outputDirectory.set(javadoc.destinationDir) - - dokkaSourceSets { - configureEach { - jdkVersion.set(8) - - sourceLink { - localDirectory.set(file("src/main/kotlin")) - remoteUrl.set(new URL("https://github.com/SmartsquareGmbH/squit/blob/master/src/main/kotlin")) - remoteLineSuffix.set("#L") - } - - externalDocumentationLink { - url.set(new URL("https://dom4j.github.io/javadoc/$dom4jVersion/")) - } - - externalDocumentationLink { - url.set(new URL("https://lightbend.github.io/config/latest/api/")) - } - - externalDocumentationLink { - url.set(new URL("https://www.javadoc.io/doc/com.google.code.gson/gson/$gsonVersion/com.google.gson/")) - } - } - } -} - -dependencyUpdates { - rejectVersionIf { - isNonStable(it.candidate.version) && !isNonStable(it.currentVersion) - } -} - -static def isNonStable(String version) { - def stableKeyword = ["RELEASE", "FINAL", "GA"].any { it -> version.toUpperCase().contains(it) } - def regex = /^[0-9,.v-]+(-r)?$/ - - return !stableKeyword && !(version ==~ regex) -} - -tasks.withType(Javadoc).all { - it.dependsOn dokkaHtml -} - -gradlePlugin { - website = "https://github.com/SmartsquareGmbH/squit" - vcsUrl = "https://github.com/SmartsquareGmbH/squit" - - plugins { - squit { - displayName = "Squit" - id = "de.smartsquare.squit" - implementationClass = "de.smartsquare.squit.SquitPlugin" - description = "Gradle plugin for simple testing of JSON/XML/SOAP/etc APIs." - tags.set(["testing", "soap", "xml" ,"automation"]) - } - } -} - -wrapper { - gradleVersion = project.ext.gradleVersion -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..68c136c6 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,160 @@ +import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask + +plugins { + kotlin("jvm") version libs.versions.kotlin + alias(libs.plugins.pluginPublish) + alias(libs.plugins.dokkatooHtml) + alias(libs.plugins.dokkatooJavadoc) + alias(libs.plugins.detekt) + alias(libs.plugins.kotlinter) + alias(libs.plugins.jacocoTestkit) + alias(libs.plugins.gradleVersions) + `java-gradle-plugin` + `maven-publish` + jacoco +} + +group = "de.smartsquare" +version = libs.versions.squit + +repositories { + mavenCentral() +} + +dependencies { + api(libs.dom4j) + api(libs.gson) + api(libs.typesafeConfig) + + implementation(libs.jaxen) + implementation(libs.pullParser) + implementation(libs.xmlSec) + implementation(libs.xmlUnit) + implementation(libs.jsonUnit) + implementation(libs.okhttp) + implementation(libs.kotlinxHtml) + implementation(libs.alphanumericComparator) + implementation(libs.diffUtils) { + exclude(group = "org.eclipse.jgit") + } + + implementation(libs.jquery) + implementation(libs.bootstrap) + implementation(libs.popper) + implementation(libs.fontAwesome) + implementation(libs.marked) + implementation(libs.diff2html) { + exclude(group = "org.webjars.npm") + } + + testImplementation(gradleTestKit()) + testImplementation(kotlin("reflect")) + testImplementation(libs.junit) + testImplementation(libs.junitParams) + testImplementation(libs.h2) + testImplementation(libs.kluent) + testImplementation(libs.mockwebserver) + testImplementation(libs.mockk) + + testRuntimeOnly(libs.junitPlatformLauncher) +} + +java { + withJavadocJar() + withSourcesJar() +} + +kotlin { + jvmToolchain { + languageVersion = JavaLanguageVersion.of(libs.versions.java.get()) + } + + compilerOptions { + allWarningsAsErrors = true + } +} + +tasks.named("test") { + useJUnitPlatform() + + finalizedBy(tasks.jacocoTestReport) +} + +jacoco { + toolVersion = libs.versions.jacoco.get() +} + +detekt { + config.from(file("${rootDir}/detekt.yml")) + + buildUponDefaultConfig = true +} + +tasks.named("javadocJar") { + from(tasks.named("dokkatooGeneratePublicationJavadoc")) +} + +dokkatoo { + val dom4jVersion = resolveVersion("org.dom4j:dom4j") + val typesafeConfigVersion = resolveVersion("com.typesafe:config") + val gsonVersion = resolveVersion("com.google.code.gson:gson") + + dokkatooSourceSets.configureEach { + externalDocumentationLinks.create("gradle") { + url("https://docs.gradle.org/${gradle.gradleVersion}/javadoc/") + packageListUrl("https://docs.gradle.org/${gradle.gradleVersion}/javadoc/element-list") + } + + externalDocumentationLinks.create("dom4j") { + url("https://javadoc.io/doc/org.dom4j/dom4j/$dom4jVersion/") + } + + externalDocumentationLinks.create("config") { + url("https://javadoc.io/doc/com.typesafe/config/$typesafeConfigVersion/") + } + + externalDocumentationLinks.create("gson") { + url("https://javadoc.io/doc/com.google.code.gson/gson/$gsonVersion") + packageListUrl("https://javadoc.io/doc/com.google.code.gson/gson/$gsonVersion/element-list") + } + } +} + +fun resolveVersion(dependency: String): String { + return project.configurations.getByName("runtimeClasspath").resolvedConfiguration.resolvedArtifacts + .find { it.moduleVersion.id.module.toString() == dependency } + ?.moduleVersion?.id?.version + ?: "latest" +} + +gradlePlugin { + website = "https://github.com/SmartsquareGmbH/squit" + vcsUrl = "https://github.com/SmartsquareGmbH/squit" + + plugins { + create("squit") { + displayName = "Squit" + id = "de.smartsquare.squit" + implementationClass = "de.smartsquare.squit.SquitPlugin" + description = "Gradle plugin for simple testing of JSON/XML/SOAP/etc APIs." + tags = listOf("testing", "soap", "xml", "automation") + } + } +} + +tasks.withType { + rejectVersionIf { + isNonStable(candidate.version) + } +} + +fun isNonStable(version: String): Boolean { + val stableKeyword = listOf("RELEASE", "FINAL", "GA").any { version.uppercase().contains(it) } + val regex = "^[0-9,.v-]+(-r)?$".toRegex() + val isStable = stableKeyword || regex.matches(version) + return !isStable +} + +tasks.withType { + gradleVersion = libs.versions.gradle.get() +} diff --git a/gradle.properties b/gradle.properties index 5b28bccb..1803c6b3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,3 @@ org.gradle.parallel=true org.gradle.caching=true kotlin.code.style=official -kapt.use.worker.api=false -kapt.include.compile.classpath=false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..c12af1fd --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,76 @@ +[versions] +java = "17" +gradle = "8.9" +squit = "6.0.0" + +gradlePublish = "1.2.1" +kotlin = "2.0.0" +dokkatoo = "2.3.1" +detekt = "1.23.6" +kotlinter = "4.4.1" +jacoco = "0.8.12" +jacocoTestkit = "1.0.12" +gradleVersions = "0.51.0" + +jaxen = "2.0.0" +dom4j = "2.1.4" +pullParser = "2.1.10" +gson = "2.11.0" +xmlSec = "4.0.2" +xmlUnit = "2.10.0" +jsonUnit = "3.4.0" +typesafeConfig = "1.4.3" +okhttp = "4.12.0" +kotlinxHtml = "0.11.0" +diffUtils = "3.0" +alphanumericComparator = "1.4.1" + +bootstrap = "4.6.0" +jquery = "3.6.0" +popper = "1.16.1" +fontAwesome = "5.15.4" +diff2html = "3.1.7" +marked = "2.0.6" + +junit = "5.10.3" +kluent = "1.73" +h2 = "2.2.224" +mockk = "1.13.11" + +[plugins] +pluginPublish = { id = "com.gradle.plugin-publish", version.ref = "gradlePublish" } +dokkatooHtml = { id = "dev.adamko.dokkatoo-html", version.ref = "dokkatoo" } +dokkatooJavadoc = { id = "dev.adamko.dokkatoo-javadoc", version.ref = "dokkatoo" } +detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } +kotlinter = { id = "org.jmailen.kotlinter", version.ref = "kotlinter" } +jacocoTestkit = { id = "pl.droidsonroids.jacoco.testkit", version.ref = "jacocoTestkit" } +gradleVersions = { id = "com.github.ben-manes.versions", version.ref = "gradleVersions" } + +[libraries] +kotlinxHtml = { module = "org.jetbrains.kotlinx:kotlinx-html-jvm", version.ref = "kotlinxHtml" } +dom4j = { module = "org.dom4j:dom4j", version.ref = "dom4j" } +gson = { module = "com.google.code.gson:gson", version.ref = "gson" } +typesafeConfig = { module = "com.typesafe:config", version.ref = "typesafeConfig" } +jaxen = { module = "jaxen:jaxen", version.ref = "jaxen" } +pullParser = { module = "pull-parser:pull-parser", version.ref = "pullParser" } +xmlSec = { module = "org.apache.santuario:xmlsec", version.ref = "xmlSec" } +xmlUnit = { module = "org.xmlunit:xmlunit-core", version.ref = "xmlUnit" } +jsonUnit = { module = "net.javacrumbs.json-unit:json-unit", version.ref = "jsonUnit" } +okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } +alphanumericComparator = { module = "se.sawano.java:alphanumeric-comparator", version.ref = "alphanumericComparator" } +diffUtils = { module = "com.github.wumpz:diffutils", version.ref = "diffUtils" } + +jquery = { module = "org.webjars.npm:jquery", version.ref = "jquery" } +bootstrap = { module = "org.webjars.npm:bootstrap", version.ref = "bootstrap" } +popper = { module = "org.webjars.npm:popper.js", version.ref = "popper" } +fontAwesome = { module = "org.webjars:font-awesome", version.ref = "fontAwesome" } +marked = { module = "org.webjars.npm:marked", version.ref = "marked" } +diff2html = { module = "org.webjars.npm:diff2html", version.ref = "diff2html" } + +junit = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" } +junitParams = { module = "org.junit.jupiter:junit-jupiter-params", version.ref = "junit" } +junitPlatformLauncher = { module = "org.junit.platform:junit-platform-launcher" } +kluent = { module = "org.amshove.kluent:kluent", version.ref = "kluent" } +mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "okhttp" } +h2 = { module = "com.h2database:h2", version.ref = "h2" } +mockk = { module = "io.mockk:mockk", version.ref = "mockk" } diff --git a/gradle/versions.gradle b/gradle/versions.gradle deleted file mode 100644 index 50bb3aad..00000000 --- a/gradle/versions.gradle +++ /dev/null @@ -1,44 +0,0 @@ -ext { - javaVersion = JavaVersion.VERSION_1_8 - gradleVersion = '7.6.2' - squitVersion = '5.2.0' - - gradlePublishVersion = '1.2.1' - - kotlinVersion = '1.7.21' - dokkaVersion = '1.7.20' - - jacocoVersion = '0.8.8' - gradleVersionsVersion = '0.44.0' - gradleTestIdeaFixVersion = '0.1.0' - - jaxenVersion = '1.2.0' - dom4jVersion = '2.1.3' - pullParserVersion = '2.1.10' - gsonVersion = '2.10' - xmlSecVersion = '3.0.1' - xmlUnitVersion = '2.9.0' - jsonUnitVersion = '2.36.0' - typesafeConfigVersion = '1.4.2' - okhttpVersion = '4.10.0' - kotlinHtmlVersion = '0.8.0' - diffUtilsVersion = '3.0' - alphanumericComparatorVersion = "1.4.1" - - bootstrapVersion = '4.6.0' - jqueryVersion = '3.6.0' - popperVersion = '1.16.1' - fontAwesomeVersion = '5.15.4' - diff2htmlVersion = '3.1.7' - markedVersion = '2.0.6' - - detektVersion = '1.21.0' - ktlintPluginVersion = '11.0.0' - - junitVersion = '5.9.1' - junitPlatformVersion = '1.7.2' - kluentVersion = '1.72' - h2Version = '2.1.214' - mockkVersion = '1.13.2' - byteBuddyVersion = '1.12.19' -} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index afba1092..2c352119 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 4e86b927..09523c0e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 65dcd68d..f5feea6d 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# 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/. @@ -83,10 +85,9 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -# 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"' +# 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 +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,10 +134,13 @@ 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. + 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. @@ -144,7 +148,7 @@ 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=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -152,7 +156,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -197,11 +201,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 93e3f59f..9d21a218 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @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 @rem ########################################################################## @@ -43,11 +45,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +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 @@ -57,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail diff --git a/src/main/kotlin/de/smartsquare/squit/SquitExtension.kt b/src/main/kotlin/de/smartsquare/squit/SquitExtension.kt index e5bf80ff..f2b1304b 100644 --- a/src/main/kotlin/de/smartsquare/squit/SquitExtension.kt +++ b/src/main/kotlin/de/smartsquare/squit/SquitExtension.kt @@ -3,84 +3,65 @@ package de.smartsquare.squit import org.gradle.api.Action import org.gradle.api.Project import org.gradle.api.file.DirectoryProperty -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputDirectory -import org.gradle.api.tasks.Internal +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property import org.gradle.api.tasks.Nested -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity +import javax.inject.Inject -/** - * Class containing the available extensions for the squit dsl. - */ -open class SquitExtension(private val project: Project) { +open class SquitExtension @Inject constructor(private val project: Project) { /** * Extension for xml configuration. */ - @get:Nested - val xml = XmlExtension() + @Nested + val xml: XmlExtension = project.objects.newInstance(XmlExtension::class.java, project) /** * Extension for json configuration. */ - @get:Nested - val json = JsonExtension() + @Nested + val json: JsonExtension = project.objects.newInstance(JsonExtension::class.java, project) /** * The jdbc driver classes to use. */ - @get:Input - var jdbcDrivers: List = emptyList() + val jdbcDrivers: ListProperty = project.objects.listProperty(String::class.java) /** * The path the sources lie in. Defaults to src/squit. */ - @get:InputDirectory - @get:PathSensitive(PathSensitivity.RELATIVE) val sourceDir: DirectoryProperty = project.objects.directoryProperty() - .convention(project.layout.projectDirectory.dir("src/squit")) /** * The path to save reports and possible failures in. */ - @get:OutputDirectory val reportDir: DirectoryProperty = project.objects.directoryProperty() - .convention(project.layout.buildDirectory.dir("squit/reports")) /** * The timeout in seconds to use for requests. */ - @get:Internal - var timeout = 10L + val requestTimeout: Property = project.objects.property(Long::class.java) /** * If squit should avoid printing anything if all tests pass. */ - @get:Internal - var silent = false + val silent: Property = project.objects.property(Boolean::class.java) /** * If failures should be ignored. * In that case the task passes, even if tests have failed. */ - @get:Input - var ignoreFailures = false + val ignoreFailures: Property = project.objects.property(Boolean::class.java) /** * Helper method to set the sourceDir via String. */ - fun sourceDir(path: String) = sourceDir.apply { - set(project.projectDir.resolve(path)) - } + fun sourceDir(path: String) = sourceDir.set(project.layout.projectDirectory.dir(path)) /** * Helper method to set the reportDir via String. */ - fun reportDir(path: String) = reportDir.apply { - set(project.projectDir.resolve(path)) - } + fun reportDir(path: String) = reportDir.set(project.layout.projectDirectory.dir(path)) /** * Configures the xml dsl. @@ -89,39 +70,42 @@ open class SquitExtension(private val project: Project) { action.execute(xml) } + /** + * Configures the json dsl. + */ + fun json(action: Action) { + action.execute(json) + } + /** * Class containing the available extensions for the xml dsl. */ - open class XmlExtension { + open class XmlExtension @Inject constructor(project: Project) { /** * If the xml diffing should use strict (e.g. identic) comparison. */ - @get:Input - var strict = true + val strict: Property = project.objects.property(Boolean::class.java) /** * If the html report should be canonicalized for xml tests. */ - @get:Input - var canonicalize = true + val canonicalize: Property = project.objects.property(Boolean::class.java) /** * Whether to try to resolve invalid namespaces on canonicalization (e.g. missing http://) */ - @get:Input - var resolveInvalidNamespaces = false + val resolveInvalidNamespaces: Property = project.objects.property(Boolean::class.java) } /** * Class containing the available extensions for the json dsl. */ - open class JsonExtension { + open class JsonExtension @Inject constructor(project: Project) { /** * If the html report should be canonicalized for json tests. */ - @get:Input - var canonicalize = true + val canonicalize: Property = project.objects.property(Boolean::class.java) } } diff --git a/src/main/kotlin/de/smartsquare/squit/SquitPlugin.kt b/src/main/kotlin/de/smartsquare/squit/SquitPlugin.kt index c6c3b30b..73e681e0 100644 --- a/src/main/kotlin/de/smartsquare/squit/SquitPlugin.kt +++ b/src/main/kotlin/de/smartsquare/squit/SquitPlugin.kt @@ -5,7 +5,6 @@ import de.smartsquare.squit.task.SquitPostProcessTask import de.smartsquare.squit.task.SquitPreProcessTask import de.smartsquare.squit.task.SquitRequestTask import de.smartsquare.squit.task.SquitTestTask -import de.smartsquare.squit.util.asPath import org.gradle.api.GradleException import org.gradle.api.Plugin import org.gradle.api.Project @@ -18,22 +17,33 @@ import org.gradle.util.GradleVersion class SquitPlugin : Plugin { override fun apply(project: Project) { - if (GradleVersion.current() < GradleVersion.version("6.8")) { + if (GradleVersion.current() < GradleVersion.version("7.3")) { throw GradleException( - "Minimum supported Gradle version is 6.8. Current version is ${GradleVersion.current().version}." + "Minimum supported Gradle version is 7.3. Current version is ${GradleVersion.current().version}.", ) } - val extension = project.extensions.create("squit", SquitExtension::class.java, project) + val extension = project.extensions.create("squit", SquitExtension::class.java, project).apply { + jdbcDrivers.convention(emptyList()) + sourceDir.convention(project.layout.projectDirectory.dir("src/squit")) + reportDir.convention(project.layout.buildDirectory.dir("squit/reports")) + requestTimeout.convention(10) + silent.convention(false) + ignoreFailures.convention(false) + xml.strict.convention(true) + xml.canonicalize.convention(true) + xml.resolveInvalidNamespaces.convention(false) + json.canonicalize.convention(true) + } project.tasks.register("squitPreProcess", SquitPreProcessTask::class.java) { - it.sourceDir = extension.sourceDir.asPath + it.sourceDir.set(extension.sourceDir) } project.tasks.register("squitRunRequests", SquitRequestTask::class.java) { - it.jdbcDrivers = extension.jdbcDrivers - it.timeout = extension.timeout - it.silent = extension.silent + it.jdbcDrivers.set(extension.jdbcDrivers) + it.requestTimeout.set(extension.requestTimeout) + it.silent.set(extension.silent) it.dependsOn("squitPreProcess") it.outputs.upToDateWhen { false } @@ -44,14 +54,17 @@ class SquitPlugin : Plugin { } project.tasks.register("squitTest", SquitTestTask::class.java) { - it.reportDir = extension.reportDir.asPath - it.silent = extension.silent - it.ignoreFailures = extension.ignoreFailures - it.mediaTypeConfig = MediaTypeConfig( - extension.xml.strict, - extension.xml.canonicalize, - extension.xml.resolveInvalidNamespaces, - extension.json.canonicalize + it.reportDir.set(extension.reportDir) + it.silent.set(extension.silent) + it.ignoreFailures.set(extension.ignoreFailures) + + it.mediaTypeConfig.set( + MediaTypeConfig( + xmlStrict = extension.xml.strict.get(), + xmlCanonicalize = extension.xml.canonicalize.get(), + xmlResolveInvalidNamespaces = extension.xml.resolveInvalidNamespaces.get(), + jsonCanonicalize = extension.json.canonicalize.get(), + ), ) it.dependsOn("squitPostProcess") diff --git a/src/main/kotlin/de/smartsquare/squit/config/ConfigExtensions.kt b/src/main/kotlin/de/smartsquare/squit/config/ConfigExtensions.kt index 58ab4358..4e7bdf1f 100644 --- a/src/main/kotlin/de/smartsquare/squit/config/ConfigExtensions.kt +++ b/src/main/kotlin/de/smartsquare/squit/config/ConfigExtensions.kt @@ -118,7 +118,7 @@ val Config.preTestTasks: List else -> listOf( SquitPreTestTask.PRE_RUNNERS, SquitPreTestTask.PRE_RUNNER_SCRIPTS, - SquitPreTestTask.DATABASE_SCRIPTS + SquitPreTestTask.DATABASE_SCRIPTS, ) } @@ -152,7 +152,7 @@ val Config.postTestTasks: List else -> listOf( SquitPostTestTask.DATABASE_SCRIPTS, SquitPostTestTask.POST_RUNNERS, - SquitPostTestTask.POST_RUNNER_SCRIPTS + SquitPostTestTask.POST_RUNNER_SCRIPTS, ) } @@ -170,7 +170,7 @@ val Config.databaseConfigurations it.getString(DATABASE_CONFIGURATION_NAME), it.getString(DATABASE_CONFIGURATION_JDBC_ADDRESS), it.getString(DATABASE_CONFIGURATION_USERNAME), - it.getString(DATABASE_CONFIGURATION_PASSWORD) + it.getString(DATABASE_CONFIGURATION_PASSWORD), ) } @@ -198,7 +198,7 @@ fun Config.mergeTag(tag: String): Config = withValue(TAGS, ConfigValueFactory.fr */ fun Config.withTestDir(testDir: Path): Config = withValue( TEST_DIRECTORY, - ConfigValueFactory.fromAnyRef(testDir.toString()) + ConfigValueFactory.fromAnyRef(testDir.toString()), ) /** @@ -206,7 +206,14 @@ fun Config.withTestDir(testDir: Path): Config = withValue( */ fun Config.validate() = this.apply { // Call getters of properties to check existence and correct declaration. - endpoint; mediaType; shouldExclude; shouldIgnore; headers; testDir; preTestTasks; postTestTasks + endpoint + mediaType + shouldExclude + shouldIgnore + headers + testDir + preTestTasks + postTestTasks preProcessors.forEach { checkClass(it) } preProcessorScripts.forEach { FilesUtils.validateExistence(it) } @@ -236,7 +243,7 @@ fun Config.writeTo( options: ConfigRenderOptions = ConfigRenderOptions.defaults() .setComments(false) .setOriginComments(false) - .setJson(false) + .setJson(false), ): Path = Files.write(path, root().render(options).toByteArray()) private fun Config.getSafeBoolean(path: String, fallback: Boolean = false) = when (hasPath(path)) { @@ -249,13 +256,11 @@ private fun Config.getSafeString(path: String, fallback: String = "") = when (ha false -> fallback } -private fun Config.getSafeStringList( - path: String, - fallback: List = emptyList() -): List = when (hasPath(path)) { - true -> getStringList(path) - false -> fallback -} +private fun Config.getSafeStringList(path: String, fallback: List = emptyList()): List = + when (hasPath(path)) { + true -> getStringList(path) + false -> fallback + } private fun Config.getSafeConfig(path: String, fallback: Config = ConfigFactory.empty()) = when (hasPath(path)) { true -> getConfig(path) diff --git a/src/main/kotlin/de/smartsquare/squit/config/TestIndexer.kt b/src/main/kotlin/de/smartsquare/squit/config/TestIndexer.kt index f3a6f3d2..86540111 100644 --- a/src/main/kotlin/de/smartsquare/squit/config/TestIndexer.kt +++ b/src/main/kotlin/de/smartsquare/squit/config/TestIndexer.kt @@ -34,7 +34,7 @@ class TestIndexer(private val projectConfig: Config) { * individual tests. */ fun index(sourceDir: Path, filter: (Pair) -> Boolean): List { - val leafDirectories = FilesUtils.getLeafDirectories(sourceDir, sort = true).asSequence() + val leafDirectories = FilesUtils.getLeafDirectories(sourceDir, sort = true) val leafDirectoriesWithConfig = indexConfigs(leafDirectories, sourceDir, filter) return indexTests(leafDirectoriesWithConfig, sourceDir) @@ -43,47 +43,42 @@ class TestIndexer(private val projectConfig: Config) { private fun indexConfigs( leafDirectories: Sequence, sourceDir: Path, - filter: (Pair) -> Boolean - ): List> { - return leafDirectories - .onEach { path -> - if (path.cut(sourceDir).toList().size < 2) { - throw GradleException( - "Invalid project structure. Please add a project directory to the src/squit directory." - ) - } + filter: (Pair) -> Boolean, + ): List> = leafDirectories + .onEach { path -> + if (path.cut(sourceDir).toList().size < 2) { + throw GradleException( + "Invalid project structure. Please add a project directory to the src/squit directory.", + ) } - .map { leafDirectory -> leafDirectory to resolveConfigs(leafDirectory, sourceDir) } - .filter(filter) - .map { (leafDirectory, config) -> - try { - leafDirectory to config.resolve().validate() - } catch (error: Exception) { - val innerMessage = when (error) { - is ConfigException -> - configExceptionMessageRegex - .find(error.message ?: "") - ?.groupValues?.getOrNull(1) - else -> error.message - } + } + .map { leafDirectory -> leafDirectory to resolveConfigs(leafDirectory, sourceDir) } + .filter(filter) + .map { (leafDirectory, config) -> + try { + leafDirectory to config.resolve().validate() + } catch (error: Exception) { + val innerMessage = when (error) { + is ConfigException -> + configExceptionMessageRegex + .find(error.message ?: "") + ?.groupValues?.getOrNull(1) + else -> error.message + } - throw GradleException( - """ + throw GradleException( + """ |Invalid test.conf or local.conf file on path of test: | ${leafDirectory.cut(sourceDir)} ($innerMessage) - """.trimMargin().replace("\n", ""), - error - ) - } + """.trimMargin().replace("\n", ""), + error, + ) } - .toList() - } + } + .toList() - private fun indexTests( - leafDirectoriesWithConfig: List>, - sourceDir: Path - ): List { - return leafDirectoriesWithConfig + private fun indexTests(leafDirectoriesWithConfig: List>, sourceDir: Path): List = + leafDirectoriesWithConfig .filterNot { (path, _) -> FilesUtils.isDirectoryEmpty(path) } .mapNotNull { (leafDirectory, config) -> val request = resolveRequest(leafDirectory, config) @@ -121,27 +116,24 @@ class TestIndexer(private val projectConfig: Config) { else -> testParts.reduce { acc, test -> acc.merge(test) } } } - } - private fun resolveConfigs(path: Path, sourceDir: Path): Config { - return FilesUtils.walkUpwards(path, sourceDir) - .map { it to resolveConfig(it) } - .fold(ConfigFactory.empty()) { acc, currentPathToConfig -> - val (currentPath, config) = currentPathToConfig - - // Do not add tag for the last part since it is part of the sourceDir. - if (currentPath.endsWith(sourceDir)) { - acc.withFallback(config) - } else { - acc.withFallback(config).mergeTag(currentPath.fileName.toString()) - } - } - .let { - projectConfig - .withTestDir(path) - .withFallback(it) + private fun resolveConfigs(path: Path, sourceDir: Path): Config = FilesUtils.walkUpwards(path, sourceDir) + .map { it to resolveConfig(it) } + .fold(ConfigFactory.empty()) { acc, currentPathToConfig -> + val (currentPath, config) = currentPathToConfig + + // Do not add tag for the last part since it is part of the sourceDir. + if (currentPath.endsWith(sourceDir)) { + acc.withFallback(config) + } else { + acc.withFallback(config).mergeTag(currentPath.fileName.toString()) } - } + } + .let { + projectConfig + .withTestDir(path) + .withFallback(it) + } private fun resolveConfig(path: Path): Config { val configPath = path.resolve(Constants.CONFIG) @@ -167,34 +159,28 @@ class TestIndexer(private val projectConfig: Config) { } } - private fun resolveResponse(path: Path, config: Config): Path { - return FilesUtils.validateExistence( - path.resolve(MediaTypeFactory.sourceResponse(config.mediaType)) - ) - } + private fun resolveResponse(path: Path, config: Config): Path = FilesUtils.validateExistence( + path.resolve(MediaTypeFactory.sourceResponse(config.mediaType)), + ) private fun resolveSqlScripts( path: Path, config: Config, leafs: List, - leafPath: Path - ): Map { - return config.databaseConfigurations.associate { databaseConfig -> - val pre = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_pre.sql")) - val preOnce = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_pre_once.sql")) - ?.takeIf { leafs.firstOrNull() == leafPath } - - val post = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_post.sql")) - val postOnce = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_post_once.sql")) - ?.takeIf { leafs.lastOrNull() == leafPath } - - databaseConfig.name to SqlScripts(pre, preOnce, post, postOnce) - } - } + leafPath: Path, + ): Map = config.databaseConfigurations.associate { databaseConfig -> + val pre = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_pre.sql")) + val preOnce = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_pre_once.sql")) + ?.takeIf { leafs.firstOrNull() == leafPath } - private fun resolveDescription(path: Path): Path? { - return FilesUtils.ifExists(path.resolve(DESCRIPTION)) + val post = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_post.sql")) + val postOnce = FilesUtils.ifExists(path.resolve("${databaseConfig.name}_post_once.sql")) + ?.takeIf { leafs.lastOrNull() == leafPath } + + databaseConfig.name to SqlScripts(pre, preOnce, post, postOnce) } + private fun resolveDescription(path: Path): Path? = FilesUtils.ifExists(path.resolve(DESCRIPTION)) + private data class SqlScripts(val pre: Path?, val preOnce: Path?, val post: Path?, val postOnce: Path?) } diff --git a/src/main/kotlin/de/smartsquare/squit/entity/SquitDatabaseConfiguration.kt b/src/main/kotlin/de/smartsquare/squit/entity/SquitDatabaseConfiguration.kt index 6bb127c2..98be586c 100644 --- a/src/main/kotlin/de/smartsquare/squit/entity/SquitDatabaseConfiguration.kt +++ b/src/main/kotlin/de/smartsquare/squit/entity/SquitDatabaseConfiguration.kt @@ -12,5 +12,5 @@ data class SquitDatabaseConfiguration( val name: String, val jdbcAddress: String, val username: String, - val password: String + val password: String, ) diff --git a/src/main/kotlin/de/smartsquare/squit/entity/SquitMetaInfo.kt b/src/main/kotlin/de/smartsquare/squit/entity/SquitMetaInfo.kt index 484d975f..1a00d4f1 100644 --- a/src/main/kotlin/de/smartsquare/squit/entity/SquitMetaInfo.kt +++ b/src/main/kotlin/de/smartsquare/squit/entity/SquitMetaInfo.kt @@ -25,7 +25,7 @@ data class SquitMetaInfo(val date: LocalDateTime, val duration: Long) { return SquitMetaInfo( LocalDateTime.parse(config.getString(DATE)), - config.getLong(DURATION) + config.getLong(DURATION), ) } } @@ -36,7 +36,7 @@ data class SquitMetaInfo(val date: LocalDateTime, val duration: Long) { fun toJson(): String = Gson().toJson( mapOf( DATE to date.toString(), - DURATION to duration - ) + DURATION to duration, + ), ) } diff --git a/src/main/kotlin/de/smartsquare/squit/entity/SquitResponseInfo.kt b/src/main/kotlin/de/smartsquare/squit/entity/SquitResponseInfo.kt index 339be919..a95e5c84 100644 --- a/src/main/kotlin/de/smartsquare/squit/entity/SquitResponseInfo.kt +++ b/src/main/kotlin/de/smartsquare/squit/entity/SquitResponseInfo.kt @@ -18,14 +18,12 @@ data class SquitResponseInfo(val responseCode: Int = 0) { /** * Constructs a [SquitResponseInfo] instance from the given [json] String. */ - fun fromJson(json: String): SquitResponseInfo = - Gson().fromJson(json, SquitResponseInfo::class.java) + fun fromJson(json: String): SquitResponseInfo = Gson().fromJson(json, SquitResponseInfo::class.java) /** * Constructs a [SquitResponseInfo] instance from the given [config] Config. */ - fun fromConfig(config: Config): SquitResponseInfo = - SquitResponseInfo(config.expectedResponseCode) + fun fromConfig(config: Config): SquitResponseInfo = SquitResponseInfo(config.expectedResponseCode) } /** @@ -33,8 +31,8 @@ data class SquitResponseInfo(val responseCode: Int = 0) { */ fun toJson(): String = GsonBuilder().setPrettyPrinting().create().toJson( mapOf( - RESPONSE_CODE to responseCode - ) + RESPONSE_CODE to responseCode, + ), ) /** diff --git a/src/main/kotlin/de/smartsquare/squit/entity/SquitResult.kt b/src/main/kotlin/de/smartsquare/squit/entity/SquitResult.kt index 41e063b9..213c0c80 100644 --- a/src/main/kotlin/de/smartsquare/squit/entity/SquitResult.kt +++ b/src/main/kotlin/de/smartsquare/squit/entity/SquitResult.kt @@ -41,7 +41,7 @@ data class SquitResult( private val contextPath: Path, private val suitePath: Path, private val testDirectoryPath: Path, - private val squitBuildDirectoryPath: Path + private val squitBuildDirectoryPath: Path, ) { /** diff --git a/src/main/kotlin/de/smartsquare/squit/entity/SquitResultTree.kt b/src/main/kotlin/de/smartsquare/squit/entity/SquitResultTree.kt index 943da9a1..14ec1036 100644 --- a/src/main/kotlin/de/smartsquare/squit/entity/SquitResultTree.kt +++ b/src/main/kotlin/de/smartsquare/squit/entity/SquitResultTree.kt @@ -19,7 +19,7 @@ data class SquitResultTree( val name: String, val successfulTests: Int, val failedTests: Int, - val ignoredTests: Int + val ignoredTests: Int, ) { companion object { @@ -41,7 +41,7 @@ data class SquitResultTree( group.first().combinedName, successfulTests, failedTests, - ignoredTests + ignoredTests, ) } else { SquitResultTree( @@ -50,7 +50,7 @@ data class SquitResultTree( path.first().fileName.toString(), successfulTests, failedTests, - ignoredTests + ignoredTests, ) } } diff --git a/src/main/kotlin/de/smartsquare/squit/entity/SquitTest.kt b/src/main/kotlin/de/smartsquare/squit/entity/SquitTest.kt index d96776d5..1b541890 100644 --- a/src/main/kotlin/de/smartsquare/squit/entity/SquitTest.kt +++ b/src/main/kotlin/de/smartsquare/squit/entity/SquitTest.kt @@ -23,7 +23,7 @@ data class SquitTest( val response: Path, val preSqlScripts: Map>, val postSqlScripts: Map>, - val descriptions: List + val descriptions: List, ) : Serializable { private companion object { @@ -50,17 +50,15 @@ data class SquitTest( // Paths are not serializable so we have to copy to a special proxy class with Strings instead of paths. // This should be hidden from the user. @Suppress("UnusedPrivateMember") - private fun writeReplace(): Any { - return SquitTestSerializationProxy( - path.toString(), - config, - request?.toString(), - response.toString(), - preSqlScripts.mapValues { (_, scripts) -> scripts.map { it.toString() } }, - postSqlScripts.mapValues { (_, scripts) -> scripts.map { it.toString() } }, - descriptions.map { it.toString() } - ) - } + private fun writeReplace(): Any = SquitTestSerializationProxy( + path.toString(), + config, + request?.toString(), + response.toString(), + preSqlScripts.mapValues { (_, scripts) -> scripts.map { it.toString() } }, + postSqlScripts.mapValues { (_, scripts) -> scripts.map { it.toString() } }, + descriptions.map { it.toString() }, + ) private data class SquitTestSerializationProxy( val path: String, @@ -69,7 +67,7 @@ data class SquitTest( val response: String, val preSqlScripts: Map>, val postSqlScripts: Map>, - val descriptions: List + val descriptions: List, ) : Serializable { private companion object { @@ -84,7 +82,7 @@ data class SquitTest( Paths.get(response), preSqlScripts.mapValues { (_, scripts) -> scripts.map { Paths.get(it) } }, postSqlScripts.mapValues { (_, scripts) -> scripts.map { Paths.get(it) } }, - descriptions.map { Paths.get(it) } + descriptions.map { Paths.get(it) }, ) } } diff --git a/src/main/kotlin/de/smartsquare/squit/io/FilesUtils.kt b/src/main/kotlin/de/smartsquare/squit/io/FilesUtils.kt index 55bce0cd..55793b3f 100644 --- a/src/main/kotlin/de/smartsquare/squit/io/FilesUtils.kt +++ b/src/main/kotlin/de/smartsquare/squit/io/FilesUtils.kt @@ -78,9 +78,8 @@ object FilesUtils { /** * Checks whether the directory at the given [path] is empty. */ - fun isDirectoryEmpty(path: Path): Boolean { - return Files.newDirectoryStream(path).use { dirStream -> !dirStream.iterator().hasNext() } - } + fun isDirectoryEmpty(path: Path): Boolean = + Files.newDirectoryStream(path).use { dirStream -> !dirStream.iterator().hasNext() } /** * Returns the given [path] if it exists or null otherwise. @@ -114,12 +113,10 @@ object FilesUtils { /** * Creates a new [BufferedReader] for the given [path] and executes [block] with improved error handling. */ - fun useBufferedReader(path: Path, block: (BufferedReader) -> T): T { - return try { - Files.newBufferedReader(path).use(block) - } catch (error: MalformedInputException) { - throw IOException("Error reading file $path. Squit expects UTF-8 encoded files only.", error) - } + fun useBufferedReader(path: Path, block: (BufferedReader) -> T): T = try { + Files.newBufferedReader(path).use(block) + } catch (error: MalformedInputException) { + throw IOException("Error reading file $path. Squit expects UTF-8 encoded files only.", error) } /** diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/BodyProcessor.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/BodyProcessor.kt index 9d2e5cfd..6c8599f6 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/BodyProcessor.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/BodyProcessor.kt @@ -17,7 +17,7 @@ interface BodyProcessor { responsePath: Path, resultRequestPath: Path, resultResponsePath: Path, - config: Config + config: Config, ) /** @@ -28,6 +28,6 @@ interface BodyProcessor { actualResponsePath: Path, expectedResponsePath: Path, resultActualResponseFilePath: Path, - config: Config + config: Config, ) } diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/MediaTypeConfig.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/MediaTypeConfig.kt index e97efef5..48f06203 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/MediaTypeConfig.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/MediaTypeConfig.kt @@ -12,6 +12,6 @@ import org.gradle.api.tasks.Input data class MediaTypeConfig( @get:Input val xmlStrict: Boolean = true, @get:Input val xmlCanonicalize: Boolean = true, - @get:Input val resolveInvalidNamespaces: Boolean = false, - @get:Input val jsonCanonicalize: Boolean = true + @get:Input val xmlResolveInvalidNamespaces: Boolean = false, + @get:Input val jsonCanonicalize: Boolean = true, ) diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericBodyProcessor.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericBodyProcessor.kt index 7c9dd73c..705a79a6 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericBodyProcessor.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericBodyProcessor.kt @@ -15,7 +15,7 @@ class GenericBodyProcessor : BodyProcessor { responsePath: Path, resultRequestPath: Path, resultResponsePath: Path, - config: Config + config: Config, ) { if (requestPath != null) Files.copy(requestPath, resultRequestPath) Files.copy(responsePath, resultResponsePath) @@ -25,7 +25,7 @@ class GenericBodyProcessor : BodyProcessor { actualResponsePath: Path, expectedResponsePath: Path, resultActualResponseFilePath: Path, - config: Config + config: Config, ) { Files.copy(actualResponsePath, resultActualResponseFilePath) } diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericCanonicalizer.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericCanonicalizer.kt index 176bd605..bb13b0c4 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericCanonicalizer.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericCanonicalizer.kt @@ -8,7 +8,5 @@ import de.smartsquare.squit.mediatype.MediaTypeConfig */ class GenericCanonicalizer : Canonicalizer { - override fun canonicalize(input: String, mediaTypeConfig: MediaTypeConfig): String { - return input - } + override fun canonicalize(input: String, mediaTypeConfig: MediaTypeConfig): String = input } diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericDiffer.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericDiffer.kt index c9c5e260..3cd4f3cc 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericDiffer.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/generic/GenericDiffer.kt @@ -13,7 +13,7 @@ class GenericDiffer : Differ { val diff = DiffUtils.diff( expectedResponse.toString(Charset.defaultCharset()), actualResponse.toString(Charset.defaultCharset()), - null + null, ) return diff.deltas.joinToString("\n") { diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonBodyProcessor.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonBodyProcessor.kt index 380a3db5..d23aaec6 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonBodyProcessor.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonBodyProcessor.kt @@ -26,7 +26,7 @@ class JsonBodyProcessor : BodyProcessor { responsePath: Path, resultRequestPath: Path, resultResponsePath: Path, - config: Config + config: Config, ) { val request = requestPath?.let { JsonParserSupport.read(it) } val response = JsonParserSupport.read(responsePath) @@ -41,7 +41,7 @@ class JsonBodyProcessor : BodyProcessor { actualResponsePath: Path, expectedResponsePath: Path, resultActualResponseFilePath: Path, - config: Config + config: Config, ) { val actualResponse = JsonParserSupport.read(actualResponsePath) val expectedResponse = JsonParserSupport.read(expectedResponsePath) @@ -53,7 +53,7 @@ class JsonBodyProcessor : BodyProcessor { private fun runPreProcessors(config: Config, request: JsonElement?, response: JsonElement) { config.preProcessors.map { Class.forName(it).getConstructor().newInstance() } - .filterIsInstance(SquitJsonPreProcessor::class.java) + .filterIsInstance() .forEach { it.process(request, response, config) } config.preProcessorScripts.forEach { @@ -62,8 +62,8 @@ class JsonBodyProcessor : BodyProcessor { mapOf( "request" to request, "expectedResponse" to response, - "config" to config - ) + "config" to config, + ), ) }.run() } @@ -71,7 +71,7 @@ class JsonBodyProcessor : BodyProcessor { private fun runPostProcessors(config: Config, actualResponse: JsonElement, expectedResponse: JsonElement) { config.postProcessors.map { Class.forName(it).getConstructor().newInstance() } - .filterIsInstance(SquitJsonPostProcessor::class.java) + .filterIsInstance() .forEach { it.process(actualResponse, expectedResponse, config) } config.postProcessorScripts.forEach { @@ -79,8 +79,8 @@ class JsonBodyProcessor : BodyProcessor { binding = Binding( mapOf( "actualResponse" to actualResponse, - "expectedResponse" to expectedResponse - ) + "expectedResponse" to expectedResponse, + ), ) }.run() } diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizer.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizer.kt index e009faec..c4ea2126 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizer.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizer.kt @@ -14,37 +14,34 @@ class JsonCanonicalizer : Canonicalizer { private val gson = GsonBuilder().setPrettyPrinting().create() - override fun canonicalize(input: String, mediaTypeConfig: MediaTypeConfig): String { - return if (mediaTypeConfig.jsonCanonicalize) { + override fun canonicalize(input: String, mediaTypeConfig: MediaTypeConfig): String = + if (mediaTypeConfig.jsonCanonicalize) { val element = gson.fromJson(input, JsonElement::class.java) gson.toJson(element.canonicalize()) } else { input } - } - private fun JsonElement.canonicalize(): JsonElement { - return when (this) { - is JsonObject -> { - val newEntries = entrySet().map { (key, value) -> key to value.canonicalize() } + private fun JsonElement.canonicalize(): JsonElement = when (this) { + is JsonObject -> { + val newEntries = entrySet().map { (key, value) -> key to value.canonicalize() } - JsonObject().also { newObject -> - newEntries.sortedBy { (key) -> key }.forEach { (key, value) -> - newObject.add(key, value) - } + JsonObject().also { newObject -> + newEntries.sortedBy { (key) -> key }.forEach { (key, value) -> + newObject.add(key, value) } } - is JsonArray -> { - val newEntries = this.map { it.canonicalize() } + } + is JsonArray -> { + val newEntries = this.map { it.canonicalize() } - JsonArray().also { newArray -> - newEntries.forEach { - newArray.add(it) - } + JsonArray().also { newArray -> + newEntries.forEach { + newArray.add(it) } } - else -> this } + else -> this } } diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonDiffer.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonDiffer.kt index 02ba4426..727c1e46 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonDiffer.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/json/JsonDiffer.kt @@ -8,16 +8,14 @@ import net.javacrumbs.jsonunit.JsonAssert */ class JsonDiffer : Differ { - override fun diff(expectedResponse: ByteArray, actualResponse: ByteArray): String { - return try { - JsonAssert.assertJsonEquals( - expectedResponse.toString(Charsets.UTF_8), - actualResponse.toString(Charsets.UTF_8) - ) + override fun diff(expectedResponse: ByteArray, actualResponse: ByteArray): String = try { + JsonAssert.assertJsonEquals( + expectedResponse.toString(Charsets.UTF_8), + actualResponse.toString(Charsets.UTF_8), + ) - "" - } catch (error: AssertionError) { - requireNotNull(error.message) - } + "" + } catch (error: AssertionError) { + requireNotNull(error.message) } } diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlBodyProcessor.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlBodyProcessor.kt index 127c3066..e754caee 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlBodyProcessor.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlBodyProcessor.kt @@ -26,7 +26,7 @@ class XmlBodyProcessor : BodyProcessor { responsePath: Path, resultRequestPath: Path, resultResponsePath: Path, - config: Config + config: Config, ) { val request = requestPath?.let { SAXReaderSupport.read(requestPath) } val response = SAXReaderSupport.read(responsePath) @@ -41,7 +41,7 @@ class XmlBodyProcessor : BodyProcessor { actualResponsePath: Path, expectedResponsePath: Path, resultActualResponseFilePath: Path, - config: Config + config: Config, ) { val actualResponse = SAXReaderSupport.read(actualResponsePath) val expectedResponse = SAXReaderSupport.read(expectedResponsePath) @@ -53,7 +53,7 @@ class XmlBodyProcessor : BodyProcessor { private fun runPreProcessors(config: Config, request: Document?, response: Document) { config.preProcessors.map { Class.forName(it).getConstructor().newInstance() } - .filterIsInstance(SquitXmlPreProcessor::class.java) + .filterIsInstance() .forEach { it.process(request, response, config) } config.preProcessorScripts.forEach { @@ -62,8 +62,8 @@ class XmlBodyProcessor : BodyProcessor { mapOf( "request" to request, "expectedResponse" to response, - "config" to config - ) + "config" to config, + ), ) }.run() } @@ -71,7 +71,7 @@ class XmlBodyProcessor : BodyProcessor { private fun runPostProcessors(config: Config, actualResponse: Document, expectedResponse: Document) { config.postProcessors.map { Class.forName(it).getConstructor().newInstance() } - .filterIsInstance(SquitXmlPostProcessor::class.java) + .filterIsInstance() .forEach { it.process(actualResponse, expectedResponse, config) } config.postProcessorScripts.forEach { @@ -79,8 +79,8 @@ class XmlBodyProcessor : BodyProcessor { binding = Binding( mapOf( "actualResponse" to actualResponse, - "expectedResponse" to expectedResponse - ) + "expectedResponse" to expectedResponse, + ), ) }.run() } diff --git a/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizer.kt b/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizer.kt index bf1da6e7..61d63945 100644 --- a/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizer.kt +++ b/src/main/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizer.kt @@ -26,19 +26,21 @@ class XmlCanonicalizer : Canonicalizer { } private companion object { + private const val RESOLVE_NAMESPACE_STRING = "http://" + private val xmlNamespaceRegex = Regex("(xmlns:\\w+=['\"])(.*?)(['\"])") private val urlRegex = Regex("^https?://") - private const val resolveNamespaceString = "http://" } - override fun canonicalize(input: String, mediaTypeConfig: MediaTypeConfig): String { - return if (mediaTypeConfig.xmlCanonicalize) { + override fun canonicalize(input: String, mediaTypeConfig: MediaTypeConfig): String = + if (mediaTypeConfig.xmlCanonicalize) { val outputStream = ByteArrayOutputStream() - val content = if (mediaTypeConfig.resolveInvalidNamespaces) + val content = if (mediaTypeConfig.xmlResolveInvalidNamespaces) { resolveInvalidNamespaces(input) - else + } else { input + } canonicalizer.canonicalize(content.toByteArray(), outputStream, false) @@ -46,25 +48,20 @@ class XmlCanonicalizer : Canonicalizer { } else { input } - } - private fun resolveInvalidNamespaces(content: String): String { - return content.replace(xmlNamespaceRegex) { match -> - val start = match.groupValues[1] - val potentialUrlString = match.groupValues[2] - val end = match.groupValues[3] + private fun resolveInvalidNamespaces(content: String): String = content.replace(xmlNamespaceRegex) { match -> + val start = match.groupValues[1] + val potentialUrlString = match.groupValues[2] + val end = match.groupValues[3] - if (!potentialUrlString.contains(urlRegex)) { - "$start$resolveNamespaceString$potentialUrlString$end" - } else { - "$start$potentialUrlString$end" - } + if (!potentialUrlString.contains(urlRegex)) { + "$start$RESOLVE_NAMESPACE_STRING$potentialUrlString$end" + } else { + "$start$potentialUrlString$end" } } - private fun Document.asString(outputFormat: OutputFormat = SquitOutputFormat): String { - return StringWriter() - .also { XMLWriter(it, outputFormat).write(this) } - .toString() - } + private fun Document.asString(outputFormat: OutputFormat = SquitOutputFormat): String = StringWriter() + .also { XMLWriter(it, outputFormat).write(this) } + .toString() } diff --git a/src/main/kotlin/de/smartsquare/squit/report/HtmlReportWriter.kt b/src/main/kotlin/de/smartsquare/squit/report/HtmlReportWriter.kt index 56aa796a..d4a103ef 100644 --- a/src/main/kotlin/de/smartsquare/squit/report/HtmlReportWriter.kt +++ b/src/main/kotlin/de/smartsquare/squit/report/HtmlReportWriter.kt @@ -25,25 +25,25 @@ class HtmlReportWriter(private val logger: Logger) { private const val DIFF_CONTEXT_SIZE = 1_000_000 private const val HTML_LINE_ENDING = "\\n\\\n" - private const val bootstrapPath = "META-INF/resources/webjars/bootstrap/4.6.0/dist" - private const val fontAwesomePath = "META-INF/resources/webjars/font-awesome/5.15.4" - private const val jqueryPath = "META-INF/resources/webjars/jquery/3.6.0/dist" - private const val popperJsPath = "META-INF/resources/webjars/popper.js/1.16.1/dist/umd" - private const val markedPath = "META-INF/resources/webjars/marked/2.0.6" - private const val diff2htmlPath = "META-INF/resources/webjars/diff2html/3.1.7" + private const val BOOTSTRAP_PATH = "META-INF/resources/webjars/bootstrap/4.6.0/dist" + private const val FONT_AWESOME_PATH = "META-INF/resources/webjars/font-awesome/5.15.4" + private const val JQUERY_PATH = "META-INF/resources/webjars/jquery/3.6.0/dist" + private const val POPPER_JS_PATH = "META-INF/resources/webjars/popper.js/1.16.1/dist/umd" + private const val MARKED_PATH = "META-INF/resources/webjars/marked/2.0.6" + private const val DIFF_2_HTML_PATH = "META-INF/resources/webjars/diff2html/3.1.7" private val resources = arrayOf( - "$bootstrapPath/css/bootstrap.min.css" to "css/bootstrap.css", - "$bootstrapPath/js/bootstrap.min.js" to "js/bootstrap.js", - "$fontAwesomePath/js/all.min.js" to "js/fontawesome.js", - "$jqueryPath/jquery.slim.min.js" to "js/jquery.js", - "$popperJsPath/popper.min.js" to "js/popper.js", - "$markedPath/marked.min.js" to "js/marked.js", - "$diff2htmlPath/bundles/css/diff2html.min.css" to "css/diff2html.css", - "$diff2htmlPath/bundles/js/diff2html.min.js" to "js/diff2html.js", - "$diff2htmlPath/bundles/js/diff2html-ui.min.js" to "js/diff2html-ui.js", + "$BOOTSTRAP_PATH/css/bootstrap.min.css" to "css/bootstrap.css", + "$BOOTSTRAP_PATH/js/bootstrap.min.js" to "js/bootstrap.js", + "$FONT_AWESOME_PATH/js/all.min.js" to "js/fontawesome.js", + "$JQUERY_PATH/jquery.slim.min.js" to "js/jquery.js", + "$POPPER_JS_PATH/popper.min.js" to "js/popper.js", + "$MARKED_PATH/marked.min.js" to "js/marked.js", + "$DIFF_2_HTML_PATH/bundles/css/diff2html.min.css" to "css/diff2html.css", + "$DIFF_2_HTML_PATH/bundles/js/diff2html.min.js" to "js/diff2html.js", + "$DIFF_2_HTML_PATH/bundles/js/diff2html-ui.min.js" to "js/diff2html-ui.js", "squit.js" to "js/squit.js", - "squit.css" to "css/squit.css" + "squit.css" to "css/squit.css", ) private val emptyDiffHeader = listOf("--- $DIFF_FILE_NAME", "+++ $DIFF_FILE_NAME", "@@ -1 +1 @@") @@ -52,11 +52,7 @@ class HtmlReportWriter(private val logger: Logger) { /** * Generates and writes the Squit html report, given the [results] list and [reportDirectoryPath]. */ - fun writeReport( - results: List, - reportDirectoryPath: Path, - mediaTypeConfig: MediaTypeConfig - ) { + fun writeReport(results: List, reportDirectoryPath: Path, mediaTypeConfig: MediaTypeConfig) { val document = StringBuilder("").appendHTML().html { squitHead() squitBody(results) @@ -78,7 +74,7 @@ class HtmlReportWriter(private val logger: Logger) { result.expectedLines, result.mediaType, mediaTypeConfig, - "Could not canonicalize expected response" + "Could not canonicalize expected response", ) else -> result.expectedLines } @@ -88,7 +84,7 @@ class HtmlReportWriter(private val logger: Logger) { result.actualLines, result.mediaType, mediaTypeConfig, - "Could not canonicalize actual response" + "Could not canonicalize actual response", ) else -> result.actualLines } @@ -98,8 +94,12 @@ class HtmlReportWriter(private val logger: Logger) { val unifiedDiffForJs = prepareForJs(bodyDiff) val unifiedInfoDiffForJs = prepareInfoForJs(result) - val descriptionForReplacement = if (result.description == null) "null" else "\"${result.description}\"" - .replace("\n", HTML_LINE_ENDING) + val descriptionForReplacement = if (result.description == null) { + "null" + } else { + "\"${result.description}\"" + .replace("\n", HTML_LINE_ENDING) + } Files.createDirectories(detailPath) Files.write(detailHtmlPath, detailDocument.toString().toByteArray()) @@ -124,8 +124,8 @@ class HtmlReportWriter(private val logger: Logger) { } // Visible for testing. - internal fun prepareInfoForJs(result: SquitResult): String { - return if (!result.expectedResponseInfo.isDefault && !result.isError) { + internal fun prepareInfoForJs(result: SquitResult): String = + if (!result.expectedResponseInfo.isDefault && !result.isError) { val expectedInfoLines = result.expectedResponseInfo.toJson().lines() val actualInfo = result.actualInfoLines.joinToString(separator = "\n") @@ -140,33 +140,28 @@ class HtmlReportWriter(private val logger: Logger) { } else { "" } - } - private fun prepareForJs(bodyDiff: List): String { - return bodyDiff - .map { it.replace(Regex("(?): String = bodyDiff + .map { it.replace(Regex("(?, mediaType: MediaType, mediaTypeConfig: MediaTypeConfig, - errorMessage: String - ): List { - return when { - lines.isEmpty() -> lines - else -> try { - MediaTypeFactory.canonicalizer(mediaType) - .canonicalize(lines.joinToString(""), mediaTypeConfig) - .lines() - } catch (error: Exception) { - logger.warn(errorMessage, error) - - lines - } + errorMessage: String, + ): List = when { + lines.isEmpty() -> lines + else -> try { + MediaTypeFactory.canonicalizer(mediaType) + .canonicalize(lines.joinToString(""), mediaTypeConfig) + .lines() + } catch (error: Exception) { + logger.warn(errorMessage, error) + + lines } } @@ -178,7 +173,7 @@ class HtmlReportWriter(private val logger: Logger) { filename, expectedLines, diff, - DIFF_CONTEXT_SIZE + DIFF_CONTEXT_SIZE, ) return when (unifiedDiff.isEmpty()) { diff --git a/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessRunner.kt b/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessRunner.kt index 238e472b..49bdc9b5 100644 --- a/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessRunner.kt +++ b/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessRunner.kt @@ -17,14 +17,9 @@ object SquitPostProcessRunner { /** * Runs the post processing. */ - fun run( - processedSourcesPath: Path, - actualResponsesPath: Path, - processedActualResponsesPath: Path, - testPath: Path - ) { + fun run(processedSourcesPath: Path, actualResponsesPath: Path, processedActualResponsesPath: Path, testPath: Path) { val resultActualResponsePath = Files.createDirectories( - processedActualResponsesPath.resolve(testPath.cut(actualResponsesPath)) + processedActualResponsesPath.resolve(testPath.cut(actualResponsesPath)), ) val errorFile = testPath.resolve(Constants.ERROR) @@ -39,13 +34,13 @@ object SquitPostProcessRunner { val config = ConfigFactory.parseFile(configPath.toFile()) val actualResponsePath = FilesUtils.validateExistence( - testPath.resolve(MediaTypeFactory.actualResponse(config.mediaType)) + testPath.resolve(MediaTypeFactory.actualResponse(config.mediaType)), ) val expectedResponsePath = FilesUtils.validateExistence( processedSourcesPath .resolve(testPath.cut(actualResponsesPath)) - .resolve(MediaTypeFactory.expectedResponse(config.mediaType)) + .resolve(MediaTypeFactory.expectedResponse(config.mediaType)), ) val resultActualResponseFilePath = resultActualResponsePath diff --git a/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessTask.kt b/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessTask.kt index 0d5d80dd..dd45a365 100644 --- a/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessTask.kt +++ b/src/main/kotlin/de/smartsquare/squit/task/SquitPostProcessTask.kt @@ -8,9 +8,11 @@ import de.smartsquare.squit.util.Constants.RESPONSES_DIRECTORY import de.smartsquare.squit.util.Constants.SOURCES_DIRECTORY import de.smartsquare.squit.util.Constants.SQUIT_DIRECTORY import de.smartsquare.squit.util.asPath +import de.smartsquare.squit.util.dir import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileTree import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.FileTree +import org.gradle.api.provider.Provider import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFiles @@ -19,42 +21,27 @@ import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction -import org.gradle.util.GradleVersion import org.gradle.workers.WorkAction import org.gradle.workers.WorkParameters import org.gradle.workers.WorkerExecutor import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths import javax.inject.Inject /** * Task for post-processing the responses. */ @CacheableTask -open class SquitPostProcessTask @Inject constructor(private val workerExecutor: WorkerExecutor) : DefaultTask() { +abstract class SquitPostProcessTask @Inject constructor(private val workerExecutor: WorkerExecutor) : DefaultTask() { /** * The directory of the test sources. */ - @InputDirectory - @PathSensitive(PathSensitivity.RELATIVE) - val processedSourcesPath: Path = Paths.get( - project.buildDir.path, - SQUIT_DIRECTORY, - SOURCES_DIRECTORY - ) + @get:InputDirectory + @get:PathSensitive(PathSensitivity.RELATIVE) + val processedSourcesDir = project.layout.buildDirectory.dir(SQUIT_DIRECTORY, SOURCES_DIRECTORY) - /** - * The directory of the previously requested responses. - */ - @Internal - val actualResponsesPath: Path = Paths.get( - project.buildDir.path, - SQUIT_DIRECTORY, - RESPONSES_DIRECTORY, - RAW_DIRECTORY - ) + @get:Internal + val actualResponsesDir = project.layout.buildDirectory.dir(SQUIT_DIRECTORY, RESPONSES_DIRECTORY, RAW_DIRECTORY) /** * Collection of actual response files except meta.json files for up-to-date checking. @@ -62,19 +49,15 @@ open class SquitPostProcessTask @Inject constructor(private val workerExecutor: @Suppress("unused") @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) - val actualResponsesFiles: ConfigurableFileTree = project - .fileTree(actualResponsesPath) { it.exclude("**/$META") } + val actualResponseFiles: Provider = actualResponsesDir + .map { dir -> dir.asFileTree.matching { tree -> tree.exclude("**/$META") } } /** * The directory to save the results in. */ - @OutputDirectory - val processedActualResponsesPath: Path = Paths.get( - project.buildDir.path, - SQUIT_DIRECTORY, - RESPONSES_DIRECTORY, - PROCESSED_DIRECTORY - ) + @get:OutputDirectory + val processedActualResponseDir = project.layout.buildDirectory + .dir(SQUIT_DIRECTORY, RESPONSES_DIRECTORY, PROCESSED_DIRECTORY) init { group = "Build" @@ -86,39 +69,28 @@ open class SquitPostProcessTask @Inject constructor(private val workerExecutor: */ @TaskAction fun run() { - FilesUtils.deleteRecursivelyIfExisting(processedActualResponsesPath) - Files.createDirectories(processedActualResponsesPath) + FilesUtils.deleteRecursivelyIfExisting(processedActualResponseDir.asPath) + Files.createDirectories(processedActualResponseDir.asPath) - if (GradleVersion.current() >= GradleVersion.version("5.6")) { - val workerQueue = workerExecutor.noIsolation() + val workerQueue = workerExecutor.noIsolation() - FilesUtils.getLeafDirectories(actualResponsesPath, sort = false).forEach { testPath -> - workerQueue.submit(Worker::class.java) { - it.processedSourcesPath.set(processedSourcesPath.toFile()) - it.actualResponsesPath.set(actualResponsesPath.toFile()) - it.processedActualResponsesPath.set(processedActualResponsesPath.toFile()) - it.testPath.set(testPath.toFile()) - } - } - } else { - FilesUtils.getLeafDirectories(actualResponsesPath, sort = false).forEach { testPath -> - SquitPostProcessRunner.run( - processedSourcesPath, actualResponsesPath, processedActualResponsesPath, testPath - ) + FilesUtils.getLeafDirectories(actualResponsesDir.asPath, sort = false).forEach { testPath -> + workerQueue.submit(Worker::class.java) { + it.processedSourcesPath.set(processedSourcesDir.get().asFile) + it.actualResponsesPath.set(actualResponsesDir.get().asFile) + it.processedActualResponsesPath.set(processedActualResponseDir.get().asFile) + it.testPath.set(testPath.toFile()) } } } internal abstract class Worker : WorkAction { - - private val processedSourcesPath get() = parameters.processedSourcesPath.asPath - private val actualResponsesPath get() = parameters.actualResponsesPath.asPath - private val processedActualResponsesPath get() = parameters.processedActualResponsesPath.asPath - private val testPath get() = parameters.testPath.asPath - override fun execute() { SquitPostProcessRunner.run( - processedSourcesPath, actualResponsesPath, processedActualResponsesPath, testPath + processedSourcesPath = parameters.processedSourcesPath.asPath, + actualResponsesPath = parameters.actualResponsesPath.asPath, + processedActualResponsesPath = parameters.processedActualResponsesPath.asPath, + testPath = parameters.testPath.asPath, ) } } diff --git a/src/main/kotlin/de/smartsquare/squit/task/SquitPostTestTask.kt b/src/main/kotlin/de/smartsquare/squit/task/SquitPostTestTask.kt index 7d278fb7..3407547e 100644 --- a/src/main/kotlin/de/smartsquare/squit/task/SquitPostTestTask.kt +++ b/src/main/kotlin/de/smartsquare/squit/task/SquitPostTestTask.kt @@ -1,5 +1,7 @@ package de.smartsquare.squit.task enum class SquitPostTestTask { - DATABASE_SCRIPTS, POST_RUNNERS, POST_RUNNER_SCRIPTS + DATABASE_SCRIPTS, + POST_RUNNERS, + POST_RUNNER_SCRIPTS, } diff --git a/src/main/kotlin/de/smartsquare/squit/task/SquitPreProcessTask.kt b/src/main/kotlin/de/smartsquare/squit/task/SquitPreProcessTask.kt index cfc29468..ec2ca679 100644 --- a/src/main/kotlin/de/smartsquare/squit/task/SquitPreProcessTask.kt +++ b/src/main/kotlin/de/smartsquare/squit/task/SquitPreProcessTask.kt @@ -11,9 +11,11 @@ import de.smartsquare.squit.util.Constants.SOURCES_DIRECTORY import de.smartsquare.squit.util.Constants.SQUIT_DIRECTORY import de.smartsquare.squit.util.asPath import de.smartsquare.squit.util.cut +import de.smartsquare.squit.util.dir import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.Property +import org.gradle.api.provider.Provider import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory @@ -21,62 +23,62 @@ import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction -import org.gradle.util.GradleVersion import org.gradle.workers.WorkAction import org.gradle.workers.WorkParameters import org.gradle.workers.WorkerExecutor import java.nio.file.Files import java.nio.file.Path -import java.nio.file.Paths import javax.inject.Inject /** * Task for pre-processing the available sources like requests, responses, sql scripts and properties. */ @CacheableTask -open class SquitPreProcessTask @Inject constructor(private val workerExecutor: WorkerExecutor) : DefaultTask() { +abstract class SquitPreProcessTask @Inject constructor(private val workerExecutor: WorkerExecutor) : DefaultTask() { /** * The path the sources lie in. */ @get:InputDirectory @get:PathSensitive(PathSensitivity.RELATIVE) - lateinit var sourceDir: Path + abstract val sourceDir: DirectoryProperty /** * The directory to save the results in. */ @get:OutputDirectory - val processedSourcesPath: Path = Paths.get(project.buildDir.path, SQUIT_DIRECTORY, SOURCES_DIRECTORY) + val processedSources = project.layout.buildDirectory.dir(SQUIT_DIRECTORY, SOURCES_DIRECTORY) /** * The tags to filter by (and). */ @get:Input - val tagsAnd = getTags("tags") + getTags("tagsAnd") + val tagsAnd: Provider> = project.provider { + getTags("tags") + getTags("tagsAnd") + } /** * The tags to filter by (or). */ @get:Input - val tagsOr = getTags("tagsOr") + val tagsOr: Provider> = project.provider { getTags("tagsOr") } /** * If all excluded or ignored tests should be run nevertheless. */ @get:Input - val shouldUnexclude by lazy { project.properties.containsKey("unexclude") } + val shouldUnexclude: Provider = project.provider { project.properties.containsKey("unexclude") } /** * The properties of the project parsed into a [Config] object. */ @get:Input - val projectConfig: Config by lazy { + val projectConfig: Provider = project.provider { ConfigValueFactory .fromMap( project.properties .filterKeys { it is String && it.startsWith("squit.") } - .mapKeys { (key, _) -> key.replaceFirst("squit.", "") } + .mapKeys { (key, _) -> key.replaceFirst("squit.", "") }, ) .toConfig() } @@ -91,33 +93,24 @@ open class SquitPreProcessTask @Inject constructor(private val workerExecutor: W */ @TaskAction fun run() { - val index = TestIndexer(projectConfig).index(sourceDir) { filterIndex(it) } + val index = TestIndexer(projectConfig.get()).index(sourceDir.asPath) { filterIndex(it) } - FilesUtils.deleteRecursivelyIfExisting(processedSourcesPath) - Files.createDirectories(processedSourcesPath) + FilesUtils.deleteRecursivelyIfExisting(processedSources.asPath) + Files.createDirectories(processedSources.asPath) - if (GradleVersion.current() >= GradleVersion.version("5.6")) { - val workerQueue = workerExecutor.noIsolation() + val workerQueue = workerExecutor.noIsolation() - index.forEach { test -> - workerQueue.submit(Worker::class.java) { - it.sourceDir.set(sourceDir.toFile()) - it.processedSourcesPath.set(processedSourcesPath.toFile()) - it.test.set(test) - } - } - } else { - index.forEach { test -> - SquitPreProcessRunner.run(sourceDir, processedSourcesPath, test) + index.forEach { test -> + workerQueue.submit(Worker::class.java) { + it.sourceDir.set(sourceDir.get().asFile) + it.processedSourcesPath.set(processedSources.get().asFile) + it.test.set(test) } } } private fun getTags(name: String): Set { - val tagsString = when (project.hasProperty(name)) { - true -> project.property(name) as String? - false -> null - } + val tagsString = if (project.hasProperty(name)) project.property(name)?.toString() else null return tagsString ?.split(",") @@ -129,35 +122,37 @@ open class SquitPreProcessTask @Inject constructor(private val workerExecutor: W private fun filterIndex(input: Pair) = when { isTestExcluded(input.second) -> { - logger.info("Excluding test ${input.first.cut(sourceDir)}") + logger.info("Excluding test ${input.first.cut(sourceDir.asPath)}") false } + !isTestCoveredByTags(input.second) -> { - logger.info("Ignoring test ${input.first.cut(sourceDir)}") + logger.info("Ignoring test ${input.first.cut(sourceDir.asPath)}") false } + else -> true } - private fun isTestExcluded(config: Config): Boolean { - return config.shouldExclude && !shouldUnexclude - } + private fun isTestExcluded(config: Config): Boolean = config.shouldExclude && !shouldUnexclude.get() - private fun isTestCoveredByTags(config: Config): Boolean { - return (tagsAnd.isEmpty() || tagsAnd.all { it in config.tags }) && - (tagsOr.isEmpty() || tagsOr.any { it in config.tags }) - } + private fun isTestCoveredByTags(config: Config): Boolean = ( + tagsAnd.get().isEmpty() || + tagsAnd.get().all { + it in config.tags + } + ) && + (tagsOr.get().isEmpty() || tagsOr.get().any { it in config.tags }) internal abstract class Worker : WorkAction { - - private val sourceDir get() = parameters.sourceDir.asPath - private val processedSourcesPath get() = parameters.processedSourcesPath.asPath - private val test get() = parameters.test.get() - override fun execute() { - SquitPreProcessRunner.run(sourceDir, processedSourcesPath, test) + SquitPreProcessRunner.run( + sourceDir = parameters.sourceDir.asPath, + processedSourcesPath = parameters.processedSourcesPath.asPath, + test = parameters.test.get(), + ) } } diff --git a/src/main/kotlin/de/smartsquare/squit/task/SquitPreTestTask.kt b/src/main/kotlin/de/smartsquare/squit/task/SquitPreTestTask.kt index 63c7502b..9bbed609 100644 --- a/src/main/kotlin/de/smartsquare/squit/task/SquitPreTestTask.kt +++ b/src/main/kotlin/de/smartsquare/squit/task/SquitPreTestTask.kt @@ -1,5 +1,7 @@ package de.smartsquare.squit.task enum class SquitPreTestTask { - DATABASE_SCRIPTS, PRE_RUNNERS, PRE_RUNNER_SCRIPTS + DATABASE_SCRIPTS, + PRE_RUNNERS, + PRE_RUNNER_SCRIPTS, } diff --git a/src/main/kotlin/de/smartsquare/squit/task/SquitRequestTask.kt b/src/main/kotlin/de/smartsquare/squit/task/SquitRequestTask.kt index 417fdd9e..58ddb3a1 100644 --- a/src/main/kotlin/de/smartsquare/squit/task/SquitRequestTask.kt +++ b/src/main/kotlin/de/smartsquare/squit/task/SquitRequestTask.kt @@ -15,6 +15,7 @@ import de.smartsquare.squit.config.preRunners import de.smartsquare.squit.config.preTestTasks import de.smartsquare.squit.db.ConnectionCollection import de.smartsquare.squit.db.executeScript +import de.smartsquare.squit.entity.SquitDatabaseConfiguration import de.smartsquare.squit.entity.SquitMetaInfo import de.smartsquare.squit.entity.SquitResponseInfo import de.smartsquare.squit.interfaces.SquitPostRunner @@ -29,7 +30,9 @@ import de.smartsquare.squit.util.Constants.RAW_DIRECTORY import de.smartsquare.squit.util.Constants.RESPONSES_DIRECTORY import de.smartsquare.squit.util.Constants.SOURCES_DIRECTORY import de.smartsquare.squit.util.Constants.SQUIT_DIRECTORY +import de.smartsquare.squit.util.asPath import de.smartsquare.squit.util.cut +import de.smartsquare.squit.util.dir import de.smartsquare.squit.util.lifecycleOnSameLine import de.smartsquare.squit.util.newLineIfNeeded import groovy.lang.Binding @@ -41,17 +44,20 @@ import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.internal.http.HttpMethod import org.gradle.api.DefaultTask +import org.gradle.api.file.Directory +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property +import org.gradle.api.provider.Provider import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory -import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import java.io.IOException import java.nio.file.Files import java.nio.file.Path -import java.nio.file.Paths import java.sql.Driver -import java.sql.DriverManager import java.sql.SQLException import java.time.LocalDateTime import java.util.concurrent.TimeUnit @@ -60,67 +66,53 @@ import java.util.concurrent.TimeUnit * Task for running requests against the given api. Also capable of running existing sql scripts before and after the * request. */ -open class SquitRequestTask : DefaultTask() { +abstract class SquitRequestTask : DefaultTask() { /** * The jdbc driver classes to use. */ @get:Input - lateinit var jdbcDrivers: List + abstract val jdbcDrivers: ListProperty /** * The timeout in seconds to use for requests. */ - @get:Internal - var timeout = 10L + @get:Input + abstract val requestTimeout: Property /** * If squit should avoid printing anything if all tests pass. */ - @get:Internal - var silent = false + @get:Input + abstract val silent: Property /** * The class name of the jdbc [Driver] to use. */ @get:Input - val jdbcDriverClassNames by lazy { - jdbcDrivers - .map { it.trim() } - .filter { it.isNotBlank() } - .let { - logger.info("Using $it for jdbc connections.") - - it - } - } + val jdbcDriverClassNames: Provider> + get() = jdbcDrivers.map { driver -> driver.map(String::trim).filter(String::isNotBlank) } /** * The directory of the test sources. */ @get:InputDirectory - val processedSourcesPath: Path = Paths.get( - project.buildDir.path, - SQUIT_DIRECTORY, - SOURCES_DIRECTORY - ) + @get:PathSensitive(PathSensitivity.RELATIVE) + val processedSourcesDir: Provider = project.layout.buildDirectory + .dir(SQUIT_DIRECTORY, SOURCES_DIRECTORY) /** * The directory to save the results in. */ @get:OutputDirectory - val actualResponsesPath: Path = Paths.get( - project.buildDir.path, - SQUIT_DIRECTORY, - RESPONSES_DIRECTORY, - RAW_DIRECTORY - ) + val actualResponsesDir: Provider = project.layout.buildDirectory + .dir(SQUIT_DIRECTORY, RESPONSES_DIRECTORY, RAW_DIRECTORY) private val okHttpClient by lazy { OkHttpClient.Builder() - .connectTimeout(timeout, TimeUnit.SECONDS) - .writeTimeout(timeout, TimeUnit.SECONDS) - .readTimeout(timeout, TimeUnit.SECONDS) + .connectTimeout(requestTimeout.get(), TimeUnit.SECONDS) + .writeTimeout(requestTimeout.get(), TimeUnit.SECONDS) + .readTimeout(requestTimeout.get(), TimeUnit.SECONDS) .build() } @@ -137,27 +129,26 @@ open class SquitRequestTask : DefaultTask() { /** * Runs the task. */ - @Suppress("unused") @TaskAction fun run() { - jdbcDriverClassNames.forEach { - DriverManager.registerDriver(Class.forName(it).getConstructor().newInstance() as Driver) - } + jdbcDriverClassNames.get() + .onEach { logger.info("Using $it for jdbc connections.") } + .forEach { Class.forName(it) } - FilesUtils.deleteRecursivelyIfExisting(actualResponsesPath) - Files.createDirectories(actualResponsesPath) + FilesUtils.deleteRecursivelyIfExisting(actualResponsesDir.asPath) + Files.createDirectories(actualResponsesDir.asPath) dbConnections.use { - FilesUtils.getLeafDirectories(processedSourcesPath).forEachIndexed { index, testDirectoryPath -> - if (!silent) { + FilesUtils.getLeafDirectories(processedSourcesDir.asPath).forEachIndexed { index, testDirectoryPath -> + if (!silent.get()) { logger.lifecycleOnSameLine( "Running test ${index + 1}", - project.gradle.startParameter.consoleOutput + project.gradle.startParameter.consoleOutput, ) } val resultResponsePath = Files.createDirectories( - actualResponsesPath.resolve(testDirectoryPath.cut(processedSourcesPath)) + actualResponsesDir.asPath.resolve(testDirectoryPath.cut(processedSourcesDir.asPath)), ) val errorFile = testDirectoryPath.resolve(ERROR) @@ -204,7 +195,7 @@ open class SquitRequestTask : DefaultTask() { testDirectoryPath: Path, resultResponsePath: Path, requestPath: Path?, - config: Config + config: Config, ) { val resultResponseFilePath = resultResponsePath.resolve(MediaTypeFactory.actualResponse(config.mediaType)) @@ -223,21 +214,21 @@ open class SquitRequestTask : DefaultTask() { Files.write(resultResponseInfoFilePath, responseInfo.toJson().toByteArray()) if (!apiResponse.isSuccessful) { - if (!silent) logger.newLineIfNeeded() + if (!silent.get()) logger.newLineIfNeeded() logger.info( - "Unsuccessful request for test ${testDirectoryPath.cut(processedSourcesPath)} " + - "(status code: ${apiResponse.code})" + "Unsuccessful request for test ${testDirectoryPath.cut(processedSourcesDir.asPath)} " + + "(status code: ${apiResponse.code})", ) } else if ( mediaType?.type != config.mediaType.type || mediaType.subtype != config.mediaType.subtype ) { - if (!silent) logger.newLineIfNeeded() + if (!silent.get()) logger.newLineIfNeeded() logger.info( - "Unexpected Media type $mediaType for test ${testDirectoryPath.cut(processedSourcesPath)}. " + - "Expected ${config.mediaType}" + "Unexpected Media type $mediaType for test " + + "${testDirectoryPath.cut(processedSourcesDir.asPath)}. Expected ${config.mediaType}", ) } } catch (error: IOException) { @@ -259,12 +250,7 @@ open class SquitRequestTask : DefaultTask() { private fun executePreDatabaseScripts(config: Config, testDirectoryPath: Path) { config.databaseConfigurations.forEach { - executeScriptIfExisting( - testDirectoryPath.resolve("${it.name}_pre.sql"), - it.jdbcAddress, - it.username, - it.password - ) + executeScriptIfExisting(it, testDirectoryPath.resolve("${it.name}_pre.sql")) } } @@ -298,12 +284,7 @@ open class SquitRequestTask : DefaultTask() { private fun executePostDatabaseScripts(config: Config, testDirectoryPath: Path) { config.databaseConfigurations.forEach { - executeScriptIfExisting( - testDirectoryPath.resolve("${it.name}_post.sql"), - it.jdbcAddress, - it.username, - it.password - ) + executeScriptIfExisting(it, testDirectoryPath.resolve("${it.name}_post.sql")) } } @@ -333,30 +314,27 @@ open class SquitRequestTask : DefaultTask() { .headers(config.headers.toHeaders()) .method(config.method, requestBody) .url(config.endpoint) - .build() + .build(), ) } - private fun executeScriptIfExisting( - path: Path, - jdbc: String, - username: String, - password: String - ) = if (Files.exists(path)) { - try { - dbConnections.createOrGet(jdbc, username, password).executeScript(path) + private fun executeScriptIfExisting(dbConfiguration: SquitDatabaseConfiguration, path: Path): Boolean { + if (!Files.exists(path)) return true + + return try { + dbConnections + .createOrGet(dbConfiguration.jdbcAddress, dbConfiguration.username, dbConfiguration.password) + .executeScript(path) true } catch (error: SQLException) { logger.newLineIfNeeded() logger.warn( "Could not run database script ${path.fileName} for test " + - "${path.parent.cut(processedSourcesPath)} (${error.toString().trim()})" + "${path.parent.cut(processedSourcesDir.asPath)} (${error.toString().trim()})", ) false } - } else { - true } } diff --git a/src/main/kotlin/de/smartsquare/squit/task/SquitTestTask.kt b/src/main/kotlin/de/smartsquare/squit/task/SquitTestTask.kt index 4e5ed426..9825f4a7 100644 --- a/src/main/kotlin/de/smartsquare/squit/task/SquitTestTask.kt +++ b/src/main/kotlin/de/smartsquare/squit/task/SquitTestTask.kt @@ -23,10 +23,18 @@ import de.smartsquare.squit.util.Constants.RAW_DIRECTORY import de.smartsquare.squit.util.Constants.RESPONSES_DIRECTORY import de.smartsquare.squit.util.Constants.SOURCES_DIRECTORY import de.smartsquare.squit.util.Constants.SQUIT_DIRECTORY +import de.smartsquare.squit.util.asPath import de.smartsquare.squit.util.countTestResults import de.smartsquare.squit.util.cut +import de.smartsquare.squit.util.dir +import de.smartsquare.squit.util.file import org.gradle.api.DefaultTask import org.gradle.api.GradleException +import org.gradle.api.file.Directory +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.FileTree +import org.gradle.api.provider.Property +import org.gradle.api.provider.Provider import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory @@ -41,59 +49,52 @@ import org.gradle.api.tasks.TaskAction import java.nio.charset.Charset import java.nio.file.Files import java.nio.file.Path -import java.nio.file.Paths -import kotlin.streams.toList /** * Task for comparing the actual responses to the expected responses and generating a report. */ @CacheableTask -open class SquitTestTask : DefaultTask() { +abstract class SquitTestTask : DefaultTask() { /** * The path to save reports and possible failures in. */ @get:OutputDirectory - lateinit var reportDir: Path + abstract val reportDir: DirectoryProperty /** * If squit should avoid printing anything if all tests pass. */ @get:Internal - var silent = false + abstract val silent: Property /** * If failures should be ignored. * In that case the task passes, even if tests have failed. */ @get:Input - var ignoreFailures = false + abstract val ignoreFailures: Property /** * Configuration class for various properties of the media types. */ @get:Nested - lateinit var mediaTypeConfig: MediaTypeConfig + abstract val mediaTypeConfig: Property /** * The directory of the test sources. */ @get:InputDirectory @get:PathSensitive(PathSensitivity.RELATIVE) - val processedSourcesPath: Path = Paths.get( - project.buildDir.path, - SQUIT_DIRECTORY, SOURCES_DIRECTORY - ) + val processedSourcesDir = project.layout.buildDirectory.dir(SQUIT_DIRECTORY, SOURCES_DIRECTORY) /** * The directory of the previously (processed) requested responses. */ @get:InputDirectory @get:PathSensitive(PathSensitivity.RELATIVE) - val processedResponsesPath: Path = Paths.get( - project.buildDir.path, - SQUIT_DIRECTORY, RESPONSES_DIRECTORY, PROCESSED_DIRECTORY - ) + val processedResponsesDir = project.layout.buildDirectory + .dir(SQUIT_DIRECTORY, RESPONSES_DIRECTORY, PROCESSED_DIRECTORY) /** * Collection of meta.json files for up-to-date checking. @@ -102,41 +103,30 @@ open class SquitTestTask : DefaultTask() { @get:Optional @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) - val metaPaths: List by lazy { - val rawDirectoryPath = Paths.get(project.buildDir.path, SQUIT_DIRECTORY, RESPONSES_DIRECTORY, RAW_DIRECTORY) - - if (Files.exists(rawDirectoryPath)) { - Files.walk(rawDirectoryPath).use { stream -> - stream.filter { Files.isRegularFile(it) && it.fileName.toString() == META }.toList() - } - } else { - emptyList() - } - } + val metaFiles: Provider = project.layout.buildDirectory + .dir(SQUIT_DIRECTORY, RESPONSES_DIRECTORY, RAW_DIRECTORY) + .map { dir -> dir.asFileTree.matching { tree -> tree.include("**/$META") } } /** * The directory to generate the xml report file into. */ @get:OutputFile - val xmlReportFilePath: Path by lazy { - reportDir.resolve("xml").resolve("index.xml") - } + val xmlReportFile + get() = reportDir.file("xml", "index.xml") /** * The directory to generate the xml report file into. */ @get:OutputDirectory - val htmlReportDirectoryPath: Path by lazy { - reportDir.resolve("html") - } + val htmlReportDir: Provider + get() = reportDir.dir("html") /** * The directory to copy failed tests into. */ @get:OutputDirectory - val failureResultDirectory: Path by lazy { - reportDir.resolve("failures") - } + val failureReportDir: Provider + get() = reportDir.dir("failures") private var nextResultId = 0L @@ -148,11 +138,10 @@ open class SquitTestTask : DefaultTask() { /** * Runs the task. */ - @Suppress("unused") @TaskAction fun run() { - FilesUtils.deleteRecursivelyIfExisting(reportDir) - Files.createDirectories(processedSourcesPath) + FilesUtils.deleteRecursivelyIfExisting(reportDir.asPath) + Files.createDirectories(processedSourcesDir.asPath) val results = processTests() @@ -162,25 +151,27 @@ open class SquitTestTask : DefaultTask() { val (successfulTests, failedTests, ignoredTests) = results.countTestResults() - if (!silent) { + if (!silent.get()) { val totalText = if (results.size == 1) "One test ran." else "${results.size} tests ran." val ignoredText = if (ignoredTests > 0) " ($ignoredTests ignored)" else "" println("$totalText\n$successfulTests successful and $failedTests failed$ignoredText.") println() - println("XML report: file://$xmlReportFilePath") - println("HTML report: file://${htmlReportDirectoryPath.resolve("index.html")}") + println("XML report: file://${xmlReportFile.asPath}") + println("HTML report: file://${htmlReportDir.asPath.resolve("index.html")}") } - if (failedTests > 0 && !ignoreFailures) throw GradleException("Failing tests.") + if (failedTests > 0 && !ignoreFailures.get()) throw GradleException("Failing tests.") } private fun processTests(): List { val resultList = mutableListOf() - FilesUtils.getLeafDirectories(processedResponsesPath).forEach { actualResponsePath -> + FilesUtils.getLeafDirectories(processedResponsesDir.asPath).forEach { actualResponsePath -> val configPath = FilesUtils.validateExistence( - processedSourcesPath.resolve(actualResponsePath.cut(processedResponsesPath)).resolve(CONFIG) + processedSourcesDir.asPath + .resolve(actualResponsePath.cut(processedResponsesDir.asPath)) + .resolve(CONFIG), ) val config = ConfigFactory.parseFile(configPath.toFile()) @@ -192,7 +183,9 @@ open class SquitTestTask : DefaultTask() { resultList += if (Files.exists(errorFile)) { constructResult( FilesUtils.readAllBytes(errorFile).toString(Charset.defaultCharset()), - expectedResponseInfo, actualResponsePath, config + expectedResponseInfo, + actualResponsePath, + config, ) } else { val bodyDiff = createBodyDifference(actualResponsePath, config) @@ -211,13 +204,13 @@ open class SquitTestTask : DefaultTask() { private fun createResponseInfoDifference( actualResponsePath: Path, - expectedResponseInfo: SquitResponseInfo + expectedResponseInfo: SquitResponseInfo, ): String { if (!expectedResponseInfo.isDefault) { - val contextPath = actualResponsePath.parent.parent.cut(processedResponsesPath) + val contextPath = actualResponsePath.parent.parent.cut(processedResponsesDir.asPath) val suitePath = actualResponsePath.parent.fileName val path: Path = contextPath.resolve(suitePath) - val squitBuildDirectoryPath = Paths.get(project.buildDir.path, SQUIT_DIRECTORY) + val squitBuildDirectoryPath = project.layout.buildDirectory.asPath.resolve(SQUIT_DIRECTORY) val testDirectoryPath = actualResponsePath.fileName val fullPath = path.resolve(testDirectoryPath) val resolvedPath = squitBuildDirectoryPath @@ -226,7 +219,7 @@ open class SquitTestTask : DefaultTask() { .resolve(fullPath) val actualResponseInfoPath = FilesUtils.validateExistence( - resolvedPath.resolve(ACTUAL_RESPONSE_INFO) + resolvedPath.resolve(ACTUAL_RESPONSE_INFO), ) val actualResponse = FilesUtils.readAllBytes(actualResponseInfoPath).toString(Charset.defaultCharset()) @@ -239,43 +232,47 @@ open class SquitTestTask : DefaultTask() { private fun createBodyDifference(actualResponsePath: Path, config: Config): String { val actualResponseFilePath = FilesUtils.validateExistence( - actualResponsePath.resolve(MediaTypeFactory.actualResponse(config.mediaType)) + actualResponsePath.resolve(MediaTypeFactory.actualResponse(config.mediaType)), ) val expectedResponseFilePath = FilesUtils.validateExistence( - processedSourcesPath - .resolve(actualResponsePath.cut(processedResponsesPath)) - .resolve(MediaTypeFactory.expectedResponse(config.mediaType)) + processedSourcesDir.asPath + .resolve(actualResponsePath.cut(processedResponsesDir.asPath)) + .resolve(MediaTypeFactory.expectedResponse(config.mediaType)), ) val expectedResponse = FilesUtils.readAllBytes(expectedResponseFilePath) val actualResponse = FilesUtils.readAllBytes(actualResponseFilePath) - return MediaTypeFactory.differ(config.mediaType, mediaTypeConfig) + return MediaTypeFactory.differ(config.mediaType, mediaTypeConfig.get()) .diff(expectedResponse, actualResponse) } private fun writeXmlReport(result: List) { - Files.createDirectories(xmlReportFilePath.parent) + Files.createDirectories(xmlReportFile.asPath.parent) - XmlReportWriter().writeReport(result, xmlReportFilePath) + XmlReportWriter().writeReport(result, xmlReportFile.asPath) } private fun writeHtmlReport(result: List) { - Files.createDirectories(htmlReportDirectoryPath) + Files.createDirectories(htmlReportDir.asPath) - HtmlReportWriter(logger).writeReport(result, htmlReportDirectoryPath, mediaTypeConfig) + HtmlReportWriter(logger).writeReport(result, htmlReportDir.asPath, mediaTypeConfig.get()) } private fun copyFailures(result: List) { - FilesUtils.deleteRecursivelyIfExisting(failureResultDirectory) - Files.createDirectories(failureResultDirectory) + FilesUtils.deleteRecursivelyIfExisting(failureReportDir.asPath) + Files.createDirectories(failureReportDir.asPath) result.filterNot { it.isSuccess }.forEach { - val resultDirectoryPath = Files.createDirectories(failureResultDirectory.resolve(it.fullPath)) + val resultDirectoryPath = Files.createDirectories(failureReportDir.asPath.resolve(it.fullPath)) + + val testProcessedSourcesPath = FilesUtils + .validateExistence(processedSourcesDir.asPath.resolve(it.fullPath)) + + val testActualResponsesPath = FilesUtils + .validateExistence(processedResponsesDir.asPath.resolve(it.fullPath)) - val testProcessedSourcesPath = FilesUtils.validateExistence(processedSourcesPath.resolve(it.fullPath)) - val testActualResponsesPath = FilesUtils.validateExistence(processedResponsesPath.resolve(it.fullPath)) val testDifferenceFile = Files.createFile(resultDirectoryPath.resolve(DIFF)) FilesUtils.copyFilesFromDirectory(testProcessedSourcesPath, resultDirectoryPath) @@ -289,10 +286,10 @@ open class SquitTestTask : DefaultTask() { responseInfo: SquitResponseInfo, actualResponsePath: Path, config: Config, - isIgnored: Boolean = false + isIgnored: Boolean = false, ): SquitResult { - val squitBuildDirectoryPath = Paths.get(project.buildDir.path, SQUIT_DIRECTORY) - val contextPath = actualResponsePath.parent.parent.cut(processedResponsesPath) + val squitBuildDirectoryPath = project.layout.buildDirectory.dir(SQUIT_DIRECTORY).asPath + val contextPath = actualResponsePath.parent.parent.cut(processedResponsesDir.asPath) val suitePath = actualResponsePath.parent.fileName val testDirectoryPath = actualResponsePath.fileName val id = nextResultId++ @@ -301,13 +298,13 @@ open class SquitTestTask : DefaultTask() { true -> SquitResult( id, differences, responseInfo, isIgnored, config.mediaType, config.title, contextPath, suitePath, - testDirectoryPath, squitBuildDirectoryPath + testDirectoryPath, squitBuildDirectoryPath, ) false -> SquitResult( id, "", responseInfo, isIgnored, config.mediaType, config.title, contextPath, suitePath, - testDirectoryPath, squitBuildDirectoryPath + testDirectoryPath, squitBuildDirectoryPath, ) } } diff --git a/src/main/kotlin/de/smartsquare/squit/util/UtilExtensions.kt b/src/main/kotlin/de/smartsquare/squit/util/UtilExtensions.kt index 981e9861..fcbb8e55 100644 --- a/src/main/kotlin/de/smartsquare/squit/util/UtilExtensions.kt +++ b/src/main/kotlin/de/smartsquare/squit/util/UtilExtensions.kt @@ -7,7 +7,11 @@ import de.smartsquare.squit.entity.SquitOutputFormat import de.smartsquare.squit.entity.SquitResult import org.dom4j.io.OutputFormat import org.dom4j.io.XMLWriter +import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.FileSystemLocation +import org.gradle.api.file.RegularFile +import org.gradle.api.provider.Provider import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths @@ -72,11 +76,28 @@ fun String.cleanSqlString() = this .replace("\uFEFF", "") // This is a weird unicode blank character, present in some sql files. .trim() +/** + * Resolves one or more directory parts. + */ +fun DirectoryProperty.dir(first: String, vararg more: String): Provider = + dir(Paths.get(first, *more).toString()) + +/** + * Resolves one or more file parts. + */ +fun DirectoryProperty.file(first: String, vararg more: String): Provider = + file(Paths.get(first, *more).toString()) + /** * Returns this as a [Path]. */ val DirectoryProperty.asPath: Path get() = asFile.get().toPath() +/** + * Returns this as a [Path]. + */ +val Provider.asPath: Path get() = get().asFile.toPath() + /** * Iterate the list of [SquitResult]s and returns a [Triple] of successful, failed and ignored tests. */ diff --git a/src/test/kotlin/de/smartsquare/squit/GradleCompatibilityTest.kt b/src/test/kotlin/de/smartsquare/squit/GradleCompatibilityTest.kt index d8367ff3..8c027c07 100644 --- a/src/test/kotlin/de/smartsquare/squit/GradleCompatibilityTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/GradleCompatibilityTest.kt @@ -23,22 +23,16 @@ class GradleCompatibilityTest { @JvmStatic fun provideVersions(): Stream { - val result = mutableListOf( - Arguments.of(GradleVersion.current()) - ) - - // These older Gradle Versions do not work on Java 17+. - if (JavaVersion.current() <= JavaVersion.VERSION_16) { - result += listOf( - Arguments.of(GradleVersion.version("7.0")) - ) + val result = mutableListOf(Arguments.of(GradleVersion.current())) + + // This older Gradle version does not work on Java 20+. + if (JavaVersion.current() < JavaVersion.VERSION_20) { + result += Arguments.of(GradleVersion.version("8.0.2")) } - // These older Gradle Versions do not work on Java 16+. - if (JavaVersion.current() <= JavaVersion.VERSION_15) { - result += listOf( - Arguments.of(GradleVersion.version("6.8")) - ) + // This older Gradle version does not work on Java 21+. + if (JavaVersion.current() < JavaVersion.VERSION_21) { + result += Arguments.of(GradleVersion.version("7.3.2")) } return result.stream() @@ -69,8 +63,9 @@ class GradleCompatibilityTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "--stacktrace" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", ) val result = gradleRunner(project, arguments, gradleVersion).build() @@ -81,8 +76,8 @@ class GradleCompatibilityTest { @Test @DisabledForJreRange(min = JRE.JAVA_16) fun `outdated version`() { - val result = gradleRunner(project, emptyList(), GradleVersion.version("6.7")).buildAndFail() + val result = gradleRunner(project, emptyList(), GradleVersion.version("7.2")).buildAndFail() - result.output shouldContain "Minimum supported Gradle version is 6.8. Current version is 6.7." + result.output shouldContain "Minimum supported Gradle version is 7.3. Current version is 7.2." } } diff --git a/src/test/kotlin/de/smartsquare/squit/TestUtils.kt b/src/test/kotlin/de/smartsquare/squit/TestUtils.kt index e1fa7c24..f0a67ca7 100644 --- a/src/test/kotlin/de/smartsquare/squit/TestUtils.kt +++ b/src/test/kotlin/de/smartsquare/squit/TestUtils.kt @@ -6,23 +6,19 @@ import org.gradle.util.GradleVersion import java.io.File import java.nio.file.Files import java.nio.file.Path -import java.nio.file.StandardCopyOption +import org.h2.Driver as H2Driver /** * Utility class for methods which cannot be a extension function. */ object TestUtils { - private val DB_FILTER = { it: Path -> - Files.isRegularFile(it) && it.fileName.toString().endsWith(".db") - } - /** - * Deletes all database files found in the passed [path] directory. + * Deletes all database files found in the given [path] directory. */ - fun deleteDatabaseFiles(path: Path) = Files.newDirectoryStream(path, DB_FILTER).use { files -> - files.forEach { Files.delete(it) } - } + fun deleteDatabaseFiles(path: Path) = Files + .newDirectoryStream(path) { Files.isRegularFile(it) && it.fileName.toString().endsWith(".db") } + .use { files -> files.forEach { Files.delete(it) } } /** * Returns the [Path] of the resource with the given [name]… @@ -35,41 +31,23 @@ object TestUtils { */ fun GradleRunner.withExtendedPluginClasspath(): GradleRunner { val classpath = PluginUnderTestMetadataReading.readImplementationClasspath() - .plus(File(org.h2.Driver::class.java.protectionDomain.codeSource.location.toURI())) + .plus(File(H2Driver::class.java.protectionDomain.codeSource.location.toURI())) .plus(File(XmlPreProcessor::class.java.protectionDomain.codeSource.location.toURI())) .plus(File(XmlPostProcessor::class.java.protectionDomain.codeSource.location.toURI())) return withPluginClasspath(classpath) } -/** - * Configures the GradleRunner to run with the jacoco agent. - */ -fun GradleRunner.withJacoco(): GradleRunner { - val properties = this.javaClass.classLoader.getResource("testkit-gradle.properties") - - if (properties != null) { - Files.copy( - File(properties.toURI()).toPath(), - projectDir.toPath().resolve("gradle.properties"), - StandardCopyOption.REPLACE_EXISTING - ) - } - - return this -} - /** * Creates a [GradleRunner] with the given [project], [arguments] and an optional [version]. * * This also applies the following default arguments: "clean --stacktrace". */ -fun gradleRunner(project: Path, arguments: List, version: GradleVersion? = null): GradleRunner { - return GradleRunner.create() +fun gradleRunner(project: Path, arguments: List, version: GradleVersion? = null): GradleRunner = + GradleRunner.create() .withArguments(listOf("clean") + arguments + "--stacktrace") .apply { if (version !== null) withGradleVersion(version.version) } .withProjectDir(project.toFile()) .withExtendedPluginClasspath() + .withDebug(true) .forwardOutput() - .withJacoco() -} diff --git a/src/test/kotlin/de/smartsquare/squit/config/ConfigExtensionsTest.kt b/src/test/kotlin/de/smartsquare/squit/config/ConfigExtensionsTest.kt index 7f87a861..a659eb80 100644 --- a/src/test/kotlin/de/smartsquare/squit/config/ConfigExtensionsTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/config/ConfigExtensionsTest.kt @@ -70,8 +70,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "method" to "GET" - ) + "method" to "GET", + ), ) config.method shouldBeEqualTo "GET" @@ -89,8 +89,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "testDir" to Paths.get(".").toString() - ) + "testDir" to Paths.get(".").toString(), + ), ) val call = { config.validate() } @@ -103,8 +103,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "testDir" to Paths.get("does_not_exist").toString() - ) + "testDir" to Paths.get("does_not_exist").toString(), + ), ) val call = { config.validate() } @@ -117,8 +117,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preProcessors" to listOf("java.lang.String") - ) + "preProcessors" to listOf("java.lang.String"), + ), ) val call = { config.validate() } @@ -131,8 +131,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preProcessors" to listOf("not.existing") - ) + "preProcessors" to listOf("not.existing"), + ), ) val call = { config.validate() } @@ -145,8 +145,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preProcessorScripts" to listOf(testProject.resolve("build.gradle").toString()) - ) + "preProcessorScripts" to listOf(testProject.resolve("build.gradle").toString()), + ), ) val call = { config.validate() } @@ -160,8 +160,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preProcessorScripts" to listOf(notExistingFilePath.toString()) - ) + "preProcessorScripts" to listOf(notExistingFilePath.toString()), + ), ) val call = { config.validate() } @@ -174,8 +174,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postProcessors" to listOf("java.lang.String") - ) + "postProcessors" to listOf("java.lang.String"), + ), ) val call = { config.validate() } @@ -188,8 +188,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postProcessors" to listOf("not.existing") - ) + "postProcessors" to listOf("not.existing"), + ), ) val call = { config.validate() } @@ -202,8 +202,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postProcessorScripts" to listOf(testProject.resolve("build.gradle").toString()) - ) + "postProcessorScripts" to listOf(testProject.resolve("build.gradle").toString()), + ), ) val call = { config.validate() } @@ -217,8 +217,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postProcessorScripts" to listOf(notExistingFilePath.toString()) - ) + "postProcessorScripts" to listOf(notExistingFilePath.toString()), + ), ) val call = { config.validate() } @@ -231,8 +231,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preRunners" to listOf("java.lang.String") - ) + "preRunners" to listOf("java.lang.String"), + ), ) val call = { config.validate() } @@ -245,8 +245,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preRunners" to listOf("not.existing") - ) + "preRunners" to listOf("not.existing"), + ), ) val call = { config.validate() } @@ -259,8 +259,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preRunnerScripts" to listOf(testProject.resolve("build.gradle").toString()) - ) + "preRunnerScripts" to listOf(testProject.resolve("build.gradle").toString()), + ), ) val call = { config.validate() } @@ -274,8 +274,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "preRunnerScripts" to listOf(notExistingFilePath.toString()) - ) + "preRunnerScripts" to listOf(notExistingFilePath.toString()), + ), ) val call = { config.validate() } @@ -288,8 +288,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postRunners" to listOf("java.lang.String") - ) + "postRunners" to listOf("java.lang.String"), + ), ) val call = { config.validate() } @@ -302,8 +302,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postRunners" to listOf("not.existing") - ) + "postRunners" to listOf("not.existing"), + ), ) val call = { config.validate() } @@ -316,8 +316,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postRunnerScripts" to listOf(testProject.resolve("build.gradle").toString()) - ) + "postRunnerScripts" to listOf(testProject.resolve("build.gradle").toString()), + ), ) val call = { config.validate() } @@ -331,8 +331,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "postRunnerScripts" to listOf(notExistingFilePath.toString()) - ) + "postRunnerScripts" to listOf(notExistingFilePath.toString()), + ), ) val call = { config.validate() } @@ -345,8 +345,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "tags" to listOf("a", "b") - ) + "tags" to listOf("a", "b"), + ), ) val call = { config.validate() } @@ -359,8 +359,8 @@ class ConfigExtensionsTest { val config = ConfigFactory.parseMap( mapOf( "endpoint" to "https://example.com", - "tags" to listOf("a", "") - ) + "tags" to listOf("a", ""), + ), ) val call = { config.validate() } @@ -378,10 +378,10 @@ class ConfigExtensionsTest { "name" to "test1", "jdbc" to "test2", "username" to "test3", - "password" to "test4" - ) - ) - ) + "password" to "test4", + ), + ), + ), ) val call = { config.validate() } @@ -399,10 +399,10 @@ class ConfigExtensionsTest { "name" to "", "jdbc" to "test2", "username" to "test3", - "password" to "test4" - ) - ) - ) + "password" to "test4", + ), + ), + ), ) val call = { config.validate() } @@ -420,10 +420,10 @@ class ConfigExtensionsTest { "name" to "test1", "jdbc" to "", "username" to "test3", - "password" to "test4" - ) - ) - ) + "password" to "test4", + ), + ), + ), ) val call = { config.validate() } @@ -441,10 +441,10 @@ class ConfigExtensionsTest { "name" to "test1", "jdbc" to "test2", "username" to "", - "password" to "test4" - ) - ) - ) + "password" to "test4", + ), + ), + ), ) val call = { config.validate() } @@ -462,10 +462,10 @@ class ConfigExtensionsTest { "name" to "test1", "jdbc" to "test2", "username" to "test3", - "password" to "" - ) - ) - ) + "password" to "", + ), + ), + ), ) val call = { config.validate() } @@ -480,9 +480,9 @@ class ConfigExtensionsTest { "endpoint" to "https://example.com", "headers" to mapOf( "abc" to "def", - "ghi" to "jkl" - ) - ) + "ghi" to "jkl", + ), + ), ) config.headers shouldContain ("abc" to "def") @@ -500,7 +500,7 @@ class ConfigExtensionsTest { "endpoint" to "https://example.com", "preTestTasks" to listOf("DATABASE_SCRIPTS", "PRE_RUNNERS", "PRE_RUNNER_SCRIPTS"), "postTestTasks" to emptyList(), - ) + ), ) val call = { config.validate() } @@ -513,7 +513,7 @@ class ConfigExtensionsTest { mapOf( "endpoint" to "https://example.com", "preTestTasks" to listOf("NotExistingTask"), - ) + ), ) val call = { config.validate() } @@ -528,7 +528,7 @@ class ConfigExtensionsTest { mapOf( "endpoint" to "https://example.com", "postTestTasks" to listOf("NotExistingTask"), - ) + ), ) val call = { config.validate() } diff --git a/src/test/kotlin/de/smartsquare/squit/config/TestIndexerTest.kt b/src/test/kotlin/de/smartsquare/squit/config/TestIndexerTest.kt index bbd0deb5..cce88552 100644 --- a/src/test/kotlin/de/smartsquare/squit/config/TestIndexerTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/config/TestIndexerTest.kt @@ -19,9 +19,9 @@ class TestIndexerTest { ConfigFactory.parseMap( mapOf( "rootDir" to "$testProjectRoot", - "endpointPlaceholder" to "https://example.com" - ) - ) + "endpointPlaceholder" to "https://example.com", + ), + ), ) @Test diff --git a/src/test/kotlin/de/smartsquare/squit/db/ConnectionCollectionTest.kt b/src/test/kotlin/de/smartsquare/squit/db/ConnectionCollectionTest.kt index d5b0104b..87705e6d 100644 --- a/src/test/kotlin/de/smartsquare/squit/db/ConnectionCollectionTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/db/ConnectionCollectionTest.kt @@ -3,7 +3,9 @@ package de.smartsquare.squit.db import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue +import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.h2.Driver as H2Driver class ConnectionCollectionTest { @@ -11,6 +13,11 @@ class ConnectionCollectionTest { private val username = "test" private val password = "test" + @BeforeEach + fun setUp() { + H2Driver.load() + } + @Test fun `creating a new db connection`() { val connectionCollection = ConnectionCollection() diff --git a/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTest.kt b/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTest.kt index afa34a0b..1797dc69 100644 --- a/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTest.kt @@ -1,9 +1,9 @@ package de.smartsquare.squit.entity -import java.nio.file.Paths import okhttp3.MediaType.Companion.toMediaType import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test +import java.nio.file.Paths class SquitResultTest { @@ -13,7 +13,7 @@ class SquitResultTest { fun `cutting the first path element of result with full path`() { val subject = SquitResult( 0, "", SquitResponseInfo(), false, mediaType, "", - Paths.get("a"), Paths.get("b"), Paths.get("c"), Paths.get("x") + Paths.get("a"), Paths.get("b"), Paths.get("c"), Paths.get("x"), ) val result = subject.cutFirstPathElement() @@ -25,7 +25,7 @@ class SquitResultTest { fun `cutting the first path element of a result without context path`() { val subject = SquitResult( 0, "", SquitResponseInfo(), false, mediaType, "", - Paths.get(""), Paths.get("b"), Paths.get("c"), Paths.get("x") + Paths.get(""), Paths.get("b"), Paths.get("c"), Paths.get("x"), ) val result = subject.cutFirstPathElement() @@ -37,7 +37,7 @@ class SquitResultTest { fun `cutting the first path element of a result with only testDirectoryPath`() { val subject = SquitResult( 0, "", SquitResponseInfo(), false, mediaType, "", - Paths.get(""), Paths.get(""), Paths.get("c"), Paths.get("x") + Paths.get(""), Paths.get(""), Paths.get("c"), Paths.get("x"), ) val result = subject.cutFirstPathElement() @@ -49,7 +49,7 @@ class SquitResultTest { fun `cutting the first path element of a result with empty path`() { val subject = SquitResult( 0, "", SquitResponseInfo(), false, mediaType, "", - Paths.get(""), Paths.get(""), Paths.get(""), Paths.get("x") + Paths.get(""), Paths.get(""), Paths.get(""), Paths.get("x"), ) val result = subject.cutFirstPathElement() diff --git a/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTreeTest.kt b/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTreeTest.kt index 5b531c1c..8caad984 100644 --- a/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTreeTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/entity/SquitResultTreeTest.kt @@ -1,7 +1,5 @@ package de.smartsquare.squit.entity -import java.nio.file.Path -import java.nio.file.Paths import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType import org.amshove.kluent.shouldBe @@ -9,6 +7,8 @@ import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.junit.jupiter.api.Test +import java.nio.file.Path +import java.nio.file.Paths class SquitResultTreeTest { @@ -19,7 +19,7 @@ class SquitResultTreeTest { constructTestSquitResult(Paths.get("a"), Paths.get("b"), Paths.get("c").resolve("c")), constructTestSquitResult(Paths.get("a"), Paths.get("b"), Paths.get("d"), isIgnored = true), constructTestSquitResult(Paths.get("a"), Paths.get("c"), Paths.get(""), result = "xyz"), - constructTestSquitResult(Paths.get("x"), Paths.get("y").resolve("z"), Paths.get("x")) + constructTestSquitResult(Paths.get("x"), Paths.get("y").resolve("z"), Paths.get("x")), ) val resultTrees = SquitResultTree.fromList(resultList) @@ -39,15 +39,16 @@ class SquitResultTreeTest { resultTrees.last().children.first().children.first().children.first().isSuccess.shouldBeTrue() } + @Suppress("LongParameterList") private fun constructTestSquitResult( contextPath: Path, suitePath: Path, testDirectoryPath: Path, mediaType: MediaType = "application/xml".toMediaType(), result: String = "", - isIgnored: Boolean = false + isIgnored: Boolean = false, ) = SquitResult( 0, result, SquitResponseInfo(), isIgnored, mediaType, "", - contextPath, suitePath, testDirectoryPath, Paths.get("") + contextPath, suitePath, testDirectoryPath, Paths.get(""), ) } diff --git a/src/test/kotlin/de/smartsquare/squit/entity/SquitTestTest.kt b/src/test/kotlin/de/smartsquare/squit/entity/SquitTestTest.kt index 6d20718c..9588e54d 100644 --- a/src/test/kotlin/de/smartsquare/squit/entity/SquitTestTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/entity/SquitTestTest.kt @@ -1,14 +1,14 @@ package de.smartsquare.squit.entity import com.typesafe.config.ConfigFactory +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldBeInstanceOf +import org.junit.jupiter.api.Test import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.nio.file.Paths -import org.amshove.kluent.shouldBeEqualTo -import org.amshove.kluent.shouldBeInstanceOf -import org.junit.jupiter.api.Test class SquitTestTest { @@ -21,7 +21,7 @@ class SquitTestTest { Paths.get("/response"), mapOf("test1_pre.sql" to listOf(Paths.get("/pre/test1_pre.sql"))), mapOf("test1_post.sql" to listOf(Paths.get("/post/test1_post.sql"))), - listOf(Paths.get("/test1/description.md")) + listOf(Paths.get("/test1/description.md")), ) val test2 = SquitTest( @@ -31,10 +31,10 @@ class SquitTestTest { Paths.get("/response"), mapOf( "test2_pre.sql" to listOf(Paths.get("/pre/test2_pre.sql")), - "test1_pre.sql" to listOf(Paths.get("/additional/test1_pre.sql")) + "test1_pre.sql" to listOf(Paths.get("/additional/test1_pre.sql")), ), mapOf("test2_post.sql" to listOf(Paths.get("/post/test2_post.sql"))), - listOf(Paths.get("/test2/description.md")) + listOf(Paths.get("/test2/description.md")), ) val expected = SquitTest( @@ -44,13 +44,13 @@ class SquitTestTest { Paths.get("/response"), mapOf( "test1_pre.sql" to listOf(Paths.get("/additional/test1_pre.sql"), Paths.get("/pre/test1_pre.sql")), - "test2_pre.sql" to listOf(Paths.get("/pre/test2_pre.sql")) + "test2_pre.sql" to listOf(Paths.get("/pre/test2_pre.sql")), ), mapOf( "test1_post.sql" to listOf(Paths.get("/post/test1_post.sql")), - "test2_post.sql" to listOf(Paths.get("/post/test2_post.sql")) + "test2_post.sql" to listOf(Paths.get("/post/test2_post.sql")), ), - listOf(Paths.get("/test2/description.md"), Paths.get("/test1/description.md")) + listOf(Paths.get("/test2/description.md"), Paths.get("/test1/description.md")), ) test1.merge(test2) shouldBeEqualTo expected @@ -65,7 +65,7 @@ class SquitTestTest { Paths.get("/response.xml"), mapOf("test_pre.sql" to listOf(Paths.get("/pre/test_pre.sql"))), mapOf("test_post.sql" to listOf(Paths.get("/post/test_pre.sql"))), - listOf(Paths.get("/description/description.md")) + listOf(Paths.get("/description/description.md")), ) val serialized = ByteArrayOutputStream().let { byteOut -> diff --git a/src/test/kotlin/de/smartsquare/squit/io/FilesUtilsTest.kt b/src/test/kotlin/de/smartsquare/squit/io/FilesUtilsTest.kt index d7d3c626..86cc2ab9 100644 --- a/src/test/kotlin/de/smartsquare/squit/io/FilesUtilsTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/io/FilesUtilsTest.kt @@ -1,10 +1,10 @@ package de.smartsquare.squit.io -import kotlin.io.path.ExperimentalPathApi -import kotlin.io.path.createTempDirectory import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldNotExist import org.junit.jupiter.api.Test +import kotlin.io.path.ExperimentalPathApi +import kotlin.io.path.createTempDirectory @ExperimentalPathApi class FilesUtilsTest { diff --git a/src/test/kotlin/de/smartsquare/squit/io/JsonParserSupportTest.kt b/src/test/kotlin/de/smartsquare/squit/io/JsonParserSupportTest.kt index a1577570..926eab10 100644 --- a/src/test/kotlin/de/smartsquare/squit/io/JsonParserSupportTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/io/JsonParserSupportTest.kt @@ -1,13 +1,13 @@ package de.smartsquare.squit.io import de.smartsquare.squit.TestUtils -import java.io.IOException import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldThrow import org.amshove.kluent.withCause import org.amshove.kluent.withMessage import org.gradle.api.GradleException import org.junit.jupiter.api.Test +import java.io.IOException class JsonParserSupportTest { diff --git a/src/test/kotlin/de/smartsquare/squit/io/SAXReaderSupportTest.kt b/src/test/kotlin/de/smartsquare/squit/io/SAXReaderSupportTest.kt index 641b5609..68860711 100644 --- a/src/test/kotlin/de/smartsquare/squit/io/SAXReaderSupportTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/io/SAXReaderSupportTest.kt @@ -1,13 +1,13 @@ package de.smartsquare.squit.io import de.smartsquare.squit.TestUtils -import java.io.IOException import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldThrow import org.amshove.kluent.withCause import org.amshove.kluent.withMessage import org.gradle.api.GradleException import org.junit.jupiter.api.Test +import java.io.IOException class SAXReaderSupportTest { diff --git a/src/test/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizerTest.kt b/src/test/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizerTest.kt index 481262ea..c2de6696 100644 --- a/src/test/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizerTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/mediatype/json/JsonCanonicalizerTest.kt @@ -32,8 +32,8 @@ class JsonCanonicalizerTest { MediaTypeConfig( xmlStrict = false, xmlCanonicalize = false, - jsonCanonicalize = true - ) + jsonCanonicalize = true, + ), ) // language=json @@ -86,8 +86,8 @@ class JsonCanonicalizerTest { MediaTypeConfig( xmlStrict = false, xmlCanonicalize = false, - jsonCanonicalize = true - ) + jsonCanonicalize = true, + ), ) // language=json @@ -135,8 +135,8 @@ class JsonCanonicalizerTest { MediaTypeConfig( xmlStrict = false, xmlCanonicalize = false, - jsonCanonicalize = false - ) + jsonCanonicalize = false, + ), ) result shouldBeEqualTo structure diff --git a/src/test/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizerTest.kt b/src/test/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizerTest.kt index 290a7ad9..e2bb23ca 100644 --- a/src/test/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizerTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/mediatype/xml/XmlCanonicalizerTest.kt @@ -22,8 +22,8 @@ class XmlCanonicalizerTest { MediaTypeConfig( xmlStrict = false, xmlCanonicalize = true, - jsonCanonicalize = false - ) + jsonCanonicalize = false, + ), ) // language=xml @@ -54,8 +54,8 @@ class XmlCanonicalizerTest { MediaTypeConfig( xmlStrict = false, xmlCanonicalize = false, - jsonCanonicalize = false - ) + jsonCanonicalize = false, + ), ) result shouldBeEqualTo structure @@ -76,8 +76,8 @@ class XmlCanonicalizerTest { xmlStrict = false, xmlCanonicalize = true, jsonCanonicalize = false, - resolveInvalidNamespaces = true - ) + xmlResolveInvalidNamespaces = true, + ), ) // language=xml @@ -108,8 +108,8 @@ class XmlCanonicalizerTest { xmlStrict = false, xmlCanonicalize = true, jsonCanonicalize = false, - resolveInvalidNamespaces = true - ) + xmlResolveInvalidNamespaces = true, + ), ) // language=xml diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskJsonTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskJsonTest.kt index 04acd5d8..aea481cd 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskJsonTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskJsonTest.kt @@ -2,7 +2,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.amshove.kluent.shouldBe @@ -11,6 +10,7 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitPostProcessTaskJsonTest { @@ -38,8 +38,9 @@ class SquitPostProcessTaskJsonTest { server.enqueue(MockResponse().setBody("{\n \"cool\": true\n}")) val arguments = listOf( - "squitPostProcess", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$jsonProject" + "squitPostProcess", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$jsonProject", ) val result = gradleRunner(jsonProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskPreviousTaskErrorTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskPreviousTaskErrorTest.kt index 87ffc901..0f69b165 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskPreviousTaskErrorTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskPreviousTaskErrorTest.kt @@ -2,12 +2,12 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.charset.Charset -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldStartWith import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.charset.Charset +import java.nio.file.Files class SquitPostProcessTaskPreviousTaskErrorTest { diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskTest.kt index 2276303a..4401d4d3 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPostProcessTaskTest.kt @@ -2,7 +2,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.amshove.kluent.shouldBe @@ -13,6 +12,7 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitPostProcessTaskTest { @@ -43,8 +43,10 @@ class SquitPostProcessTaskTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitPostProcess", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-PtagsOr=call1,call2" + "squitPostProcess", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-PtagsOr=call1,call2", ) val result = gradleRunner(project, arguments).build() @@ -63,8 +65,10 @@ class SquitPostProcessTaskTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitPostProcess", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-PtagsOr=call1,call2" + "squitPostProcess", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-PtagsOr=call1,call2", ) val result = gradleRunner(project, arguments).build() @@ -83,8 +87,11 @@ class SquitPostProcessTaskTest { } val arguments = listOf( - "squitPostProcess", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-PtagsOr=call1,call2", "--build-cache" + "squitPostProcess", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-PtagsOr=call1,call2", + "--build-cache", ) val result = gradleRunner(project, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskDifferentEncodingTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskDifferentEncodingTest.kt index e80892d9..6b39b672 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskDifferentEncodingTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskDifferentEncodingTest.kt @@ -2,15 +2,15 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files -import java.nio.file.StandardOpenOption.CREATE -import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldContain import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.nio.file.Files +import java.nio.file.StandardOpenOption.CREATE +import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING class SquitPreProcessTaskDifferentEncodingTest { @@ -32,8 +32,10 @@ class SquitPreProcessTaskDifferentEncodingTest { @Test fun `normal run`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", - "-Psquit.rootDir=$project", "-PtagsOr=call1,call2,call4" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$project", + "-PtagsOr=call1,call2,call4", ) val result = gradleRunner(project, arguments).buildAndFail() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskGetTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskGetTest.kt index 1eb09a68..470a0fc1 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskGetTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskGetTest.kt @@ -2,11 +2,11 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeFalse import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitPreProcessTaskGetTest { @@ -17,7 +17,9 @@ class SquitPreProcessTaskGetTest { @Test fun `normal run`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", "-Psquit.rootDir=$getProject" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$getProject", ) val result = gradleRunner(getProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidConfTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidConfTest.kt index 02382f15..ac1f83e2 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidConfTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidConfTest.kt @@ -2,11 +2,11 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.io.File import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldContain import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.io.File class SquitPreProcessTaskInvalidConfTest { diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidResponseTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidResponseTest.kt index 5af7acc4..672d4c72 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidResponseTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskInvalidResponseTest.kt @@ -2,12 +2,12 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.charset.Charset -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldStartWith import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.charset.Charset +import java.nio.file.Files class SquitPreProcessTaskInvalidResponseTest { diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskJsonTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskJsonTest.kt index 41fea65f..4aa07d7c 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskJsonTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskJsonTest.kt @@ -2,11 +2,11 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeTrue import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitPreProcessTaskJsonTest { @@ -17,8 +17,9 @@ class SquitPreProcessTaskJsonTest { @Test fun `normal run`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", - "-Psquit.rootDir=$jsonProject" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$jsonProject", ) val result = gradleRunner(jsonProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskOptionsTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskOptionsTest.kt index 2c37e9d2..878df0a6 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskOptionsTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskOptionsTest.kt @@ -2,12 +2,12 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitPreProcessTaskOptionsTest { @@ -18,7 +18,9 @@ class SquitPreProcessTaskOptionsTest { @Test fun `normal run`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", "-Psquit.rootDir=$optionsProject" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$optionsProject", ) val result = gradleRunner(optionsProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskPlaceholderTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskPlaceholderTest.kt index 46c753f4..ef4dd8cb 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskPlaceholderTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskPlaceholderTest.kt @@ -13,8 +13,11 @@ class SquitPreProcessTaskPlaceholderTest { @Test fun `normal run`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", "-Ptags=call2", - "-Psquit.rootDir=$projectWithPlaceholders", "-Psquit.placeholder2=test" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Ptags=call2", + "-Psquit.rootDir=$projectWithPlaceholders", + "-Psquit.placeholder2=test", ) val result = gradleRunner(projectWithPlaceholders, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskTest.kt index 15f6c7de..440211a3 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitPreProcessTaskTest.kt @@ -2,7 +2,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse @@ -12,6 +11,7 @@ import org.amshove.kluent.shouldContain import org.amshove.kluent.shouldNotContain import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitPreProcessTaskTest { @@ -38,8 +38,10 @@ class SquitPreProcessTaskTest { @Test fun `normal run`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", - "-Psquit.rootDir=$project", "-PtagsOr=call1,call2,call4" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$project", + "-PtagsOr=call1,call2,call4", ) val result = gradleRunner(project, arguments).build() @@ -85,8 +87,10 @@ class SquitPreProcessTaskTest { @Test fun `running with tags`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", - "-Psquit.rootDir=$project", "-PtagsAnd=project,unique" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$project", + "-PtagsAnd=project,unique", ) val result = gradleRunner(project, arguments).build() @@ -102,8 +106,10 @@ class SquitPreProcessTaskTest { @Test fun `running with the unignore flag`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", - "-Psquit.rootDir=$project", "-Psquit.titlePlaceholder=newTitle" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$project", + "-Psquit.titlePlaceholder=newTitle", ) val result = gradleRunner(project, arguments).build() @@ -118,8 +124,10 @@ class SquitPreProcessTaskTest { @Test fun `running with overriding config`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", - "-Psquit.rootDir=$project", "-Punignore" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$project", + "-Punignore", ) val result = gradleRunner(project, arguments).build() @@ -130,8 +138,11 @@ class SquitPreProcessTaskTest { @Test fun `running with build cache twice`() { val arguments = listOf( - "squitPreProcess", "-Psquit.endpointPlaceholder=https://example.com", - "-Psquit.rootDir=$project", "-Punignore", "--build-cache" + "squitPreProcess", + "-Psquit.endpointPlaceholder=https://example.com", + "-Psquit.rootDir=$project", + "-Punignore", + "--build-cache", ) val result = gradleRunner(project, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskConfigurableTasksTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskConfigurableTasksTest.kt index 5b2625c6..67af17f4 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskConfigurableTasksTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskConfigurableTasksTest.kt @@ -18,8 +18,10 @@ import org.junit.jupiter.api.Test import java.sql.DriverManager import java.time.Instant import java.util.concurrent.TimeUnit +import org.h2.Driver as H2Driver class SquitRequestTaskConfigurableTasksTest { + private val project = TestUtils.getResourcePath("test-project-task-config") private val jdbc = "jdbc:h2:$project/testDb;IFEXISTS=TRUE" @@ -32,6 +34,8 @@ class SquitRequestTaskConfigurableTasksTest { @BeforeEach fun setUp() { + H2Driver.load() + server = MockWebServer() } @@ -40,6 +44,7 @@ class SquitRequestTaskConfigurableTasksTest { server.shutdown() TestUtils.deleteDatabaseFiles(project) + preRunFile.delete() postRunFile.delete() } @@ -49,19 +54,23 @@ class SquitRequestTaskConfigurableTasksTest { server.enqueue( MockResponse() .setHeadersDelay(10L, TimeUnit.MILLISECONDS) - .setBody("") + .setBody(""), ) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-Ptags=default" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-Ptags=default", ) val result = gradleRunner(project, arguments).build() result.task(":squitRunRequests")?.outcome shouldBe TaskOutcome.SUCCESS + val preScriptExecution = Instant.ofEpochMilli(preRunFile.readText().toLong()) val postScriptExecution = Instant.ofEpochMilli(postRunFile.readText().toLong()) + DriverManager.getConnection(jdbc, username, password).use { connection -> val resultSet = connection.createStatement().executeQuery("SELECT * FROM TIMESTAMPS") resultSet.next() @@ -82,12 +91,14 @@ class SquitRequestTaskConfigurableTasksTest { server.enqueue( MockResponse() .setHeadersDelay(10L, TimeUnit.MILLISECONDS) - .setBody("") + .setBody(""), ) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-Ptags=configured_order" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-Ptags=configured_order", ) val result = gradleRunner(project, arguments).build() @@ -96,6 +107,7 @@ class SquitRequestTaskConfigurableTasksTest { val preScriptExecution = Instant.ofEpochMilli(preRunFile.readText().toLong()) val postScriptExecution = Instant.ofEpochMilli(postRunFile.readText().toLong()) + DriverManager.getConnection(jdbc, username, password).use { connection -> val resultSet = connection.createStatement().executeQuery("SELECT * FROM TIMESTAMPS") resultSet.next() @@ -116,12 +128,14 @@ class SquitRequestTaskConfigurableTasksTest { server.enqueue( MockResponse() .setHeadersDelay(10L, TimeUnit.MILLISECONDS) - .setBody("") + .setBody(""), ) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-Ptags=only_pre_db_script" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-Ptags=only_pre_db_script", ) val result = gradleRunner(project, arguments).build() @@ -134,6 +148,7 @@ class SquitRequestTaskConfigurableTasksTest { resultSet.getString(3) shouldBeEqualTo "TEST_PRE.SQL" resultSet.next().shouldBeFalse() } + preRunFile.shouldNotExist() postRunFile.shouldExist() } diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskGetTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskGetTest.kt index fe8cf797..30a4cfa5 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskGetTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskGetTest.kt @@ -34,8 +34,9 @@ class SquitRequestTaskGetTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$getProject" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$getProject", ) val result = gradleRunner(getProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskInvalidSqlTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskInvalidSqlTest.kt index f65fe322..a99f8397 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskInvalidSqlTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskInvalidSqlTest.kt @@ -2,7 +2,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.io.File import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.amshove.kluent.shouldBe @@ -11,6 +10,7 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.io.File class SquitRequestTaskInvalidSqlTest { @@ -35,8 +35,9 @@ class SquitRequestTaskInvalidSqlTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$invalidProject2" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$invalidProject2", ) val result = gradleRunner(invalidProject2, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskJsonTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskJsonTest.kt index 36ed48b1..c9ecf0cb 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskJsonTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskJsonTest.kt @@ -3,7 +3,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.entity.SquitResponseInfo import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.amshove.kluent.shouldBe @@ -13,6 +12,7 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitRequestTaskJsonTest { @@ -41,8 +41,9 @@ class SquitRequestTaskJsonTest { server.enqueue(MockResponse().setBody("{\n \"cool\": true\n}")) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$jsonProject" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$jsonProject", ) val result = gradleRunner(jsonProject, arguments).build() @@ -56,7 +57,7 @@ class SquitRequestTaskJsonTest { } val (expectedResponseCode) = SquitResponseInfo.fromJson( - Files.readAllBytes(jsonCall1ActualResponseInfo).toString(Charsets.UTF_8) + Files.readAllBytes(jsonCall1ActualResponseInfo).toString(Charsets.UTF_8), ) expectedResponseCode shouldBeInRange 200..599 diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskOptionsTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskOptionsTest.kt index 0ff09787..e345dd75 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskOptionsTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskOptionsTest.kt @@ -35,8 +35,9 @@ class SquitRequestTaskOptionsTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$optionsProject" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$optionsProject", ) val result = gradleRunner(optionsProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskPreviousTaskErrorTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskPreviousTaskErrorTest.kt index 6a83b9b1..739f99a0 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskPreviousTaskErrorTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskPreviousTaskErrorTest.kt @@ -2,12 +2,12 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.charset.Charset -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldStartWith import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.charset.Charset +import java.nio.file.Files class SquitRequestTaskPreviousTaskErrorTest { diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskTest.kt index ac277394..e84842e2 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitRequestTaskTest.kt @@ -3,11 +3,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.entity.SquitMetaInfo import de.smartsquare.squit.gradleRunner -import java.io.File -import java.nio.charset.Charset -import java.nio.file.Files -import java.sql.DriverManager -import java.time.LocalDateTime import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.amshove.kluent.shouldBe @@ -23,6 +18,12 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.io.File +import java.nio.charset.Charset +import java.nio.file.Files +import java.sql.DriverManager +import java.time.LocalDateTime +import org.h2.Driver as H2Driver class SquitRequestTaskTest { @@ -59,8 +60,10 @@ class SquitRequestTaskTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-PtagsOr=call1,call2" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-PtagsOr=call1,call2", ) val result = gradleRunner(project, arguments).build() @@ -73,7 +76,7 @@ class SquitRequestTaskTest { val (date, duration) = SquitMetaInfo.fromJson( Files.readAllBytes(call1Meta) - .toString(Charset.defaultCharset()) + .toString(Charset.defaultCharset()), ) date shouldBeBefore LocalDateTime.now() @@ -92,6 +95,7 @@ class SquitRequestTaskTest { it.headers["some"] shouldBeEqualTo "header" } + H2Driver.load() DriverManager.getConnection(jdbc, username, password).use { connection -> val resultSet = connection.createStatement().executeQuery("SELECT * FROM animals") @@ -113,8 +117,11 @@ class SquitRequestTaskTest { server.enqueue(MockResponse().setBody("error").setResponseCode(500)) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-PtagsOr=call1", "--info" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-PtagsOr=call1", + "--info", ) val result = gradleRunner(project, arguments).build() @@ -130,8 +137,10 @@ class SquitRequestTaskTest { // Nothing enqueued to cause timeout. val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-Ptags=call1" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-Ptags=call1", ) val result = gradleRunner(project, arguments).build() @@ -147,8 +156,11 @@ class SquitRequestTaskTest { server.enqueue(MockResponse().setBody("").setHeader("Content-Type", "text/plain")) val arguments = listOf( - "squitRunRequests", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-Ptags=call1", "--info" + "squitRunRequests", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-Ptags=call1", + "--info", ) val result = gradleRunner(project, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskDifferentStructureTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskDifferentStructureTest.kt index 141ef36a..8d4e559f 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskDifferentStructureTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskDifferentStructureTest.kt @@ -2,7 +2,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.amshove.kluent.shouldBe @@ -11,6 +10,7 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.nio.file.Files class SquitTestTaskDifferentStructureTest { @@ -37,8 +37,9 @@ class SquitTestTaskDifferentStructureTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$differentStructureProject" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$differentStructureProject", ) val result = gradleRunner(differentStructureProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskErrorResponseCodeTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskErrorResponseCodeTest.kt index 465df73e..2672adef 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskErrorResponseCodeTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskErrorResponseCodeTest.kt @@ -33,8 +33,9 @@ class SquitTestTaskErrorResponseCodeTest { server.enqueue(MockResponse().setBody("{\n \"cool\": true\n}").setResponseCode(400)) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$projectWithResponseCode" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$projectWithResponseCode", ) val result = gradleRunner(projectWithResponseCode, arguments).build() @@ -47,8 +48,9 @@ class SquitTestTaskErrorResponseCodeTest { server.enqueue(MockResponse().setBody("{\n \"cool\": true\n}").setResponseCode(200)) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$projectWithResponseCode" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$projectWithResponseCode", ) val result = gradleRunner(projectWithResponseCode, arguments).buildAndFail() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskIgnoreFailuresTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskIgnoreFailuresTest.kt index e0dfdab1..bae6bdb3 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskIgnoreFailuresTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskIgnoreFailuresTest.kt @@ -33,8 +33,9 @@ class SquitTestTaskIgnoreFailuresTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$projectIgnoreFailures" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$projectIgnoreFailures", ) val result = gradleRunner(projectIgnoreFailures, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonDifferentOrderTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonDifferentOrderTest.kt index ba81eb84..401d4015 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonDifferentOrderTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonDifferentOrderTest.kt @@ -40,13 +40,14 @@ class SquitTestTaskJsonDifferentOrderTest { "olleh": 321, "hello": "123" } - """.trimIndent() - ) + """.trimIndent(), + ), ) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$jsonProjectWithDifferentOrder" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$jsonProjectWithDifferentOrder", ) val result = gradleRunner(jsonProjectWithDifferentOrder, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonTest.kt index f6904acd..fbccffb6 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskJsonTest.kt @@ -33,8 +33,9 @@ class SquitTestTaskJsonTest { server.enqueue(MockResponse().setBody("{\n \"cool\": true\n}")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$jsonProject" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$jsonProject", ) val result = gradleRunner(jsonProject, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskNonStrictXmlDiffingTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskNonStrictXmlDiffingTest.kt index 4edfabab..4f74f880 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskNonStrictXmlDiffingTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskNonStrictXmlDiffingTest.kt @@ -33,8 +33,9 @@ class SquitTestTaskNonStrictXmlDiffingTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$projectWithNonStrictXml" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$projectWithNonStrictXml", ) val result = gradleRunner(projectWithNonStrictXml, arguments).build() diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskPreviousTaskErrorTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskPreviousTaskErrorTest.kt index 4cb3a8fc..f23458ab 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskPreviousTaskErrorTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskPreviousTaskErrorTest.kt @@ -2,12 +2,12 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.charset.Charset -import java.nio.file.Files import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldStartWith import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test +import java.nio.charset.Charset +import java.nio.file.Files class SquitTestTaskPreviousTaskErrorTest { diff --git a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskTest.kt b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskTest.kt index d672b735..16ecedae 100644 --- a/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/task/SquitTestTaskTest.kt @@ -2,8 +2,6 @@ package de.smartsquare.squit.task import de.smartsquare.squit.TestUtils import de.smartsquare.squit.gradleRunner -import java.nio.file.Files -import kotlin.streams.toList import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.amshove.kluent.shouldBe @@ -17,6 +15,8 @@ import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.nio.file.Files +import kotlin.streams.toList class SquitTestTaskTest { @@ -54,8 +54,9 @@ class SquitTestTaskTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", ) val result = gradleRunner(project, arguments).build() @@ -83,8 +84,10 @@ class SquitTestTaskTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-PtagsOr=call1,call2" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-PtagsOr=call1,call2", ) val result = gradleRunner(project, arguments).buildAndFail() @@ -109,8 +112,10 @@ class SquitTestTaskTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-Punignore" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-Punignore", ) val result = gradleRunner(project, arguments).buildAndFail() @@ -129,8 +134,10 @@ class SquitTestTaskTest { server.enqueue(MockResponse().setBody("")) val arguments = listOf( - "squitTest", "-Psquit.endpointPlaceholder=${server.url("/")}", - "-Psquit.rootDir=$project", "-Punexclude" + "squitTest", + "-Psquit.endpointPlaceholder=${server.url("/")}", + "-Psquit.rootDir=$project", + "-Punexclude", ) val result = gradleRunner(project, arguments).buildAndFail() diff --git a/src/test/kotlin/de/smartsquare/squit/util/UtilExtensionsTest.kt b/src/test/kotlin/de/smartsquare/squit/util/UtilExtensionsTest.kt index 3ab78ed2..5120b08e 100644 --- a/src/test/kotlin/de/smartsquare/squit/util/UtilExtensionsTest.kt +++ b/src/test/kotlin/de/smartsquare/squit/util/UtilExtensionsTest.kt @@ -1,8 +1,8 @@ package de.smartsquare.squit.util -import java.nio.file.Paths import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test +import java.nio.file.Paths class UtilExtensionsTest {