diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..6dade98 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,80 @@ +name: Build & test +on: + push: + branches-ignore: [ main ] + pull_request: + branches: [ develop ] + workflow_dispatch: + repository_dispatch: + types: [ utPLSQL-build ] + +defaults: + run: + shell: bash + +jobs: + build: + + runs-on: ubuntu-latest + + services: + oracle: + image: gvenzl/oracle-xe:21-slim + env: + ORACLE_PASSWORD: oracle + ports: + - 1521:1521 + options: >- + --health-cmd healthcheck.sh + --health-interval 10s + --health-timeout 5s + --health-retries 10 + + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Install utPLSQL + run: sh ${{ github.workspace }}/scripts/1_install_utplsql.sh + + - name: Install demo project + run: sh ${{ github.workspace }}/scripts/2_install_demo_project.sh + + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' + server-id: ossrh + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + + - name: Cache local Maven repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Maven unit and integration tests + run: mvn clean verify sonar:sonar -Pcoverage -Dsonar.projectKey=utPLSQL_utPLSQL-java-api + env: + GITHUB_TOKEN: ${{ secrets.API_TOKEN_GITHUB }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + + - name: Maven deploy snapshot + run: mvn deploy -DskipTests + env: + MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + - name: Publish unit test results + uses: EnricoMi/publish-unit-test-result-action@v1.24 + if: always() + with: + files: target/**/TEST**.xml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..9cee803 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,70 @@ +name: Build and deploy release + +on: + push: + branches: [ main ] + +defaults: + run: + shell: bash + +jobs: + build: + + runs-on: ubuntu-latest + + services: + oracle: + image: gvenzl/oracle-xe:21-slim + env: + ORACLE_PASSWORD: oracle + ports: + - 1521:1521 + options: >- + --health-cmd healthcheck.sh + --health-interval 10s + --health-timeout 5s + --health-retries 10 + + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Install utPLSQL + run: sh ${{ github.workspace }}/scripts/1_install_utplsql.sh + + - name: Install demo project + run: sh ${{ github.workspace }}/scripts/2_install_demo_project.sh + + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' + server-id: ossrh + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + + - name: Cache local Maven repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Maven deploy release + run: mvn clean deploy -Prelease + env: + MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + - name: Publish unit test results + uses: EnricoMi/publish-unit-test-result-action@v1.24 + if: always() + with: + files: target/**/TEST**.xml diff --git a/.gitignore b/.gitignore index 3a7808b..9ec7c9e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ # IntelliJ *.iml -.idea/* +.idea !/.idea/codeStyles !/.idea/dictionaries diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml deleted file mode 100644 index 4f717ff..0000000 --- a/.idea/codeStyles/Project.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml deleted file mode 100644 index 79ee123..0000000 --- a/.idea/codeStyles/codeStyleConfig.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/dictionaries/utPLSQL.xml b/.idea/dictionaries/utPLSQL.xml deleted file mode 100644 index 6cb7c83..0000000 --- a/.idea/dictionaries/utPLSQL.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - utplsql - - - \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..cb28b0e Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c257d25 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.3/apache-maven-3.8.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index bfb554f..0000000 --- a/.travis.yml +++ /dev/null @@ -1,85 +0,0 @@ -sudo: required -language: java - -services: - - docker - -jdk: - - oraclejdk8 - -env: - global: - - DOCKER_CFG=$HOME/.docker - - DOCKER_REPO="utplsqlv3/oracledb" - - CACHE_DIR=$HOME/.cache - - DB_URL="127.0.0.1:1521:XE" - - DB_USER=app - - DB_PASS=app - - ORACLE_VERSION="11g-r2-xe" - - DOCKER_OPTIONS="--shm-size=1g" - - UTPLSQL_FILE="utPLSQL" - matrix: - - UTPLSQL_VERSION="v3.0.0" - UTPLSQL_FILE="utPLSQLv3.0.0" - - UTPLSQL_VERSION="v3.0.1" - - UTPLSQL_VERSION="v3.0.2" - - UTPLSQL_VERSION="v3.0.3" - - UTPLSQL_VERSION="v3.0.4" - - UTPLSQL_VERSION="v3.1.1" - - UTPLSQL_VERSION="v3.1.2" - - UTPLSQL_VERSION="v3.1.3" - - UTPLSQL_VERSION="develop" - UTPLSQL_FILE="utPLSQL" - -before_cache: - - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock - - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ -cache: - directories: - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ - - $DOCKER_CFG - - $CACHE_DIR - -install: - - bash .travis/start_db.sh - - bash .travis/install_utplsql.sh - - bash .travis/install_demo_project.sh - -before_script: - - echo JAVA_HOME = ${JAVA_HOME} - - echo PATH = ${PATH} - - ls ${JAVA_HOME} - - java -version - - echo $JAVA_OPTS - - echo $GRADLE_OPTS - - echo JAVA_HOME = ${GRADLE_HOME} - -script: - - ./gradlew check - -deploy: - - provider: script - script: ./gradlew uploadArchives - skip_cleanup: true - on: - repository: utPLSQL/utPLSQL-java-api - tags: true - # Use only first job "#xxx.1" to publish artifacts - condition: "${TRAVIS_JOB_NUMBER} =~ \\.1$" - - - provider: script - script: ./gradlew uploadArchives - skip_cleanup: true - on: - repository: utPLSQL/utPLSQL-java-api - branch: develop - # Use only first job "#xxx.1" to publish artifacts - condition: "${TRAVIS_JOB_NUMBER} =~ \\.1$" - -notifications: - slack: - rooms: - - secure: "RTwZxg50LgiDo8/Z0ZGrYP7+gHFXlDjcAlXu7IGne8/O/79B8UVG3KP5j4PHuRtlt86WBflXB/5nhszgwjleEhNVdciuBPTBv3PHtvoYnqEajtoDsBR4fiqpGk4QJREqYo5UwzBVisEtGS2qvhjOVRy5sgfPqdXfKM4Jl6x6EMoPmuEWKPZW80eO1AXD2lhcT35fxKAuEavKDrY9WKB3P8HycySFm2+IOgEvxk7p3qkukd/AMOPW54A52ry5AkwElj7439DV8MGYOHnrK9f5neMGCi6Q8VzUlTf95WbF7yoPWHNOMPt0LFKtnDOEjljwrRDpf8D/TcbLO5Q03kgOcXOB/KJp8WqgViGT8WO963GPBM7JXD4f5h04QYVn9lab8M6nK1PQZVKuzq6qBcjGW06EmczaseKnc5VW0tc/svw0Qhgot1rh3bRMHe9xX1j2wgfNcqeHFkoRX2AtPBtH5tDsWYVY0148wJ3cLXKZf1hxRd7V6gFfE5fVey/rTRVk8eEpNEhudIZCJ/T/ng3DWC271uPne7B/E2jy3jrgQ5p+VfcjC8dSu65Gmu7hWEON8g2cD8YQxCEryqgaCRn5R77FHWi9Gi3a85Kh951qL6mLxMl44VFil4CGdGi0hJpWPaGvSNNbfXx5eNyzHwjjT5fgk0EDOWVyHaO/Ni6jDFM=" - on_success: change - on_failure: always diff --git a/.travis/create_api_user.sh b/.travis/create_api_user.sh deleted file mode 100644 index c898f15..0000000 --- a/.travis/create_api_user.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -set -ev - -sqlplus -S -L sys/oracle@//127.0.0.1:1521/xe AS SYSDBA < demo_project.sh.tmp < install.sh.tmp < section of your pom.xml. No special plugins or extensions are required. +This is a Maven Library project, you can add on your Java project as a dependency. -```xml - - - utplsql-java-api - - https://packagecloud.io/utplsql/utplsql-java-api/maven2 - - - true - - - true - - - -``` +*Notice: You no longer need to configure an additional repository. The library is available in Maven Central since version 3.1.15.* -To use the java-api library, add this to the `` section of your `pom.xml`. ```xml org.utplsql - java-api - 3.1.2 - compile + utplsql-java-api + 3.1.16 ``` ## Compatibility The latest Java-API is always compatible with all database frameworks of the same major version. -For example API-3.0.4 is compatible with database framework 3.0.0-3.1.2 but not with database framework 2.x. +For example API-3.0.4 is compatible with database framework 3.0.0-3.1.* but not with database framework 2.x. It is although recommended to always use the latest release of the API to build your tools for utPLSQL. @@ -100,7 +76,7 @@ You can also ask it for the database-version. ```java try (Connection conn = DriverManager.getConnection(url)) { CompatiblityProxy proxy = new CompatibilityProxy( conn ); - Version version = proxy.getDatabaseVersion(); + Version version = proxy.getUtPlsqlVersion(); } catch (SQLException e) { e.printStackTrace(); } @@ -113,7 +89,7 @@ It also provides a more generic approach to Reporter-handling. If you request the Reporter-Factory for a Reporter it has no specific implementation for it will just return an instance of a `DefaultReporter` with the given name as SQL-Type, assuming -that it exists in the database. Therefore you can address custom reporters without the need +that it exists in the database. Therefore, you can address custom reporters without the need of a specific java-side implementation. ```java @@ -130,4 +106,4 @@ try (Connection conn = DriverManager.getConnection(url)) { ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md) \ No newline at end of file +See [CONTRIBUTING.md](CONTRIBUTING.md) diff --git a/build.gradle.kts b/build.gradle.kts deleted file mode 100644 index d584e09..0000000 --- a/build.gradle.kts +++ /dev/null @@ -1,165 +0,0 @@ -import de.undercouch.gradle.tasks.download.Download -import org.gradle.api.tasks.testing.logging.TestExceptionFormat - -val deployerJars by configurations.creating - -group = "org.utplsql" -val mavenArtifactId = "java-api" -version = "3.1.6" - -val coverageResourcesVersion = "1.0.1" -val ojdbcVersion = "12.2.0.1" - -plugins { - `java-library` - `maven-publish` - maven - id("de.undercouch.download") version "3.4.3" -} - -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 -} - -// In this section you declare where to find the dependencies of your project -repositories { - maven { - url = uri("https://www.oracle.com/content/secure/maven/content") - credentials { - // you may set this properties using gradle.properties file in the root of the project or in your GRADLE_HOME - username = if (project.hasProperty("ORACLE_OTN_USER")) project.property("ORACLE_OTN_USER") as String? else System.getenv("ORACLE_OTN_USER") - password = if (project.hasProperty("ORACLE_OTN_PASSWORD")) project.property("ORACLE_OTN_PASSWORD") as String? else System.getenv("ORACLE_OTN_PASSWORD") - } - } - mavenCentral() -} - -dependencies { - // This dependency is exported to consumers, that is to say found on their compile classpath. - api("com.google.code.findbugs:jsr305:3.0.2") - - // This dependency is used internally, and not exposed to consumers on their own compile classpath. - implementation("org.slf4j:slf4j-api:1.7.25") - implementation("com.oracle.jdbc:ojdbc8:$ojdbcVersion") { - exclude(group = "com.oracle.jdbc") - } - implementation("com.oracle.jdbc:orai18n:$ojdbcVersion") - - // Use Jupiter test framework - testImplementation("org.junit.jupiter:junit-jupiter:5.4.0") - testImplementation("org.hamcrest:hamcrest:2.1") - deployerJars("io.packagecloud.maven.wagon:maven-packagecloud-wagon:0.0.6") -} - -tasks { - test { - useJUnitPlatform() - exclude("**/*IT.class") - testLogging { - events("passed", "skipped", "failed") - exceptionFormat = TestExceptionFormat.FULL - showStackTraces = true - } - } - - val intTest = create("intTest") { - dependsOn(test) - doFirst { - environment("DB_URL", System.getenv("DB_URL") ?: "localhost:1521/XE") - environment("DB_USER", System.getenv("DB_USER") ?: "app") - environment("DB_PASS", System.getenv("DB_PASS") ?: "app") - } - useJUnitPlatform() - include("**/*IT.class") - testLogging { - events("passed", "skipped", "failed") - exceptionFormat = TestExceptionFormat.FULL - showStackTraces = true - showStandardStreams = true - } - } - - // add integration tests to the whole check - named("check") { - dependsOn(intTest) - } - - val coverageResourcesDirectory = "${project.buildDir}/resources/main/CoverageHTMLReporter" - val coverageResourcesZip = "${project.buildDir}/utPLSQL-coverage-html-$coverageResourcesVersion.zip" - // download Coverage Resources from web - val downloadResources = create("downloadCoverageResources") { - src("https://codeload.github.com/utPLSQL/utPLSQL-coverage-html/zip/$coverageResourcesVersion") - dest(File(coverageResourcesZip)) - overwrite(true) - } - - withType { - dependsOn(downloadResources) - - val properties = project.properties.toMutableMap() - properties.putIfAbsent("travisBuildNumber", System.getenv("TRAVIS_BUILD_NUMBER") ?: "local") - expand(properties) - - doLast { - copy { - // extract assets folder only from downloaded archive - // https://github.com/gradle/gradle/pull/8494 - from(zipTree(coverageResourcesZip)) { - include("*/assets/**") - eachFile { - relativePath = RelativePath(true, *relativePath.segments.drop(2).toTypedArray()) // <2> - } - includeEmptyDirs = false - } - into(coverageResourcesDirectory) - } - } - } - - withType { - dependsOn("generatePomFileForMavenPublication") - manifest { - attributes( - "Built-By" to System.getProperty("user.name"), - "Created-By" to "Gradle ${gradle.gradleVersion}", - "Build-Jdk" to "${System.getProperty("os.name")} ${System.getProperty("os.arch")} ${System.getProperty("os.version")}" - ) - } - into("META-INF/maven/${project.group}/$mavenArtifactId") { - from("$buildDir/publications/maven") - rename(".*", "pom.xml") - } - archiveBaseName.set("java-api") - } - - named("uploadArchives") { - repositories.withGroovyBuilder { - "mavenDeployer" { - setProperty("configuration", deployerJars) - "repository"("url" to "packagecloud+https://packagecloud.io/utPLSQL/utPLSQL-java-api") { - "authentication"("password" to System.getenv("PACKAGECLOUD_TOKEN")) - } - } - } - } -} - -publishing { - publications { - create("maven") { - artifactId = mavenArtifactId - pom { - name.set("utPLSQL-java-api") - url.set("https://github.com/utPLSQL/utPLSQL-java-api") - licenses { - license { - name.set("The Apache License, Version 2.0") - url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") - } - } - } - from(components["java"]) - } - } -} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100755 index f6b961f..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1b2b07c..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100755 index af6708f..0000000 --- a/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 6d57edc..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..8d937f4 --- /dev/null +++ b/mvnw @@ -0,0 +1,308 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "$(uname)" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$(cd "$wdir/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..c4586b5 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,205 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..189ef45 --- /dev/null +++ b/pom.xml @@ -0,0 +1,225 @@ + + 4.0.0 + + org.utplsql + utplsql-java-api + 3.1.17-SNAPSHOT + + utPLSQL Java API + Java API for running Unit Tests with utPLSQL v3+. + https://github.com/utPLSQL/utPLSQL-java-api + + + UTF-8 + 1.8 + 1.8 + 5.5.2 + 19.3.0.0 + + utplsql + https://sonarcloud.io + + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + + Simon Martinelli + utPLSQL.org + http://utplsql.org + simon@martineli.ch + https://martinelli.ch + + + + + scm:git@github.com:utPLSQL/utPLSQL-java-api.git + https://github.com/utPLSQL/utPLSQL-java-api + + + + + org.slf4j + slf4j-api + 1.7.36 + + + com.oracle.database.jdbc + ojdbc8 + 19.3.0.0 + + + com.oracle.database.nls + orai18n + 19.3.0.0 + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + org.junit.jupiter + junit-jupiter + ${junit.jupiter.version} + test + + + org.hamcrest + hamcrest + 2.1 + + + org.mockito + mockito-core + 3.0.0 + + + + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.2 + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + ${dbUrl} + ${dbUser} + ${dbPass} + + + + + com.amashchenko.maven.plugin + gitflow-maven-plugin + 1.18.0 + + true + + main + + + + + + + + + coverage + + + + org.jacoco + jacoco-maven-plugin + 0.8.7 + + + prepare-agent + + prepare-agent + + + + report + + report + + + + + + + + + release + + + release + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.3.1 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.1 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.0.1 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + diff --git a/scripts/0_start_db.sh b/scripts/0_start_db.sh new file mode 100644 index 0000000..d319407 --- /dev/null +++ b/scripts/0_start_db.sh @@ -0,0 +1 @@ +docker run -d --name ora-utplsql -p 1521:1521 -e ORACLE_PASSWORD=oracle gvenzl/oracle-xe:21-slim diff --git a/scripts/1_install_utplsql.sh b/scripts/1_install_utplsql.sh new file mode 100644 index 0000000..bb6577c --- /dev/null +++ b/scripts/1_install_utplsql.sh @@ -0,0 +1,8 @@ +UTPLSQL_DOWNLOAD_URL=$(curl --silent https://api.github.com/repos/utPLSQL/utPLSQL/releases/latest | awk '/browser_download_url/ { print $2 }' | grep ".zip\"" | sed 's/"//g') + +curl -Lk "${UTPLSQL_DOWNLOAD_URL}" -o utPLSQL.zip + +unzip -q utPLSQL.zip + +docker run --rm -v $(pwd)/utPLSQL:/utPLSQL -w /utPLSQL/source --network host \ + --entrypoint sqlplus truemark/sqlplus:19.8 sys/oracle@//127.0.0.1:1521/XE as sysdba @install_headless.sql UT3 UT3 users diff --git a/scripts/2_install_demo_project.sh b/scripts/2_install_demo_project.sh new file mode 100644 index 0000000..a4089b1 --- /dev/null +++ b/scripts/2_install_demo_project.sh @@ -0,0 +1,11 @@ +docker run --rm -v $(pwd):/work -w /work/ --network host --entrypoint sqlplus truemark/sqlplus:19.8 \ + sys/oracle@//127.0.0.1:1521/XE as sysdba @scripts/sql/create_users.sql + +docker run --rm -v $(pwd):/work -w /work/ --network host --entrypoint sqlplus truemark/sqlplus:19.8 \ + app/pass@//127.0.0.1:1521/XE @scripts/sql/create_app_objects.sql + +docker run --rm -v $(pwd):/work -w /work/ --network host --entrypoint sqlplus truemark/sqlplus:19.8 \ + code_owner/pass@//127.0.0.1:1521/XE @scripts/sql/create_source_owner_objects.sql + +docker run --rm -v $(pwd):/work -w /work/ --network host --entrypoint sqlplus truemark/sqlplus:19.8 \ + tests_owner/pass@//127.0.0.1:1521/XE @scripts/sql/create_tests_owner_objects.sql diff --git a/scripts/sql/create_app_objects.sql b/scripts/sql/create_app_objects.sql new file mode 100644 index 0000000..2ad509f --- /dev/null +++ b/scripts/sql/create_app_objects.sql @@ -0,0 +1,9 @@ +whenever sqlerror exit failure rollback +whenever oserror exit failure rollback + +@scripts/sql/simple/scripts/sources/TO_TEST_ME.sql +@scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pks +@scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pkb + +@scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pks +@scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pkb diff --git a/scripts/sql/create_source_owner_objects.sql b/scripts/sql/create_source_owner_objects.sql new file mode 100644 index 0000000..bc10482 --- /dev/null +++ b/scripts/sql/create_source_owner_objects.sql @@ -0,0 +1,6 @@ +whenever sqlerror exit failure rollback +whenever oserror exit failure rollback + +@scripts/sql/owner_param/scripts/sources/foo/tables/TO_TEST_ME.sql +@scripts/sql/owner_param/scripts/sources/foo/packages/PKG_TEST_ME.pks +@scripts/sql/owner_param/scripts/sources/foo/package_bodies/PKG_TEST_ME.pkb diff --git a/scripts/sql/create_tests_owner_objects.sql b/scripts/sql/create_tests_owner_objects.sql new file mode 100644 index 0000000..cb244db --- /dev/null +++ b/scripts/sql/create_tests_owner_objects.sql @@ -0,0 +1,8 @@ +whenever sqlerror exit failure rollback +whenever oserror exit failure rollback + +create synonym TO_TEST_ME for CODE_OWNER.TO_TEST_ME; +create synonym PKG_TEST_ME for CODE_OWNER.PKG_TEST_ME; + +@scripts/sql/owner_param/scripts/test/bar/packages/TEST_PKG_TEST_ME.pks +@scripts/sql/owner_param/scripts/test/bar/package_bodies/TEST_PKG_TEST_ME.pkb diff --git a/scripts/sql/create_users.sql b/scripts/sql/create_users.sql new file mode 100644 index 0000000..fe64882 --- /dev/null +++ b/scripts/sql/create_users.sql @@ -0,0 +1,30 @@ +whenever sqlerror exit failure rollback +whenever oserror exit failure rollback +set echo off +set verify off + +define UTPLSQL_USER = 'UT3'; +define APP_USER = 'APP'; +define CODE_OWNER = 'CODE_OWNER'; +define TESTS_OWNER = 'TESTS_OWNER'; +define DB_PASS = 'pass'; + +grant execute any procedure to &UTPLSQL_USER; +grant create any procedure to &UTPLSQL_USER; +grant execute on dbms_lob to &UTPLSQL_USER; +grant execute on dbms_sql to &UTPLSQL_USER; +grant execute on dbms_xmlgen to &UTPLSQL_USER; +grant execute on dbms_lock to &UTPLSQL_USER; + +create user &APP_USER identified by &DB_PASS quota unlimited on USERS default tablespace USERS; +grant create session, create procedure, create type, create table, create sequence, create view to &APP_USER; +grant select any dictionary to &APP_USER; + +create user &CODE_OWNER identified by &DB_PASS quota unlimited on USERS default tablespace USERS; +grant create session, create procedure, create type, create table, create sequence, create view to &CODE_OWNER; + +create user &TESTS_OWNER identified by &DB_PASS quota unlimited on USERS default tablespace USERS; +grant create session, create procedure, create type, create table, create sequence, create view, create synonym to &TESTS_OWNER; +grant select any dictionary to &TESTS_OWNER; +grant select any table, delete any table, drop any table to &TESTS_OWNER; +grant execute any procedure to &TESTS_OWNER; diff --git a/scripts/sql/owner_param/scripts/sources/foo/package_bodies/PKG_TEST_ME.pkb b/scripts/sql/owner_param/scripts/sources/foo/package_bodies/PKG_TEST_ME.pkb new file mode 100644 index 0000000..d6846b2 --- /dev/null +++ b/scripts/sql/owner_param/scripts/sources/foo/package_bodies/PKG_TEST_ME.pkb @@ -0,0 +1,27 @@ +CREATE OR REPLACE PACKAGE BODY CODE_OWNER.PKG_TEST_ME IS + -- + -- This + -- + FUNCTION FC_TEST_ME(PPARAM1 IN VARCHAR2) RETURN NUMBER IS + BEGIN + IF PPARAM1 IS NULL THEN + RETURN NULL; + ELSIF PPARAM1 = '1' THEN + RETURN 1; + ELSE + RETURN 0; + END IF; + END FC_TEST_ME; + + PROCEDURE PR_TEST_ME(PSNAME IN VARCHAR2) IS + BEGIN + IF PSNAME IS NULL THEN + NULL; + ELSE + INSERT INTO TO_TEST_ME (SNAME) VALUES (PSNAME); + COMMIT; + END IF; + END PR_TEST_ME; + +END PKG_TEST_ME; +/ diff --git a/scripts/sql/owner_param/scripts/sources/foo/packages/PKG_TEST_ME.pks b/scripts/sql/owner_param/scripts/sources/foo/packages/PKG_TEST_ME.pks new file mode 100644 index 0000000..959b122 --- /dev/null +++ b/scripts/sql/owner_param/scripts/sources/foo/packages/PKG_TEST_ME.pks @@ -0,0 +1,8 @@ +-- +-- This package is used TO demonstrate the utPL/SQL possibilities +-- +CREATE OR REPLACE PACKAGE CODE_OWNER.PKG_TEST_ME AS + FUNCTION FC_TEST_ME(PPARAM1 IN VARCHAR2) RETURN NUMBER; + PROCEDURE PR_TEST_ME(PSNAME IN VARCHAR2); +END PKG_TEST_ME; +/ \ No newline at end of file diff --git a/scripts/sql/owner_param/scripts/sources/foo/tables/TO_TEST_ME.sql b/scripts/sql/owner_param/scripts/sources/foo/tables/TO_TEST_ME.sql new file mode 100644 index 0000000..b2e90d9 --- /dev/null +++ b/scripts/sql/owner_param/scripts/sources/foo/tables/TO_TEST_ME.sql @@ -0,0 +1,8 @@ +-- +-- This is a table used to demonstrate the UNIT test framework. +-- +CREATE TABLE TO_TEST_ME +( + SNAME VARCHAR2(10) +) +/ diff --git a/scripts/sql/owner_param/scripts/test/bar/package_bodies/TEST_PKG_TEST_ME.pkb b/scripts/sql/owner_param/scripts/test/bar/package_bodies/TEST_PKG_TEST_ME.pkb new file mode 100644 index 0000000..1b34f08 --- /dev/null +++ b/scripts/sql/owner_param/scripts/test/bar/package_bodies/TEST_PKG_TEST_ME.pkb @@ -0,0 +1,126 @@ +CREATE OR REPLACE PACKAGE BODY TESTS_OWNER.TEST_PKG_TEST_ME AS + + --------------------------------------------------------------------------- + PROCEDURE SETUP_GLOBAL IS + BEGIN + -- Put here the code which is valid for all tests and that should be + -- executed once. + NULL; + END SETUP_GLOBAL; + + --------------------------------------------------------------------------- + PROCEDURE TEARDOWN_GLOBAL IS + BEGIN + -- Put here the code that should be called only once after all the test + -- have executed + NULL; + END TEARDOWN_GLOBAL; + + --------------------------------------------------------------------------- + PROCEDURE SETUP_TEST IS + BEGIN + -- Nothing to clean up globally + NULL; + END SETUP_TEST; + + PROCEDURE TEARDOWN_TEST IS + BEGIN + -- Nothing to clean up globally + NULL; + END TEARDOWN_TEST; + + PROCEDURE TEST_FC_INPUT_1 IS + BEGIN + -- Ok this is a real test where I check that the function return 1 + -- when called with a '1' parameter + UT.EXPECT(PKG_TEST_ME.FC_TEST_ME('1')).TO_EQUAL(1); + END; + + PROCEDURE SETUP_TEST_FC_INPUT_1 IS + BEGIN + -- Nothing to be done really + NULL; + END; + + PROCEDURE TEARDOWN_TEST_FC_INPUT_1 IS + BEGIN + -- Nothing to be done really + NULL; + END; + + PROCEDURE TEST_FC_INPUT_0 IS + BEGIN + -- Ok this is a real test where I check that the function return 0 + -- when called with a '0' parameter + UT.EXPECT(PKG_TEST_ME.FC_TEST_ME('0')).TO_EQUAL(0); + END; + + PROCEDURE TEST_FC_INPUT_NULL IS + BEGIN + -- Ok I check that the function return NULL + -- when called with a NULL parameter + UT.EXPECT(PKG_TEST_ME.FC_TEST_ME(NULL)).TO_BE_NULL; + END TEST_FC_INPUT_NULL; + + PROCEDURE TEST_PR_TEST_ME_NULL IS + VNCOUNT1 PLS_INTEGER; + VNCOUNT2 PLS_INTEGER; + BEGIN + -- In this example I check that the procedure does + -- not insert anything when passing it a NULL parameter + SELECT COUNT(1) INTO VNCOUNT1 FROM TO_TEST_ME; + PKG_TEST_ME.PR_TEST_ME(NULL); + SELECT COUNT(1) INTO VNCOUNT2 FROM TO_TEST_ME; + UT.EXPECT(VNCOUNT1).TO_EQUAL(VNCOUNT2); + END; + + PROCEDURE TEST_PR_TEST_ME_NOT_NULL IS + VNCOUNT1 PLS_INTEGER; + VNCOUNT2 PLS_INTEGER; + VSNAME TO_TEST_ME.SNAME%TYPE; + BEGIN + -- In this test I will check that I do insert a value + -- when the parameter is not null. I futher check that + -- the procedure has inserted the value I specified. + SELECT COUNT(1) INTO VNCOUNT1 FROM TO_TEST_ME; + VSNAME := TO_CHAR(VNCOUNT1); + PKG_TEST_ME.PR_TEST_ME(VSNAME); + SELECT COUNT(1) INTO VNCOUNT2 FROM TO_TEST_ME; + + -- Check that I have inserted the value + UT.EXPECT(VNCOUNT1 + 1).TO_EQUAL(VNCOUNT2); + SELECT COUNT(1) INTO VNCOUNT2 FROM TO_TEST_ME T WHERE T.SNAME = VSNAME; + + -- Check that I inserted the one I said I would insert + UT.EXPECT(VNCOUNT2).TO_EQUAL(1); + DELETE FROM TO_TEST_ME T WHERE T.SNAME = VSNAME; + COMMIT; + END; + + PROCEDURE TEST_PR_TEST_ME_EXISTS IS + BEGIN + -- In case the value exists the procedure should fail with an exception. + BEGIN + PKG_TEST_ME.PR_TEST_ME('EXISTS'); + PKG_TEST_ME.PR_TEST_ME('EXISTS'); + EXCEPTION + WHEN OTHERS THEN + UT.FAIL('Unexpected exception raised'); + END; + END; + + PROCEDURE TEST_PR_TEST_ME_CURSOR IS + TYPE REF_CURSOR IS REF CURSOR; + VEXPECTED REF_CURSOR; + VACTUAL REF_CURSOR; + BEGIN + EXECUTE IMMEDIATE 'TRUNCATE TABLE CODE_OWNER.TO_TEST_ME'; + OPEN VEXPECTED FOR + SELECT T.SNAME FROM TO_TEST_ME T; + OPEN VACTUAL FOR + SELECT T.SNAME FROM TO_TEST_ME T; + UT.EXPECT(VEXPECTED).TO_(EQUAL(VACTUAL)); + END; + +END; +/ diff --git a/scripts/sql/owner_param/scripts/test/bar/packages/TEST_PKG_TEST_ME.pks b/scripts/sql/owner_param/scripts/test/bar/packages/TEST_PKG_TEST_ME.pks new file mode 100644 index 0000000..b0cdf54 --- /dev/null +++ b/scripts/sql/owner_param/scripts/test/bar/packages/TEST_PKG_TEST_ME.pks @@ -0,0 +1,86 @@ +CREATE OR REPLACE PACKAGE TESTS_OWNER.TEST_PKG_TEST_ME AS + -- %suite(TEST_PKG_TEST_ME) + -- %suitepath(plsql.examples) + -- + -- This package shows all the possibilities to unit test + -- your PL/SQL package. NOTE that it is not limited to + -- testing your package. You can do that on all your + -- procedure/functions... + -- + + /** + * This two parameters are used by the test framework in + * order to identify the test suite to run + */ + + /* + * This method is invoked once before any other method. + * It should contain all the setup code that is relevant + * for all your test. It might be inserting a register, + * creating a type, etc... + */ + -- %beforeall + PROCEDURE SETUP_GLOBAL; + + /* + * This method is invoked once after all other method. + * It can be used to clean up all the resources that + * you created in your script + */ + -- %afterall + PROCEDURE TEARDOWN_GLOBAL; + + /* + * This method is called once before each test. + */ + -- %beforeeach + PROCEDURE SETUP_TEST; + + /* + * This method is called once after each test. + */ + -- %aftereach + PROCEDURE TEARDOWN_TEST; + + /** + * This is a real test. The main test can declare a setup + * and teardown method in order to setup and cleanup things + * for that specific test. + */ + -- %test + -- %displayname(Checking if function ('1') returns 1) + -- %beforetest(SETUP_TEST_FC_INPUT_1) + -- %aftertest(TEARDOWN_TEST_FC_INPUT_1) + PROCEDURE TEST_FC_INPUT_1; + PROCEDURE SETUP_TEST_FC_INPUT_1; + PROCEDURE TEARDOWN_TEST_FC_INPUT_1; + + -- %test + -- %displayname(Checking if function ('0') returns 0) + PROCEDURE TEST_FC_INPUT_0; + + -- %test + -- %displayname(Checking if function (NULL) returns NULL) + PROCEDURE TEST_FC_INPUT_NULL; + + -- %test + -- %displayname(Checking if procedure (NULL) insert) + PROCEDURE TEST_PR_TEST_ME_NULL; + + -- %test + -- %displayname(Checking if procedure (NOT NULL) insert) + -- %rollback(manual) + PROCEDURE TEST_PR_TEST_ME_NOT_NULL; + + -- %test + -- %displayname(Checking if procedure (NOT NULL) insert while existing) + -- %rollback(manual) + PROCEDURE TEST_PR_TEST_ME_EXISTS; + + -- %test + -- %displayname(Demonstrating the use of cursor) + -- %rollback(manual) + PROCEDURE TEST_PR_TEST_ME_CURSOR; + +END; +/ diff --git a/scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pkb b/scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pkb new file mode 100644 index 0000000..331959d --- /dev/null +++ b/scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pkb @@ -0,0 +1,27 @@ +CREATE OR REPLACE PACKAGE BODY PKG_TEST_ME IS + -- + -- This + -- + FUNCTION FC_TEST_ME(PPARAM1 IN VARCHAR2) RETURN NUMBER IS + BEGIN + IF PPARAM1 IS NULL THEN + RETURN NULL; + ELSIF PPARAM1 = '1' THEN + RETURN 1; + ELSE + RETURN 0; + END IF; + END FC_TEST_ME; + + PROCEDURE PR_TEST_ME(PSNAME IN VARCHAR2) IS + BEGIN + IF PSNAME IS NULL THEN + NULL; + ELSE + INSERT INTO TO_TEST_ME (SNAME) VALUES (PSNAME); + COMMIT; + END IF; + END PR_TEST_ME; + +END PKG_TEST_ME; +/ diff --git a/scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pks b/scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pks new file mode 100644 index 0000000..26b2589 --- /dev/null +++ b/scripts/sql/simple/scripts/sources/APP.PKG_TEST_ME.pks @@ -0,0 +1,8 @@ +-- +-- This package is used TO demonstrate the utPL/SQL possibilities +-- +CREATE OR REPLACE PACKAGE PKG_TEST_ME AS + FUNCTION FC_TEST_ME(PPARAM1 IN VARCHAR2) RETURN NUMBER; + PROCEDURE PR_TEST_ME(PSNAME IN VARCHAR2); +END PKG_TEST_ME; +/ \ No newline at end of file diff --git a/scripts/sql/simple/scripts/sources/TO_TEST_ME.sql b/scripts/sql/simple/scripts/sources/TO_TEST_ME.sql new file mode 100644 index 0000000..b2e90d9 --- /dev/null +++ b/scripts/sql/simple/scripts/sources/TO_TEST_ME.sql @@ -0,0 +1,8 @@ +-- +-- This is a table used to demonstrate the UNIT test framework. +-- +CREATE TABLE TO_TEST_ME +( + SNAME VARCHAR2(10) +) +/ diff --git a/scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pkb b/scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pkb new file mode 100644 index 0000000..115bc15 --- /dev/null +++ b/scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pkb @@ -0,0 +1,126 @@ +CREATE OR REPLACE PACKAGE BODY TEST_PKG_TEST_ME AS + + --------------------------------------------------------------------------- + PROCEDURE SETUP_GLOBAL IS + BEGIN + -- Put here the code which is valid for all tests and that should be + -- executed once. + NULL; + END SETUP_GLOBAL; + + --------------------------------------------------------------------------- + PROCEDURE TEARDOWN_GLOBAL IS + BEGIN + -- Put here the code that should be called only once after all the test + -- have executed + NULL; + END TEARDOWN_GLOBAL; + + --------------------------------------------------------------------------- + PROCEDURE SETUP_TEST IS + BEGIN + -- Nothing to clean up globally + NULL; + END SETUP_TEST; + + PROCEDURE TEARDOWN_TEST IS + BEGIN + -- Nothing to clean up globally + NULL; + END TEARDOWN_TEST; + + PROCEDURE TEST_FC_INPUT_1 IS + BEGIN + -- Ok this is a real test where I check that the function return 1 + -- when called with a '1' parameter + UT.EXPECT(PKG_TEST_ME.FC_TEST_ME('1')).TO_EQUAL(1); + END; + + PROCEDURE SETUP_TEST_FC_INPUT_1 IS + BEGIN + -- Nothing to be done really + NULL; + END; + + PROCEDURE TEARDOWN_TEST_FC_INPUT_1 IS + BEGIN + -- Nothing to be done really + NULL; + END; + + PROCEDURE TEST_FC_INPUT_0 IS + BEGIN + -- Ok this is a real test where I check that the function return 0 + -- when called with a '0' parameter + UT.EXPECT(PKG_TEST_ME.FC_TEST_ME('0')).TO_EQUAL(0); + END; + + PROCEDURE TEST_FC_INPUT_NULL IS + BEGIN + -- Ok I check that the function return NULL + -- when called with a NULL parameter + UT.EXPECT(PKG_TEST_ME.FC_TEST_ME(NULL)).TO_BE_NULL; + END TEST_FC_INPUT_NULL; + + PROCEDURE TEST_PR_TEST_ME_NULL IS + VNCOUNT1 PLS_INTEGER; + VNCOUNT2 PLS_INTEGER; + BEGIN + -- In this example I check that the procedure does + -- not insert anything when passing it a NULL parameter + SELECT COUNT(1) INTO VNCOUNT1 FROM TO_TEST_ME; + PKG_TEST_ME.PR_TEST_ME(NULL); + SELECT COUNT(1) INTO VNCOUNT2 FROM TO_TEST_ME; + UT.EXPECT(VNCOUNT1).TO_EQUAL(VNCOUNT2); + END; + + PROCEDURE TEST_PR_TEST_ME_NOT_NULL IS + VNCOUNT1 PLS_INTEGER; + VNCOUNT2 PLS_INTEGER; + VSNAME TO_TEST_ME.SNAME%TYPE; + BEGIN + -- In this test I will check that I do insert a value + -- when the parameter is not null. I futher check that + -- the procedure has inserted the value I specified. + SELECT COUNT(1) INTO VNCOUNT1 FROM TO_TEST_ME; + VSNAME := TO_CHAR(VNCOUNT1); + PKG_TEST_ME.PR_TEST_ME(VSNAME); + SELECT COUNT(1) INTO VNCOUNT2 FROM TO_TEST_ME; + + -- Check that I have inserted the value + UT.EXPECT(VNCOUNT1 + 1).TO_EQUAL(VNCOUNT2); + SELECT COUNT(1) INTO VNCOUNT2 FROM TO_TEST_ME T WHERE T.SNAME = VSNAME; + + -- Check that I inserted the one I said I would insert + UT.EXPECT(VNCOUNT2).TO_EQUAL(1); + DELETE FROM TO_TEST_ME T WHERE T.SNAME = VSNAME; + COMMIT; + END; + + PROCEDURE TEST_PR_TEST_ME_EXISTS IS + BEGIN + -- In case the value exists the procedure should fail with an exception. + BEGIN + PKG_TEST_ME.PR_TEST_ME('EXISTS'); + PKG_TEST_ME.PR_TEST_ME('EXISTS'); + EXCEPTION + WHEN OTHERS THEN + UT.FAIL('Unexpected exception raised'); + END; + END; + + PROCEDURE TEST_PR_TEST_ME_CURSOR IS + TYPE REF_CURSOR IS REF CURSOR; + VEXPECTED REF_CURSOR; + VACTUAL REF_CURSOR; + BEGIN + EXECUTE IMMEDIATE 'TRUNCATE TABLE TO_TEST_ME'; + OPEN VEXPECTED FOR + SELECT T.SNAME FROM TO_TEST_ME T; + OPEN VACTUAL FOR + SELECT T.SNAME FROM TO_TEST_ME T; + UT.EXPECT(VEXPECTED).TO_(EQUAL(VACTUAL)); + END; + +END; +/ diff --git a/scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pks b/scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pks new file mode 100644 index 0000000..8a2b852 --- /dev/null +++ b/scripts/sql/simple/scripts/tests/APP.TEST_PKG_TEST_ME.pks @@ -0,0 +1,88 @@ +CREATE OR REPLACE PACKAGE TEST_PKG_TEST_ME AS + -- %suite(TEST_PKG_TEST_ME) + -- %suitepath(plsql.examples) + -- + -- This package shows all the possibilities to unit test + -- your PL/SQL package. NOTE that it is not limited to + -- testing your package. You can do that on all your + -- procedure/functions... + -- + + /** + * This two parameters are used by the test framework in + * order to identify the test suite to run + */ + + /* + * This method is invoked once before any other method. + * It should contain all the setup code that is relevant + * for all your test. It might be inserting a register, + * creating a type, etc... + */ + -- %beforeall + PROCEDURE SETUP_GLOBAL; + + /* + * This method is invoked once after all other method. + * It can be used to clean up all the resources that + * you created in your script + */ + -- %afterall + PROCEDURE TEARDOWN_GLOBAL; + + /* + * This method is called once before each test. + */ + -- %beforeeach + PROCEDURE SETUP_TEST; + + /* + * This method is called once after each test. + */ + -- %aftereach + PROCEDURE TEARDOWN_TEST; + + /** + * This is a real test. The main test can declare a setup + * and teardown method in order to setup and cleanup things + * for that specific test. + */ + -- %test + -- %displayname(Checking if function ('1') returns 1) + -- %beforetest(SETUP_TEST_FC_INPUT_1) + -- %aftertest(TEARDOWN_TEST_FC_INPUT_1) + PROCEDURE TEST_FC_INPUT_1; + PROCEDURE SETUP_TEST_FC_INPUT_1; + PROCEDURE TEARDOWN_TEST_FC_INPUT_1; + + -- %test + -- %displayname(Checking if function ('0') returns 0) + PROCEDURE TEST_FC_INPUT_0; + + -- %test + -- %displayname(Checking if function (NULL) returns NULL) + PROCEDURE TEST_FC_INPUT_NULL; + + -- %test + -- %displayname(Checking if procedure (NULL) insert) + PROCEDURE TEST_PR_TEST_ME_NULL; + + -- %test + -- %displayname(Checking if procedure (NOT NULL) insert) + -- %rollback(manual) + PROCEDURE TEST_PR_TEST_ME_NOT_NULL; + + -- %test + -- %displayname(Checking if procedure (NOT NULL) insert while existing) + -- %rollback(manual) + -- %tags(exists) + PROCEDURE TEST_PR_TEST_ME_EXISTS; + + -- %test + -- %displayname(Demonstrating the use of cursor) + -- %rollback(manual) + -- %tags(cursor) + PROCEDURE TEST_PR_TEST_ME_CURSOR; + +END; +/ diff --git a/settings.gradle.kts b/settings.gradle.kts deleted file mode 100644 index 2fd8241..0000000 --- a/settings.gradle.kts +++ /dev/null @@ -1,2 +0,0 @@ - -rootProject.name = "utPLSQL-java-api" diff --git a/src/main/java/org/utplsql/api/FileMapper.java b/src/main/java/org/utplsql/api/FileMapper.java deleted file mode 100644 index 150dca3..0000000 --- a/src/main/java/org/utplsql/api/FileMapper.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.utplsql.api; - - -import oracle.jdbc.OracleConnection; -import oracle.jdbc.OracleTypes; - -import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public final class FileMapper { - - private FileMapper() { - } - - /** - * Call the database api to build the custom file mappings. - */ - public static Array buildFileMappingArray( - Connection conn, FileMapperOptions mapperOptions) throws SQLException { - OracleConnection oraConn = conn.unwrap(OracleConnection.class); - - Map> typeMap = conn.getTypeMap(); - typeMap.put(CustomTypes.UT_FILE_MAPPING, FileMapping.class); - typeMap.put(CustomTypes.UT_KEY_VALUE_PAIR, KeyValuePair.class); - conn.setTypeMap(typeMap); - - CallableStatement callableStatement = conn.prepareCall( - "BEGIN " + - "? := ut_file_mapper.build_file_mappings(" + - "a_object_owner => ?, " + - "a_file_paths => ?, " + - "a_file_to_object_type_mapping => ?, " + - "a_regex_pattern => ?, " + - "a_object_owner_subexpression => ?, " + - "a_object_name_subexpression => ?, " + - "a_object_type_subexpression => ?); " + - "END;"); - - int paramIdx = 0; - callableStatement.registerOutParameter(++paramIdx, OracleTypes.ARRAY, CustomTypes.UT_FILE_MAPPINGS); - - if (mapperOptions.getObjectOwner() == null) { - callableStatement.setNull(++paramIdx, Types.VARCHAR); - } else { - callableStatement.setString(++paramIdx, mapperOptions.getObjectOwner()); - } - - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_VARCHAR2_LIST, mapperOptions.getFilePaths().toArray())); - - if (mapperOptions.getTypeMappings() == null) { - callableStatement.setNull(++paramIdx, Types.ARRAY, CustomTypes.UT_KEY_VALUE_PAIRS); - } else { - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_KEY_VALUE_PAIRS, mapperOptions.getTypeMappings().toArray())); - } - - if (mapperOptions.getRegexPattern() == null) { - callableStatement.setNull(++paramIdx, Types.VARCHAR); - } else { - callableStatement.setString(++paramIdx, mapperOptions.getRegexPattern()); - } - - if (mapperOptions.getOwnerSubExpression() == null) { - callableStatement.setNull(++paramIdx, Types.INTEGER); - } else { - callableStatement.setInt(++paramIdx, mapperOptions.getOwnerSubExpression()); - } - - if (mapperOptions.getNameSubExpression() == null) { - callableStatement.setNull(++paramIdx, Types.INTEGER); - } else { - callableStatement.setInt(++paramIdx, mapperOptions.getNameSubExpression()); - } - - if (mapperOptions.getTypeSubExpression() == null) { - callableStatement.setNull(++paramIdx, Types.INTEGER); - } else { - callableStatement.setInt(++paramIdx, mapperOptions.getTypeSubExpression()); - } - - callableStatement.execute(); - return callableStatement.getArray(1); - } - - public static List buildFileMappingList( - Connection conn, FileMapperOptions mapperOptions) throws SQLException { - java.sql.Array fileMappings = buildFileMappingArray(conn, mapperOptions); - - List mappingList = new ArrayList<>(); - for (Object obj : (Object[]) fileMappings.getArray()) { - mappingList.add((FileMapping) obj); - } - - return mappingList; - } - -} diff --git a/src/main/java/org/utplsql/api/JavaApiVersionInfo.java b/src/main/java/org/utplsql/api/JavaApiVersionInfo.java index 503b84d..48e529b 100644 --- a/src/main/java/org/utplsql/api/JavaApiVersionInfo.java +++ b/src/main/java/org/utplsql/api/JavaApiVersionInfo.java @@ -7,7 +7,7 @@ /** * This class is getting updated automatically by the build process. - * Please do not update its constants manually cause they will be overwritten. + * Please do not update its constants manually because they will be overwritten. * * @author pesse */ @@ -18,10 +18,11 @@ public class JavaApiVersionInfo { static { try { - - try (InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-api.version"); - BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { - MAVEN_PROJECT_VERSION = reader.readLine(); + try (InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-api.version")) { + assert in != null; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { + MAVEN_PROJECT_VERSION = reader.readLine(); + } } } catch (IOException e) { System.out.println("WARNING: Could not get Version information!"); diff --git a/src/main/java/org/utplsql/api/ResourceUtil.java b/src/main/java/org/utplsql/api/ResourceUtil.java index 9f6c225..d4ac0b3 100644 --- a/src/main/java/org/utplsql/api/ResourceUtil.java +++ b/src/main/java/org/utplsql/api/ResourceUtil.java @@ -1,18 +1,11 @@ package org.utplsql.api; -import com.sun.nio.zipfs.ZipPath; -import org.utplsql.api.reporter.CoverageHTMLReporter; - import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.*; -import java.util.ArrayList; +import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; /** * Helper class for dealing with Resources @@ -25,63 +18,48 @@ private ResourceUtil() { } /** - * Returns the Path to a resource so it is walkable no matter if it's inside a jar or on the file system + * Copy directory from a jar file to the destination folder * - * @param resourceName The name of the resource - * @return Path to the resource, either in JAR or on file system - * @throws IOException - * @throws URISyntaxException + * @param resourceAsPath The resource to get children from + * @param targetDirectory If set to true it will only return files, not directories */ - public static Path getPathToResource(String resourceName) throws IOException, URISyntaxException { - URI uri = CoverageHTMLReporter.class.getResource(resourceName).toURI(); - Path myPath; - if (uri.getScheme().equalsIgnoreCase("jar")) { - FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap()); - myPath = fileSystem.getPath(resourceName); - } else { - myPath = Paths.get(uri); + public static void copyResources(Path resourceAsPath, Path targetDirectory) { + try { + String resourceName = "/" + resourceAsPath; + Files.createDirectories(targetDirectory); + URI uri = ResourceUtil.class.getResource(resourceName).toURI(); + Path myPath; + if (uri.getScheme().equalsIgnoreCase("jar")) { + try (FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap())) { + myPath = fileSystem.getPath(resourceName); + copyRecursive(myPath, targetDirectory); + } + } else { + myPath = Paths.get(uri); + copyRecursive(myPath, targetDirectory); + } + } catch (IOException | URISyntaxException e) { + throw new RuntimeException(e); } - - return myPath; } - /** - * Returns the relative paths of all children of the given resource. Relative path begins from the first atom of the given path. - * - * @param resourceAsPath The resource to get children from - * @param filesOnly If set to true it will only return files, not directories - * @return List of relative Paths to the children - * @throws IOException - * @throws URISyntaxException - */ - public static List getListOfChildren(Path resourceAsPath, boolean filesOnly) throws IOException, URISyntaxException { - - Path resourcePath = getPathToResource("/" + resourceAsPath.toString()); - int relativeStartIndex = resourcePath.getNameCount() - resourceAsPath.getNameCount(); + private static void copyRecursive(Path from, Path targetDirectory) throws IOException { + Files.walkFileTree(from, new SimpleFileVisitor() { - final List result = new ArrayList<>(); - - if (resourcePath instanceof ZipPath) { - try (ZipFile zf = new ZipFile(resourcePath.getFileSystem().toString())) { - - for (Enumeration list = zf.entries(); list.hasMoreElements(); ) { - ZipEntry entry = (ZipEntry) list.nextElement(); - // Get entry-path with root element so we can compare it - Path entryPath = resourcePath.getRoot().resolve(resourcePath.getFileSystem().getPath(entry.toString())); - - if (entryPath.startsWith(resourcePath) && (!filesOnly || !entry.isDirectory())) { - result.add(entryPath.subpath(relativeStartIndex, entryPath.getNameCount())); - } - } + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + super.preVisitDirectory(dir, attrs); + Path currentTarget = targetDirectory.resolve(from.relativize(dir).toString()); + Files.createDirectories(currentTarget); + return FileVisitResult.CONTINUE; } - resourcePath.getFileSystem().close(); - } else { - Files.walk(resourcePath) - .filter(p -> !filesOnly || p.toFile().isFile()) - .forEach(p -> result.add(p.subpath(relativeStartIndex, p.getNameCount()))); - } - - return result; + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + super.visitFile(file, attrs); + Files.copy(file, targetDirectory.resolve(from.relativize(file).toString()), StandardCopyOption.REPLACE_EXISTING); + return FileVisitResult.CONTINUE; + } + }); } -} \ No newline at end of file +} diff --git a/src/main/java/org/utplsql/api/TestRunner.java b/src/main/java/org/utplsql/api/TestRunner.java index c330f0c..3a3f6e1 100644 --- a/src/main/java/org/utplsql/api/TestRunner.java +++ b/src/main/java/org/utplsql/api/TestRunner.java @@ -16,6 +16,7 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.concurrent.*; @@ -73,6 +74,11 @@ public TestRunner addCoverageScheme(String coverageScheme) { return this; } + public TestRunner addCoverageSchemes(Collection schemaNames) { + this.options.coverageSchemes.addAll(schemaNames); + return this; + } + public TestRunner includeObject(String obj) { options.includeObjects.add(obj); return this; @@ -93,6 +99,26 @@ public TestRunner excludeObjects(List obj) { return this; } + public TestRunner includeSchemaExpr(String expr) { + options.includeSchemaExpr = expr; + return this; + } + + public TestRunner excludeSchemaExpr(String expr) { + options.excludeSchemaExpr = expr; + return this; + } + + public TestRunner includeObjectExpr(String expr) { + options.includeObjectExpr = expr; + return this; + } + + public TestRunner excludeObjectExpr(String expr) { + options.excludeObjectExpr = expr; + return this; + } + public TestRunner sourceMappingOptions(FileMapperOptions mapperOptions) { options.sourceMappingOptions = mapperOptions; return this; @@ -118,6 +144,36 @@ public TestRunner setReporterFactory(ReporterFactory reporterFactory) { return this; } + public TestRunner randomTestOrder(boolean randomTestOrder) { + this.options.randomTestOrder = randomTestOrder; + return this; + } + + public TestRunner randomTestOrderSeed(Integer seed) { + this.options.randomTestOrderSeed = seed; + if (seed != null) this.options.randomTestOrder = true; + return this; + } + + public TestRunner addTag(String tag) { + this.options.tags.add(tag); + return this; + } + + public TestRunner addTags(Collection tags) { + this.options.tags.addAll(tags); + return this; + } + + public TestRunner oraStuckTimeout(Integer oraStuckTimeout) { + this.options.oraStuckTimeout = oraStuckTimeout; + return this; + } + + public TestRunnerOptions getOptions() { + return options; + } + private void delayedAddReporters() { if (reporterFactory != null) { reporterNames.forEach(this::addReporter); @@ -128,10 +184,10 @@ private void delayedAddReporters() { private void handleException(Throwable e) throws SQLException { // Just pass exceptions already categorized - if ( e instanceof UtPLSQLNotInstalledException ) throw (UtPLSQLNotInstalledException)e; - else if ( e instanceof SomeTestsFailedException ) throw (SomeTestsFailedException)e; - else if ( e instanceof OracleCreateStatmenetStuckException ) throw (OracleCreateStatmenetStuckException)e; - // Categorize exceptions + if (e instanceof UtPLSQLNotInstalledException) throw (UtPLSQLNotInstalledException) e; + else if (e instanceof SomeTestsFailedException) throw (SomeTestsFailedException) e; + else if (e instanceof OracleCreateStatmenetStuckException) throw (OracleCreateStatmenetStuckException) e; + // Categorize exceptions else if (e instanceof SQLException) { SQLException sqlException = (SQLException) e; if (sqlException.getErrorCode() == SomeTestsFailedException.ERROR_CODE) { @@ -152,8 +208,12 @@ public void run(Connection conn) throws SQLException { DatabaseInformation databaseInformation = new DefaultDatabaseInformation(); - compatibilityProxy = new CompatibilityProxy(conn, options.skipCompatibilityCheck, databaseInformation); - logger.info("Running on utPLSQL {}", compatibilityProxy.getDatabaseVersion()); + if (options.skipCompatibilityCheck) { + compatibilityProxy = new CompatibilityProxy(conn, Version.LATEST, databaseInformation); + } else { + compatibilityProxy = new CompatibilityProxy(conn, databaseInformation); + } + logger.info("Running on utPLSQL {}", compatibilityProxy.getVersionDescription()); if (reporterFactory == null) { reporterFactory = ReporterFactory.createDefault(compatibilityProxy); @@ -180,7 +240,7 @@ public void run(Connection conn) throws SQLException { TestRunnerStatement testRunnerStatement = null; try { - testRunnerStatement = initStatementWithTimeout(conn); + testRunnerStatement = (options.oraStuckTimeout > 0) ? initStatementWithTimeout(conn, options.oraStuckTimeout) : initStatement(conn); logger.info("Running tests"); testRunnerStatement.execute(); logger.info("Running tests finished."); @@ -194,15 +254,20 @@ public void run(Connection conn) throws SQLException { } } - private TestRunnerStatement initStatementWithTimeout( Connection conn ) throws OracleCreateStatmenetStuckException, SQLException { + private TestRunnerStatement initStatement(Connection conn) throws SQLException { + return compatibilityProxy.getTestRunnerStatement(options, conn); + } + + private TestRunnerStatement initStatementWithTimeout(Connection conn, int timeout) throws SQLException { + TestRunnerStatement testRunnerStatement; ExecutorService executor = Executors.newSingleThreadExecutor(); Callable callable = () -> compatibilityProxy.getTestRunnerStatement(options, conn); Future future = executor.submit(callable); // We want to leave the statement open in case of stuck scenario - TestRunnerStatement testRunnerStatement = null; + testRunnerStatement = null; try { - testRunnerStatement = future.get(2, TimeUnit.SECONDS); + testRunnerStatement = future.get(timeout, TimeUnit.SECONDS); } catch (TimeoutException e) { logger.error("Detected Oracle driver stuck during Statement initialization"); executor.shutdownNow(); @@ -236,7 +301,7 @@ private void validateReporter(Connection conn, Reporter reporter) throws SQLExce */ public Version getUsedDatabaseVersion() { if (compatibilityProxy != null) { - return compatibilityProxy.getDatabaseVersion(); + return compatibilityProxy.getUtPlsqlVersion(); } else { return null; } diff --git a/src/main/java/org/utplsql/api/TestRunnerOptions.java b/src/main/java/org/utplsql/api/TestRunnerOptions.java index 059d9ba..615e308 100644 --- a/src/main/java/org/utplsql/api/TestRunnerOptions.java +++ b/src/main/java/org/utplsql/api/TestRunnerOptions.java @@ -4,7 +4,9 @@ import java.nio.charset.Charset; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; /** * Holds the various possible options of TestRunner @@ -19,10 +21,22 @@ public class TestRunnerOptions { public final List testFiles = new ArrayList<>(); public final List includeObjects = new ArrayList<>(); public final List excludeObjects = new ArrayList<>(); + public String includeSchemaExpr; + public String excludeSchemaExpr; + public String includeObjectExpr; + public String excludeObjectExpr; public boolean colorConsole = false; public FileMapperOptions sourceMappingOptions; public FileMapperOptions testMappingOptions; public boolean failOnErrors = false; public boolean skipCompatibilityCheck = false; public String clientCharacterSet = Charset.defaultCharset().toString(); + public boolean randomTestOrder = false; + public Integer randomTestOrderSeed; + public final Set tags = new LinkedHashSet<>(); + public Integer oraStuckTimeout = 0; + + public String getTagsAsString() { + return String.join(",", tags); + } } diff --git a/src/main/java/org/utplsql/api/Version.java b/src/main/java/org/utplsql/api/Version.java index cc2ef3e..5aaabfa 100644 --- a/src/main/java/org/utplsql/api/Version.java +++ b/src/main/java/org/utplsql/api/Version.java @@ -24,12 +24,25 @@ public class Version implements Comparable { public final static Version V3_0_2 = new Version("3.0.2", 3, 0, 2, null, true); public final static Version V3_0_3 = new Version("3.0.3", 3, 0, 3, null, true); public final static Version V3_0_4 = new Version("3.0.4", 3, 0, 4, null, true); - public final static Version V3_1_0 = new Version("3.1.0", 3, 1, 0, null, true); - public final static Version V3_1_1 = new Version("3.1.1", 3, 1, 1, null, true); - public final static Version V3_1_2 = new Version("3.1.2", 3, 1, 2, null, true); + public final static Version V3_1_0 = new Version("3.1.0", 3, 1, 0, 1847, true); + public final static Version V3_1_1 = new Version("3.1.1", 3, 1, 1, 1865, true); + public final static Version V3_1_2 = new Version("3.1.2", 3, 1, 2, 2130, true); + public final static Version V3_1_3 = new Version("3.1.3", 3, 1, 3, 2398, true); + public final static Version V3_1_4 = new Version("3.1.4", 3, 1, 4, 2223, true); + public final static Version V3_1_5 = new Version("3.1.5", 3, 1, 5, 2707, true); + public final static Version V3_1_6 = new Version("3.1.6", 3, 1, 6, 2729, true); + public final static Version V3_1_7 = new Version("3.1.7", 3, 1, 7, 3085, true); + public final static Version V3_1_8 = new Version("3.1.8", 3, 1, 8, 3188, true); + public final static Version V3_1_9 = new Version("3.1.9", 3, 1, 9, 3268, true); + public final static Version V3_1_10 = new Version("3.1.10", 3, 1, 10, 3347, true); + public final static Version V3_1_11 = new Version("3.1.11", 3, 1, 11, 3557, true); + public final static Version V3_1_12 = new Version("3.1.12", 3, 1, 12, 3876, true); + public final static Version V3_1_13 = new Version("3.1.13", 3, 1, 13, 3592, true); + private final static Map knownVersions = - Stream.of(V3_0_0, V3_0_1, V3_0_2, V3_0_3, V3_0_4, V3_1_0, V3_1_1, V3_1_2) + Stream.of(V3_0_0, V3_0_1, V3_0_2, V3_0_3, V3_0_4, V3_1_0, V3_1_1, V3_1_2, V3_1_3, V3_1_4, V3_1_5, V3_1_6, V3_1_7, V3_1_8, V3_1_9, V3_1_10, V3_1_11, V3_1_13) .collect(toMap(Version::toString, Function.identity())); + public final static Version LATEST = V3_1_13; private final String origString; private final Integer major; @@ -50,10 +63,13 @@ private Version(String origString, @Nullable Integer major, @Nullable Integer mi /** * Use {@link Version#create} factory method instead * For removal + * + * @param versionString Version as String */ @Deprecated() public Version(String versionString) { - assert versionString != null; + Objects.requireNonNull(versionString); + Version dummy = parseVersionString(versionString); this.origString = dummy.origString; @@ -99,8 +115,7 @@ private static Version parseVersionString(String origString) { // We need a valid major version as minimum requirement for a Version object to be valid valid = major != null; } - } catch (NumberFormatException e) { - valid = false; + } catch (NumberFormatException ignore) { } return new Version(origString, major, minor, bugfix, build, valid); @@ -138,7 +153,7 @@ public boolean isValid() { /** * Returns a normalized form of the parsed version information * - * @return + * @return normalized string */ public String getNormalizedString() { if (isValid()) { @@ -161,10 +176,14 @@ public String getNormalizedString() { } private int compareToWithNulls(@Nullable Integer i1, @Nullable Integer i2) { + return compareToWithNulls(i1, i2, false); + } + + private int compareToWithNulls(@Nullable Integer i1, @Nullable Integer i2, boolean nullMeansEqual) { if (i1 == null && i2 == null) { return 0; } else if (i1 == null) { - return -1; + return nullMeansEqual ? 0 : -1; } else if (i2 == null) { return 1; } else { @@ -174,29 +193,32 @@ private int compareToWithNulls(@Nullable Integer i1, @Nullable Integer i2) { @Override public int compareTo(Version o) { + return compareTo(o, false); + } + + public int compareTo(Version o, boolean nullMeansEqual) { int curResult; if (isValid() && o.isValid()) { - curResult = compareToWithNulls(getMajor(), o.getMajor()); + curResult = compareToWithNulls(getMajor(), o.getMajor(), nullMeansEqual); if (curResult != 0) { return curResult; } - curResult = compareToWithNulls(getMinor(), o.getMinor()); + curResult = compareToWithNulls(getMinor(), o.getMinor(), nullMeansEqual); if (curResult != 0) { return curResult; } - curResult = compareToWithNulls(getBugfix(), o.getBugfix()); + curResult = compareToWithNulls(getBugfix(), o.getBugfix(), nullMeansEqual); if (curResult != 0) { return curResult; } - curResult = compareToWithNulls(getBuild(), o.getBuild()); - if (curResult != 0) { - return curResult; - } + curResult = compareToWithNulls(getBuild(), o.getBuild(), nullMeansEqual); + + return curResult; } return 0; @@ -214,33 +236,60 @@ private void versionsAreValid(Version v) throws InvalidVersionException { /** * Compares this version to a given version and returns true if this version is greater or equal than the given one - * Throws an InvalidVersionException if either this or the given version are invalid + * If one of the version parts of the base version is null, this level is assumed equal no matter the comparing level's version part + * Throws an {@link InvalidVersionException} if either this or the given version are invalid * * @param v Version to compare with - * @return - * @throws InvalidVersionException + * @return true if is greater or equal + * @throws InvalidVersionException If the version does not match */ public boolean isGreaterOrEqualThan(Version v) throws InvalidVersionException { versionsAreValid(v); - return compareTo(v) >= 0; + return compareTo(v, true) >= 0; } - + /** + * Compares this version to a given version and returns true if this version is greater than the given one + * If one of the version parts of the base version is null, this level is assumed equal no matter the comparing level's version part + * Throws an {@link InvalidVersionException} if either this or the given version are invalid + * + * @param v Version to compare with + * @return true if is greater + * @throws InvalidVersionException If the version does not match + */ public boolean isGreaterThan(Version v) throws InvalidVersionException { versionsAreValid(v); return compareTo(v) > 0; } + /** + * Compares this version to a given version and returns true if this version is less or equal than the given one + * If one of the version parts of the base version is null, this level is assumed equal no matter the comparing level's version part + * Throws an {@link InvalidVersionException} if either this or the given version are invalid + * + * @param v Version to compare with + * @return if version is less or equal + * @throws InvalidVersionException If version is invalid + */ public boolean isLessOrEqualThan(Version v) throws InvalidVersionException { versionsAreValid(v); - return compareTo(v) <= 0; + return compareTo(v, true) <= 0; } + /** + * Compares this version to a given version and returns true if this version is less than the given one + * If one of the version parts of the base version is null, this level is assumed equal no matter the comparing level's version part + * Throws an {@link InvalidVersionException} if either this or the given version are invalid + * + * @param v Version to compare with + * @return if version is less + * @throws InvalidVersionException If version is invalid + */ public boolean isLessThan(Version v) throws InvalidVersionException { versionsAreValid(v); diff --git a/src/main/java/org/utplsql/api/compatibility/CompatibilityProxy.java b/src/main/java/org/utplsql/api/compatibility/CompatibilityProxy.java index 0c184a0..eb68f23 100644 --- a/src/main/java/org/utplsql/api/compatibility/CompatibilityProxy.java +++ b/src/main/java/org/utplsql/api/compatibility/CompatibilityProxy.java @@ -11,6 +11,7 @@ import org.utplsql.api.testRunner.TestRunnerStatement; import org.utplsql.api.testRunner.TestRunnerStatementProvider; +import javax.annotation.Nullable; import java.sql.Connection; import java.sql.SQLException; import java.util.Objects; @@ -25,30 +26,42 @@ public class CompatibilityProxy { public static final String UTPLSQL_COMPATIBILITY_VERSION = "3"; - private static final String UTPLSQL_API_VERSION = "3.1.1"; private final DatabaseInformation databaseInformation; - private Version databaseVersion; + private Version utPlsqlVersion; + private final Version realDbPlsqlVersion; private boolean compatible = false; public CompatibilityProxy(Connection conn) throws SQLException { - this(conn, false, null); - } - - public CompatibilityProxy(Connection conn, DatabaseInformation databaseInformation) throws SQLException { - this(conn, false, databaseInformation); + this(conn, null, null); } + @Deprecated public CompatibilityProxy(Connection conn, boolean skipCompatibilityCheck) throws SQLException { this(conn, skipCompatibilityCheck, null); } - public CompatibilityProxy(Connection conn, boolean skipCompatibilityCheck, DatabaseInformation databaseInformation) throws SQLException { + @Deprecated + public CompatibilityProxy(Connection conn, boolean skipCompatibilityCheck, @Nullable DatabaseInformation databaseInformation) throws SQLException { + this(conn, skipCompatibilityCheck ? Version.LATEST : null, databaseInformation); + } + + public CompatibilityProxy(Connection conn, @Nullable DatabaseInformation databaseInformation) throws SQLException { + this(conn, null, databaseInformation); + } + + public CompatibilityProxy(Connection conn, @Nullable Version assumedUtPlsVersion) throws SQLException { + this(conn, assumedUtPlsVersion, null); + } + + public CompatibilityProxy(Connection conn, @Nullable Version assumedUtPlsqlVersion, @Nullable DatabaseInformation databaseInformation) throws SQLException { this.databaseInformation = (databaseInformation != null) ? databaseInformation : new DefaultDatabaseInformation(); - if (skipCompatibilityCheck) { - doExpectCompatibility(); + realDbPlsqlVersion = this.databaseInformation.getUtPlsqlFrameworkVersion(conn); + if (assumedUtPlsqlVersion != null) { + utPlsqlVersion = assumedUtPlsqlVersion; + compatible = utPlsqlVersion.getNormalizedString().startsWith(UTPLSQL_COMPATIBILITY_VERSION); } else { doCompatibilityCheckWithDatabase(conn); } @@ -58,22 +71,22 @@ public CompatibilityProxy(Connection conn, boolean skipCompatibilityCheck, Datab * Receives the current framework version from database and checks - depending on the framework version - whether * the API version is compatible or not. * - * @param conn - * @throws SQLException + * @param conn {@link Connection} + * @throws DatabaseNotCompatibleException if the database is not compatible */ - private void doCompatibilityCheckWithDatabase(Connection conn) throws SQLException { - databaseVersion = databaseInformation.getUtPlsqlFrameworkVersion(conn); + private void doCompatibilityCheckWithDatabase(Connection conn) throws DatabaseNotCompatibleException { + utPlsqlVersion = realDbPlsqlVersion; Version clientVersion = Version.create(UTPLSQL_COMPATIBILITY_VERSION); - if (databaseVersion == null) { + if (utPlsqlVersion == null) { throw new DatabaseNotCompatibleException("Could not get database version", clientVersion, null, null); } - if (databaseVersion.getMajor() == null) { - throw new DatabaseNotCompatibleException("Illegal database version: " + databaseVersion.toString(), clientVersion, databaseVersion, null); + if (utPlsqlVersion.getMajor() == null) { + throw new DatabaseNotCompatibleException("Illegal database version: " + utPlsqlVersion.toString(), clientVersion, utPlsqlVersion, null); } - if (OptionalFeatures.FRAMEWORK_COMPATIBILITY_CHECK.isAvailableFor(databaseVersion)) { + if (OptionalFeatures.FRAMEWORK_COMPATIBILITY_CHECK.isAvailableFor(utPlsqlVersion)) { try { compatible = versionCompatibilityCheck(conn, UTPLSQL_COMPATIBILITY_VERSION, null); } catch (SQLException e) { @@ -84,14 +97,6 @@ private void doCompatibilityCheckWithDatabase(Connection conn) throws SQLExcepti } } - /** - * Just prepare the proxy to expect compatibility, expecting the database framework to be the same version as the API - */ - private void doExpectCompatibility() { - databaseVersion = Version.create(UTPLSQL_API_VERSION); - compatible = true; - } - /** * Check the utPLSQL version compatibility. * @@ -113,27 +118,29 @@ private boolean versionCompatibilityCheck(Connection conn, String requested, Str } /** - * Simple fallback check for compatiblity: Major and Minor version must be equal + * Simple fallback check for compatibility: Major and Minor version must be equal * - * @param requested - * @return + * @param versionRequested Requested version + * @return weather the version is available or not */ - private boolean versionCompatibilityCheckPre303(String requested) { - Version requestedVersion = Version.create(requested); + private boolean versionCompatibilityCheckPre303(String versionRequested) { + Version requestedVersion = Version.create(versionRequested); - Objects.requireNonNull(databaseVersion.getMajor(), "Illegal database Version: " + databaseVersion.toString()); - return databaseVersion.getMajor().equals(requestedVersion.getMajor()) + Objects.requireNonNull(utPlsqlVersion.getMajor(), "Illegal database Version: " + utPlsqlVersion.toString()); + return Objects.equals(utPlsqlVersion.getMajor(), requestedVersion.getMajor()) && (requestedVersion.getMinor() == null - || requestedVersion.getMinor().equals(databaseVersion.getMinor())); + || requestedVersion.getMinor().equals(utPlsqlVersion.getMinor())); } /** * Checks if actual API-version is compatible with utPLSQL database version and throws a DatabaseNotCompatibleException if not * Throws a DatabaseNotCompatibleException if version compatibility can not be checked. + * + * @throws DatabaseNotCompatibleException if versions are not compatible */ public void failOnNotCompatible() throws DatabaseNotCompatibleException { if (!isCompatible()) { - throw new DatabaseNotCompatibleException(databaseVersion); + throw new DatabaseNotCompatibleException(utPlsqlVersion); } } @@ -141,31 +148,48 @@ public boolean isCompatible() { return compatible; } + @Deprecated public Version getDatabaseVersion() { - return databaseVersion; + return utPlsqlVersion; + } + + public Version getUtPlsqlVersion() { + return utPlsqlVersion; + } + + public Version getRealDbPlsqlVersion() { + return realDbPlsqlVersion; + } + + public String getVersionDescription() { + if (utPlsqlVersion != realDbPlsqlVersion) { + return realDbPlsqlVersion.toString() + " (Assumed: " + utPlsqlVersion.toString() + ")"; + } else { + return utPlsqlVersion.toString(); + } } /** * Returns a TestRunnerStatement compatible with the current framework * - * @param options - * @param conn - * @return - * @throws SQLException + * @param options {@link TestRunnerOptions} + * @param conn {@link Connection} + * @return TestRunnerStatement + * @throws SQLException if there are problems with the database access */ public TestRunnerStatement getTestRunnerStatement(TestRunnerOptions options, Connection conn) throws SQLException { - return TestRunnerStatementProvider.getCompatibleTestRunnerStatement(databaseVersion, options, conn); + return TestRunnerStatementProvider.getCompatibleTestRunnerStatement(utPlsqlVersion, options, conn); } /** * Returns an OutputBuffer compatible with the current framework * - * @param reporter - * @param conn - * @return - * @throws SQLException + * @param reporter {@link Reporter} + * @param conn {@link Connection} + * @return OutputBuffer + * @throws SQLException if there are problems with the database access */ public OutputBuffer getOutputBuffer(Reporter reporter, Connection conn) throws SQLException { - return OutputBufferProvider.getCompatibleOutputBuffer(databaseVersion, reporter, conn); + return OutputBufferProvider.getCompatibleOutputBuffer(utPlsqlVersion, reporter, conn); } } diff --git a/src/main/java/org/utplsql/api/compatibility/OptionalFeatures.java b/src/main/java/org/utplsql/api/compatibility/OptionalFeatures.java index 629ec5b..8462b95 100644 --- a/src/main/java/org/utplsql/api/compatibility/OptionalFeatures.java +++ b/src/main/java/org/utplsql/api/compatibility/OptionalFeatures.java @@ -10,7 +10,11 @@ public enum OptionalFeatures { FAIL_ON_ERROR("3.0.3.1266", null), FRAMEWORK_COMPATIBILITY_CHECK("3.0.3.1266", null), - CUSTOM_REPORTERS("3.1.0.1849", null); + CUSTOM_REPORTERS("3.1.0.1849", null), + CLIENT_CHARACTER_SET("3.1.2.2130", null), + RANDOM_EXECUTION_ORDER("3.1.7.2795", null), + TAGS("3.1.7.3006", null), + EXPR("3.1.13", null); private final Version minVersion; private final Version maxVersion; @@ -32,6 +36,10 @@ public boolean isAvailableFor(Version version) { public boolean isAvailableFor(Connection conn) throws SQLException { CompatibilityProxy proxy = new CompatibilityProxy(conn); - return isAvailableFor(proxy.getDatabaseVersion()); + return isAvailableFor(proxy.getUtPlsqlVersion()); } + + public Version getMinVersion() { return minVersion; } + + public Version getMaxVersion() { return maxVersion; } } diff --git a/src/main/java/org/utplsql/api/db/DynamicParameterList.java b/src/main/java/org/utplsql/api/db/DynamicParameterList.java new file mode 100644 index 0000000..c6df04c --- /dev/null +++ b/src/main/java/org/utplsql/api/db/DynamicParameterList.java @@ -0,0 +1,220 @@ +package org.utplsql.api.db; + +import oracle.jdbc.OracleConnection; + +import java.sql.CallableStatement; +import java.sql.SQLException; +import java.sql.Types; +import java.util.LinkedHashMap; +import java.util.stream.Collectors; + +/** Lets you build a list of parameters for a CallableStatement + *
+ * Create it with the Builder (DynamicParameterList.builder()) + * + * @author pesse + */ +public class DynamicParameterList { + + private final LinkedHashMap params; + + interface DynamicParameter { + void setParam( CallableStatement statement, int index ) throws SQLException; + + default String getSql( String key ) { + return key + " => ?"; + } + } + + private DynamicParameterList(LinkedHashMap params) { + this.params = params; + } + + /** Returns the SQL of this ParameterList as comma-separated list of the parameter identifiers:
+ * + * e.g. "a_parameter1 => ?, a_parameter2 => ?" + * + * @return comma-separated list of parameter identifiers + */ + public String getSql() { + return params.entrySet().stream() + .map(e -> e.getValue().getSql(e.getKey())) + .collect(Collectors.joining(", ")); + } + + /** Sets the contained parameters in the order they were added to the given statement by index, starting with the given one + * + * @param statement The statement to set the parameters to + * @param startIndex The index to start with + * @throws SQLException SQLException of the underlying statement.setX methods + */ + public void setParamsStartWithIndex(CallableStatement statement, int startIndex ) throws SQLException { + int index = startIndex; + for ( DynamicParameter param : params.values() ) { + param.setParam(statement, index++); + } + } + + /** Returns a builder to create a DynamicParameterList + * + * @return Builder + */ + public static DynamicParameterListBuilder builder() { + return new DynamicParameterListBuilder(); + } + + /** Builder-class for DynamicParameterList + *
+ * Usage: + *
+     *  DynamicParameterList.builder()
+     *      .add("parameter1", "StringParameter")
+     *      .addIfNotEmpty("parameter2", 123)
+     *      .build();
+     * 
+ * + * @author pesse + */ + public static class DynamicParameterListBuilder { + + private final LinkedHashMap params = new LinkedHashMap<>(); + + private DynamicParameterListBuilder() { + + } + + public DynamicParameterListBuilder add(String identifier, String value ) { + params.put(identifier, new DynamicParameterList.DynamicStringParameter(value)); + return this; + } + + public DynamicParameterListBuilder addIfNotEmpty(String identifier, String value ) { + if ( value != null && !value.isEmpty() ) { + add(identifier, value); + } + return this; + } + + public DynamicParameterListBuilder add(String identifier, Integer value ) { + params.put(identifier, new DynamicParameterList.DynamicIntegerParameter(value)); + return this; + } + + public DynamicParameterListBuilder addIfNotEmpty(String identifier, Integer value ) { + if ( value != null) { + add(identifier, value); + } + return this; + } + + public DynamicParameterListBuilder add(String identifier, Object[] value, String customTypeName, OracleConnection oraConnection ) { + params.put(identifier, new DynamicParameterList.DynamicArrayParameter(value, customTypeName, oraConnection)); + return this; + } + + public DynamicParameterListBuilder addIfNotEmpty(String identifier, Object[] value, String customTypeName, OracleConnection oraConnection ) { + if ( value != null && value.length > 0 ) { + add(identifier, value, customTypeName, oraConnection); + } + return this; + } + + public DynamicParameterListBuilder add(String identifier, Boolean value) { + params.put(identifier, new DynamicBoolParameter(value)); + return this; + } + + public DynamicParameterListBuilder addIfNotEmpty(String identifier, Boolean value) { + if ( value != null ) { + add(identifier, value); + } + return this; + } + + public DynamicParameterList build() { + return new DynamicParameterList(params); + } + } + + /* Implementations of DynamicStringParameter */ + private static class DynamicStringParameter implements DynamicParameter { + private final String value; + + DynamicStringParameter( String value ) { + this.value = value; + } + + @Override + public void setParam(CallableStatement statement, int index) throws SQLException { + if ( value == null ) { + statement.setNull(index, Types.VARCHAR); + } else { + statement.setString(index, value); + } + } + } + + private static class DynamicIntegerParameter implements DynamicParameter { + private final Integer value; + + DynamicIntegerParameter( Integer value ) { + this.value = value; + } + + @Override + public void setParam(CallableStatement statement, int index) throws SQLException { + if ( value == null ) { + statement.setNull(index, Types.INTEGER); + } else { + statement.setInt(index, value); + } + } + } + + private static class DynamicBoolParameter implements DynamicParameter { + private final Boolean value; + + DynamicBoolParameter( Boolean value ) { + this.value = value; + } + + @Override + public void setParam(CallableStatement statement, int index) throws SQLException { + if ( value == null ) { + statement.setNull(index, Types.BOOLEAN); + } else { + statement.setInt(index, (value)?1:0); + } + } + + @Override + public String getSql(String key) { + return key + " => (case ? when 1 then true else false end)"; + } + } + + private static class DynamicArrayParameter implements DynamicParameter { + private final Object[] value; + private final String customTypeName; + private final OracleConnection oraConnection; + + DynamicArrayParameter( Object[] value, String customTypeName, OracleConnection oraConnection ) { + this.value = value; + this.customTypeName = customTypeName; + this.oraConnection = oraConnection; + } + + @Override + public void setParam(CallableStatement statement, int index) throws SQLException { + if ( value == null ) { + statement.setNull(index, Types.ARRAY, customTypeName); + } else { + statement.setArray( + index, + oraConnection.createOracleArray(customTypeName, value) + ); + } + } + } + +} diff --git a/src/main/java/org/utplsql/api/outputBuffer/NonOutputBuffer.java b/src/main/java/org/utplsql/api/outputBuffer/NonOutputBuffer.java index f354a63..971cd63 100644 --- a/src/main/java/org/utplsql/api/outputBuffer/NonOutputBuffer.java +++ b/src/main/java/org/utplsql/api/outputBuffer/NonOutputBuffer.java @@ -4,7 +4,6 @@ import java.io.PrintStream; import java.sql.Connection; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; @@ -33,14 +32,14 @@ public OutputBuffer setFetchSize(int fetchSize) { } @Override - public void printAvailable(Connection conn, PrintStream ps) throws SQLException { + public void printAvailable(Connection conn, PrintStream ps) { List printStreams = new ArrayList<>(1); printStreams.add(ps); printAvailable(conn, printStreams); } @Override - public void printAvailable(Connection conn, List printStreams) throws SQLException { + public void printAvailable(Connection conn, List printStreams) { fetchAvailable(conn, s -> { for (PrintStream ps : printStreams) { ps.println(s); diff --git a/src/main/java/org/utplsql/api/outputBuffer/OutputBufferProvider.java b/src/main/java/org/utplsql/api/outputBuffer/OutputBufferProvider.java index 094cf50..e29716e 100644 --- a/src/main/java/org/utplsql/api/outputBuffer/OutputBufferProvider.java +++ b/src/main/java/org/utplsql/api/outputBuffer/OutputBufferProvider.java @@ -19,11 +19,11 @@ private OutputBufferProvider() { * Returns an OutputBuffer compatible with the given databaseVersion * If we are at 3.1.0 or greater, returns an OutputBuffer based upon the information whether the Reporter has Output or not * - * @param databaseVersion - * @param reporter - * @param conn - * @return - * @throws SQLException + * @param databaseVersion {@link Version} + * @param reporter {@link Reporter} + * @param conn {@link Connection} + * @return OutputBuffer + * @throws SQLException if there are problems with the database access */ public static OutputBuffer getCompatibleOutputBuffer(Version databaseVersion, Reporter reporter, Connection conn) throws SQLException { OracleConnection oraConn = conn.unwrap(OracleConnection.class); diff --git a/src/main/java/org/utplsql/api/reporter/CoreReporters.java b/src/main/java/org/utplsql/api/reporter/CoreReporters.java index 74c9dec..a2b9f1f 100644 --- a/src/main/java/org/utplsql/api/reporter/CoreReporters.java +++ b/src/main/java/org/utplsql/api/reporter/CoreReporters.java @@ -11,14 +11,19 @@ */ public enum CoreReporters { + UT_COVERAGE_COBERTURA_REPORTER(Version.V3_1_0, null), UT_COVERAGE_HTML_REPORTER(Version.V3_0_0, null), - UT_DOCUMENTATION_REPORTER(Version.V3_0_0, null), - UT_TEAMCITY_REPORTER(Version.V3_0_0, null), - UT_XUNIT_REPORTER(Version.V3_0_0, null), - UT_COVERALLS_REPORTER(Version.V3_0_0, null), UT_COVERAGE_SONAR_REPORTER(Version.V3_0_0, null), + UT_COVERALLS_REPORTER(Version.V3_0_0, null), + UT_DEBUG_REPORTER(Version.V3_1_4, null), + UT_DOCUMENTATION_REPORTER(Version.V3_0_0, null), + UT_JUNIT_REPORTER(Version.V3_1_0, null), + UT_REALTIME_REPORTER(Version.V3_1_4, null), UT_SONAR_TEST_REPORTER(Version.V3_0_0, null), - UT_COVERAGE_COBERTURA_REPORTER(Version.V3_1_0, null); + UT_TEAMCITY_REPORTER(Version.V3_0_0, null), + UT_TFS_JUNIT_REPORTER(Version.V3_1_0, null), + @Deprecated + UT_XUNIT_REPORTER(Version.V3_0_0, null); private final Version since; private final Version until; diff --git a/src/main/java/org/utplsql/api/reporter/CoverageHTMLReporter.java b/src/main/java/org/utplsql/api/reporter/CoverageHTMLReporter.java index f927b00..2b1ebb4 100644 --- a/src/main/java/org/utplsql/api/reporter/CoverageHTMLReporter.java +++ b/src/main/java/org/utplsql/api/reporter/CoverageHTMLReporter.java @@ -2,15 +2,8 @@ import org.utplsql.api.ResourceUtil; -import java.io.IOException; -import java.io.InputStream; -import java.net.URISyntaxException; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.List; -import java.util.function.Consumer; public class CoverageHTMLReporter extends DefaultReporter { @@ -29,46 +22,13 @@ public CoverageHTMLReporter(String selfType, Object[] attributes) { super(selfType, attributes); } - /** - * Copies files from Classpath to a target directory. - * Can omit the first x folders of the asset-path when copying to the target directory - * - * @param assetPath Path of the asset in the classpath - * @param targetDirectory Target directory to copy the asset to - * @param filterNumOfFolders Omits the first x folders of the path when copying the asset to the target directory - * @throws IOException - */ - private static void copyFileFromClasspath(Path assetPath, Path targetDirectory, int filterNumOfFolders) throws IOException { - - Path assetStartPath = assetPath.subpath(filterNumOfFolders, assetPath.getNameCount()); - Path targetAssetPath = targetDirectory.resolve(Paths.get(assetStartPath.toString())); - - Files.createDirectories(targetAssetPath.getParent()); - - try (InputStream is = CoverageHTMLReporter.class.getClassLoader() - .getResourceAsStream(assetPath.toString()) - ) { - Files.copy(is, targetAssetPath, StandardCopyOption.REPLACE_EXISTING); - } - } - /** * Write the bundled assets necessary for the HTML Coverage report to a given targetPath * * @param targetDirectory Directory where the assets should be stored - * @throws RuntimeException */ - public static void writeReportAssetsTo(Path targetDirectory) throws RuntimeException { - - try { - Files.createDirectories(targetDirectory); - - List paths = ResourceUtil.getListOfChildren(Paths.get("CoverageHTMLReporter"), true); - - paths.forEach((ThrowingConsumer) p -> copyFileFromClasspath(p, targetDirectory, 1)); - } catch (IOException | URISyntaxException e) { - throw new RuntimeException(e); - } + protected static void writeReportAssetsTo(Path targetDirectory) { + ResourceUtil.copyResources(Paths.get("CoverageHTMLReporter"), targetDirectory); } @Override @@ -116,23 +76,4 @@ public void setAssetsPath(String assetsPath) { this.assetsPath = assetsPath; } - /** - * Functional Interface just to throw Exception from Consumer - * - * @param - */ - @FunctionalInterface - public interface ThrowingConsumer extends Consumer { - - @Override - default void accept(final T elem) { - try { - acceptThrows(elem); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - void acceptThrows(T t) throws IOException; - } } diff --git a/src/main/java/org/utplsql/api/reporter/Reporter.java b/src/main/java/org/utplsql/api/reporter/Reporter.java index 6edd853..6e91062 100644 --- a/src/main/java/org/utplsql/api/reporter/Reporter.java +++ b/src/main/java/org/utplsql/api/reporter/Reporter.java @@ -10,7 +10,6 @@ import org.utplsql.api.compatibility.CompatibilityProxy; import org.utplsql.api.outputBuffer.OutputBuffer; -import javax.xml.bind.DatatypeConverter; import java.sql.Connection; import java.sql.SQLException; @@ -64,8 +63,8 @@ public Reporter init(Connection con) throws SQLException { * This is necessary because we set up DefaultOutputBuffer (and maybe other stuff) we don't want to know and care about * in the java API. Let's just do the instantiation of the Reporter in the database and map it into this object. * - * @param oraConn - * @throws SQLException + * @param oraConn {@link OracleConnection} + * @throws SQLException if there are problems with the database access */ private void initDbReporter(OracleConnection oraConn, ReporterFactory reporterFactory) throws SQLException { OracleCallableStatement callableStatement = (OracleCallableStatement) oraConn.prepareCall("{? = call " + selfType + "()}"); @@ -114,4 +113,17 @@ public Datum toDatum(Connection c) throws SQLException { public OutputBuffer getOutputBuffer() { return outputBuffer; } + + private static class DatatypeConverter { + private static final char[] hexCode = "0123456789ABCDEF".toCharArray(); + + static String printHexBinary(byte[] data) { + StringBuilder r = new StringBuilder(data.length * 2); + for (byte b : data) { + r.append(hexCode[(b >> 4) & 0xF]); + r.append(hexCode[(b & 0xF)]); + } + return r.toString(); + } + } } diff --git a/src/main/java/org/utplsql/api/reporter/ReporterFactory.java b/src/main/java/org/utplsql/api/reporter/ReporterFactory.java index 4b733e3..b569127 100644 --- a/src/main/java/org/utplsql/api/reporter/ReporterFactory.java +++ b/src/main/java/org/utplsql/api/reporter/ReporterFactory.java @@ -120,6 +120,9 @@ public Reporter createReporter(String reporterName, @Nullable Object[] attribute /** * Returns a new reporter of the given name (or should do so). * If no specific ReporterFactoryMethod is registered, returns a default {Reporter} + * + * @param reporterName Name of the reporter + * @return Reporter */ public Reporter createReporter(String reporterName) { return createReporter(reporterName, null); @@ -128,7 +131,7 @@ public Reporter createReporter(String reporterName) { /** * Returns a set of all registered reporter's names * - * @return Set of reporter names + * @return Map of reporter names */ public Map getRegisteredReporterInfo() { Map descMap = new HashMap<>(reportFactoryMethodMap.size()); diff --git a/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspector.java b/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspector.java index bf4c287..878e3b0 100644 --- a/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspector.java +++ b/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspector.java @@ -22,16 +22,17 @@ public interface ReporterInspector { /** * Returns a new instance of a ReporterInspector, based on the utPLSQL version used in the connection * - * @param reporterFactory - * @param conn - * @return - * @throws SQLException + * @param reporterFactory {@link ReporterFactory} + * @param conn {@link Connection} + * @return ReporterInspector + * @throws SQLException if there are problems with the database access + * @throws InvalidVersionException if version is not valid */ static ReporterInspector create(ReporterFactory reporterFactory, Connection conn) throws SQLException, InvalidVersionException { CompatibilityProxy proxy = new CompatibilityProxy(conn); - if (proxy.getDatabaseVersion().isGreaterOrEqualThan(Version.V3_1_0)) { + if (proxy.getUtPlsqlVersion().isGreaterOrEqualThan(Version.V3_1_0)) { return new ReporterInspector310(reporterFactory, conn); } else { return new ReporterInspectorPre310(reporterFactory, conn); diff --git a/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspectorPre310.java b/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspectorPre310.java index f188ac9..40d85fd 100644 --- a/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspectorPre310.java +++ b/src/main/java/org/utplsql/api/reporter/inspect/ReporterInspectorPre310.java @@ -21,7 +21,7 @@ class ReporterInspectorPre310 extends AbstractReporterInspector { registeredReporterFactoryMethods = reporterFactory.getRegisteredReporterInfo(); initDefaultDescriptions(); - Version databaseVersion = new CompatibilityProxy(connection).getDatabaseVersion(); + Version databaseVersion = new CompatibilityProxy(connection).getUtPlsqlVersion(); this.infos = Arrays.stream(CoreReporters.values()) .filter(r -> r.isAvailableFor(databaseVersion)) .map(this::getReporterInfo) @@ -35,7 +35,7 @@ private void initDefaultDescriptions() { descriptions.put(CoreReporters.UT_DOCUMENTATION_REPORTER, ""); descriptions.put(CoreReporters.UT_SONAR_TEST_REPORTER, ""); descriptions.put(CoreReporters.UT_TEAMCITY_REPORTER, ""); - descriptions.put(CoreReporters.UT_XUNIT_REPORTER, ""); + descriptions.put(CoreReporters.UT_JUNIT_REPORTER, ""); } @Override diff --git a/src/main/java/org/utplsql/api/testRunner/AbstractTestRunnerStatement.java b/src/main/java/org/utplsql/api/testRunner/AbstractTestRunnerStatement.java deleted file mode 100644 index dbd5086..0000000 --- a/src/main/java/org/utplsql/api/testRunner/AbstractTestRunnerStatement.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.utplsql.api.testRunner; - -import oracle.jdbc.OracleConnection; -import org.utplsql.api.CustomTypes; -import org.utplsql.api.FileMapper; -import org.utplsql.api.FileMapping; -import org.utplsql.api.TestRunnerOptions; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Types; -import java.util.List; - -/** - * Abstract class which creates a callable statement for running tests - * The SQL to be used has to be implemented for there are differences between the Framework-versions - * - * @author pesse - */ -abstract class AbstractTestRunnerStatement implements TestRunnerStatement { - - protected final TestRunnerOptions options; - protected final CallableStatement callableStatement; - private final Connection conn; - - public AbstractTestRunnerStatement(TestRunnerOptions options, Connection conn) throws SQLException { - this.options = options; - this.conn = conn; - - callableStatement = conn.prepareCall(getSql()); - - createStatement(); - } - - protected abstract String getSql(); - - protected int createStatement() throws SQLException { - - OracleConnection oraConn = conn.unwrap(OracleConnection.class); - - int paramIdx = 0; - - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.pathList.toArray())); - - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_REPORTERS, options.reporterList.toArray())); - - if (options.coverageSchemes.isEmpty()) { - callableStatement.setNull(++paramIdx, Types.ARRAY, CustomTypes.UT_VARCHAR2_LIST); - } else { - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.coverageSchemes.toArray())); - } - - if (options.sourceMappingOptions == null) { - callableStatement.setNull(++paramIdx, Types.ARRAY, CustomTypes.UT_FILE_MAPPINGS); - } else { - List sourceMappings = FileMapper.buildFileMappingList(conn, options.sourceMappingOptions); - - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_FILE_MAPPINGS, sourceMappings.toArray())); - } - - if (options.testMappingOptions == null) { - callableStatement.setNull(++paramIdx, Types.ARRAY, CustomTypes.UT_FILE_MAPPINGS); - } else { - List sourceMappings = FileMapper.buildFileMappingList(conn, options.testMappingOptions); - - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_FILE_MAPPINGS, sourceMappings.toArray())); - } - - if (options.includeObjects.isEmpty()) { - callableStatement.setNull(++paramIdx, Types.ARRAY, CustomTypes.UT_VARCHAR2_LIST); - } else { - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.includeObjects.toArray())); - } - - if (options.excludeObjects.isEmpty()) { - callableStatement.setNull(++paramIdx, Types.ARRAY, CustomTypes.UT_VARCHAR2_LIST); - } else { - callableStatement.setArray( - ++paramIdx, oraConn.createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.excludeObjects.toArray())); - } - - return paramIdx; - } - - public void execute() throws SQLException { - callableStatement.execute(); - } - - @Override - public void close() throws SQLException { - if (callableStatement != null) { - callableStatement.close(); - } - } -} diff --git a/src/main/java/org/utplsql/api/testRunner/ActualTestRunnerStatement.java b/src/main/java/org/utplsql/api/testRunner/ActualTestRunnerStatement.java deleted file mode 100644 index 8625f95..0000000 --- a/src/main/java/org/utplsql/api/testRunner/ActualTestRunnerStatement.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.utplsql.api.testRunner; - -import org.utplsql.api.TestRunnerOptions; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Provides the call to run tests for the most actual Framework version. - * Includes fail on error - * - * @author pesse - */ -class ActualTestRunnerStatement extends AbstractTestRunnerStatement { - - public ActualTestRunnerStatement(TestRunnerOptions options, Connection connection) throws SQLException { - super(options, connection); - } - - @Override - protected String getSql() { - // Workaround because Oracle JDBC doesn't support passing boolean to stored procedures. - String colorConsoleStr = Boolean.toString(options.colorConsole); - String failOnErrors = Boolean.toString(options.failOnErrors); - - return - "BEGIN " + - "ut_runner.run(" + - "a_paths => ?, " + - "a_reporters => ?, " + - "a_color_console => " + colorConsoleStr + ", " + - "a_coverage_schemes => ?, " + - "a_source_file_mappings => ?, " + - "a_test_file_mappings => ?, " + - "a_include_objects => ?, " + - "a_exclude_objects => ?, " + - "a_fail_on_errors => " + failOnErrors + ", " + - "a_client_character_set => ?); " + - "END;"; - } - - @Override - protected int createStatement() throws SQLException { - int curParamIdx = super.createStatement(); - - callableStatement.setString(++curParamIdx, options.clientCharacterSet); - - return curParamIdx; - } -} diff --git a/src/main/java/org/utplsql/api/testRunner/DynamicTestRunnerStatement.java b/src/main/java/org/utplsql/api/testRunner/DynamicTestRunnerStatement.java new file mode 100644 index 0000000..71fe893 --- /dev/null +++ b/src/main/java/org/utplsql/api/testRunner/DynamicTestRunnerStatement.java @@ -0,0 +1,109 @@ +package org.utplsql.api.testRunner; + +import oracle.jdbc.OracleConnection; +import org.utplsql.api.CustomTypes; +import org.utplsql.api.TestRunnerOptions; +import org.utplsql.api.Version; +import org.utplsql.api.compatibility.OptionalFeatures; +import org.utplsql.api.db.DynamicParameterList; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +public class DynamicTestRunnerStatement implements TestRunnerStatement { + + private CallableStatement stmt; + private final OracleConnection oracleConnection; + private final Version utPlSQlVersion; + private final TestRunnerOptions options; + private final DynamicParameterList dynamicParameterList; + + private DynamicTestRunnerStatement(Version utPlSQlVersion, OracleConnection connection, TestRunnerOptions options, CallableStatement statement) throws SQLException { + this.utPlSQlVersion = utPlSQlVersion; + this.oracleConnection = connection; + this.options = options; + this.stmt = statement; + + this.dynamicParameterList = initParameterList(); + + prepareStatement(); + } + + private DynamicParameterList initParameterList() throws SQLException { + + Object[] sourceMappings = (options.sourceMappingOptions != null) + ? FileMapper.buildFileMappingList(oracleConnection, options.sourceMappingOptions).toArray() + : null; + Object[] testMappings = (options.testMappingOptions != null) + ? FileMapper.buildFileMappingList(oracleConnection, options.testMappingOptions).toArray() + : null; + + DynamicParameterList.DynamicParameterListBuilder builder = DynamicParameterList.builder() + .addIfNotEmpty("a_paths", options.pathList.toArray(), CustomTypes.UT_VARCHAR2_LIST, oracleConnection) + .addIfNotEmpty("a_reporters", options.reporterList.toArray(), CustomTypes.UT_REPORTERS, oracleConnection) + .addIfNotEmpty("a_color_console", options.colorConsole) + .addIfNotEmpty("a_coverage_schemes", options.coverageSchemes.toArray(), CustomTypes.UT_VARCHAR2_LIST, oracleConnection) + .addIfNotEmpty("a_source_file_mappings", sourceMappings, CustomTypes.UT_FILE_MAPPINGS, oracleConnection) + .addIfNotEmpty("a_test_file_mappings", testMappings, CustomTypes.UT_FILE_MAPPINGS, oracleConnection) + .addIfNotEmpty("a_include_objects", options.includeObjects.toArray(), CustomTypes.UT_VARCHAR2_LIST, oracleConnection) + .addIfNotEmpty("a_exclude_objects", options.excludeObjects.toArray(), CustomTypes.UT_VARCHAR2_LIST, oracleConnection); + + if (OptionalFeatures.FAIL_ON_ERROR.isAvailableFor(utPlSQlVersion)) { + builder.addIfNotEmpty("a_fail_on_errors", options.failOnErrors); + } + if (OptionalFeatures.CLIENT_CHARACTER_SET.isAvailableFor(utPlSQlVersion)) { + builder.addIfNotEmpty("a_client_character_set", options.clientCharacterSet); + } + if (OptionalFeatures.RANDOM_EXECUTION_ORDER.isAvailableFor(utPlSQlVersion)) { + builder.addIfNotEmpty("a_random_test_order", options.randomTestOrder) + .addIfNotEmpty("a_random_test_order_seed", options.randomTestOrderSeed); + } + if (OptionalFeatures.TAGS.isAvailableFor(utPlSQlVersion)) { + builder.addIfNotEmpty("a_tags", options.getTagsAsString()); + } + if (OptionalFeatures.EXPR.isAvailableFor(utPlSQlVersion)) { + builder.addIfNotEmpty("a_include_schema_expr", options.includeSchemaExpr) + .addIfNotEmpty("a_include_object_expr", options.includeObjectExpr) + .addIfNotEmpty("a_exclude_schema_expr", options.excludeSchemaExpr) + .addIfNotEmpty("a_exclude_object_expr", options.excludeObjectExpr); + } + + return builder.build(); + } + + private void prepareStatement() throws SQLException { + if (stmt == null) { + String sql = "BEGIN " + + "ut_runner.run(" + + dynamicParameterList.getSql() + + ");" + + "END;"; + stmt = oracleConnection.prepareCall(sql); + } + + dynamicParameterList.setParamsStartWithIndex(stmt, 1); + } + + @Override + public void execute() throws SQLException { + stmt.execute(); + } + + @Override + public String getSql() { + return dynamicParameterList.getSql(); + } + + @Override + public void close() throws SQLException { + if (stmt != null) { + stmt.close(); + } + } + + public static DynamicTestRunnerStatement forVersion(Version version, Connection connection, TestRunnerOptions options, CallableStatement statement) throws SQLException { + OracleConnection oraConn = connection.unwrap(OracleConnection.class); + return new DynamicTestRunnerStatement(version, oraConn, options, statement); + } +} diff --git a/src/main/java/org/utplsql/api/testRunner/FileMapper.java b/src/main/java/org/utplsql/api/testRunner/FileMapper.java new file mode 100644 index 0000000..b599a5a --- /dev/null +++ b/src/main/java/org/utplsql/api/testRunner/FileMapper.java @@ -0,0 +1,84 @@ +package org.utplsql.api.testRunner; + + +import oracle.jdbc.OracleConnection; +import oracle.jdbc.OracleTypes; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.utplsql.api.CustomTypes; +import org.utplsql.api.FileMapperOptions; +import org.utplsql.api.FileMapping; +import org.utplsql.api.KeyValuePair; +import org.utplsql.api.db.DynamicParameterList; + +import java.sql.*; +import java.util.*; + +final class FileMapper { + + private static final Logger logger = LoggerFactory.getLogger(FileMapper.class); + + private FileMapper() { + } + + /** + * Call the database api to build the custom file mappings. + */ + private static Array buildFileMappingArray( + Connection conn, FileMapperOptions mapperOptions) throws SQLException { + OracleConnection oraConn = conn.unwrap(OracleConnection.class); + + Map> typeMap = conn.getTypeMap(); + typeMap.put(CustomTypes.UT_FILE_MAPPING, FileMapping.class); + typeMap.put(CustomTypes.UT_KEY_VALUE_PAIR, KeyValuePair.class); + conn.setTypeMap(typeMap); + + logger.debug("Building fileMappingArray"); + final Object[] filePathsArray = mapperOptions.getFilePaths().toArray(); + for ( Object elem : filePathsArray ) { + logger.debug("Path: " + elem); + } + Object[] typeMapArray = null; + if ( mapperOptions.getTypeMappings() != null ) { + typeMapArray = mapperOptions.getTypeMappings().toArray(); + } + + DynamicParameterList parameterList = DynamicParameterList.builder() + .add("a_file_paths", filePathsArray, CustomTypes.UT_VARCHAR2_LIST, oraConn) + .addIfNotEmpty("a_object_owner", mapperOptions.getObjectOwner()) + .addIfNotEmpty("a_file_to_object_type_mapping", typeMapArray, CustomTypes.UT_KEY_VALUE_PAIRS, oraConn) + .addIfNotEmpty("a_regex_pattern", mapperOptions.getRegexPattern()) + .addIfNotEmpty("a_object_owner_subexpression", mapperOptions.getOwnerSubExpression()) + .addIfNotEmpty("a_object_name_subexpression", mapperOptions.getNameSubExpression()) + .addIfNotEmpty("a_object_type_subexpression", mapperOptions.getTypeSubExpression()) + .build(); + + CallableStatement callableStatement = conn.prepareCall( + "BEGIN " + + "? := ut_file_mapper.build_file_mappings(" + + parameterList.getSql() + + "); " + + "END;"); + + int paramIdx = 0; + callableStatement.registerOutParameter(++paramIdx, OracleTypes.ARRAY, CustomTypes.UT_FILE_MAPPINGS); + + parameterList.setParamsStartWithIndex(callableStatement, ++paramIdx); + + callableStatement.execute(); + return callableStatement.getArray(1); + } + + static List buildFileMappingList( + Connection conn, FileMapperOptions mapperOptions) throws SQLException { + java.sql.Array fileMappings = buildFileMappingArray(conn, mapperOptions); + + List mappingList = new ArrayList<>(); + for (Object obj : (Object[]) fileMappings.getArray()) { + mappingList.add((FileMapping) obj); + } + + return mappingList; + } + +} diff --git a/src/main/java/org/utplsql/api/testRunner/Pre303TestRunnerStatement.java b/src/main/java/org/utplsql/api/testRunner/Pre303TestRunnerStatement.java deleted file mode 100644 index d2d53cb..0000000 --- a/src/main/java/org/utplsql/api/testRunner/Pre303TestRunnerStatement.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.utplsql.api.testRunner; - -import org.utplsql.api.TestRunnerOptions; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * TestRunner-Statement for Framework version before 3.0.3 - * Does not know about failOnErrors option - * - * @author pesse - */ -class Pre303TestRunnerStatement extends AbstractTestRunnerStatement { - - public Pre303TestRunnerStatement(TestRunnerOptions options, Connection conn) throws SQLException { - super(options, conn); - } - - @Override - protected String getSql() { - // Workaround because Oracle JDBC doesn't support passing boolean to stored procedures. - String colorConsoleStr = Boolean.toString(options.colorConsole); - - return "BEGIN " + - "ut_runner.run(" + - "a_paths => ?, " + - "a_reporters => ?, " + - "a_color_console => " + colorConsoleStr + ", " + - "a_coverage_schemes => ?, " + - "a_source_file_mappings => ?, " + - "a_test_file_mappings => ?, " + - "a_include_objects => ?, " + - "a_exclude_objects => ?); " + - "END;"; - } -} diff --git a/src/main/java/org/utplsql/api/testRunner/Pre312TestRunnerStatement.java b/src/main/java/org/utplsql/api/testRunner/Pre312TestRunnerStatement.java deleted file mode 100644 index 129413b..0000000 --- a/src/main/java/org/utplsql/api/testRunner/Pre312TestRunnerStatement.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.utplsql.api.testRunner; - -import org.utplsql.api.TestRunnerOptions; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * TestRunner-Statement for Framework version before 3.0.3 - * Does not know about client character set - * - * @author pesse - */ -class Pre312TestRunnerStatement extends AbstractTestRunnerStatement { - - public Pre312TestRunnerStatement(TestRunnerOptions options, Connection connection) throws SQLException { - super(options, connection); - } - - @Override - protected String getSql() { - // Workaround because Oracle JDBC doesn't support passing boolean to stored procedures. - String colorConsoleStr = Boolean.toString(options.colorConsole); - String failOnErrors = Boolean.toString(options.failOnErrors); - - return - "BEGIN " + - "ut_runner.run(" + - "a_paths => ?, " + - "a_reporters => ?, " + - "a_color_console => " + colorConsoleStr + ", " + - "a_coverage_schemes => ?, " + - "a_source_file_mappings => ?, " + - "a_test_file_mappings => ?, " + - "a_include_objects => ?, " + - "a_exclude_objects => ?, " + - "a_fail_on_errors => " + failOnErrors + "); " + - "END;"; - } -} diff --git a/src/main/java/org/utplsql/api/testRunner/TestRunnerStatement.java b/src/main/java/org/utplsql/api/testRunner/TestRunnerStatement.java index 9a0bb48..dbc5b71 100644 --- a/src/main/java/org/utplsql/api/testRunner/TestRunnerStatement.java +++ b/src/main/java/org/utplsql/api/testRunner/TestRunnerStatement.java @@ -11,6 +11,8 @@ public interface TestRunnerStatement extends AutoCloseable { void execute() throws SQLException; + String getSql(); + @Override void close() throws SQLException; } diff --git a/src/main/java/org/utplsql/api/testRunner/TestRunnerStatementProvider.java b/src/main/java/org/utplsql/api/testRunner/TestRunnerStatementProvider.java index 77a9204..f263237 100644 --- a/src/main/java/org/utplsql/api/testRunner/TestRunnerStatementProvider.java +++ b/src/main/java/org/utplsql/api/testRunner/TestRunnerStatementProvider.java @@ -2,7 +2,6 @@ import org.utplsql.api.TestRunnerOptions; import org.utplsql.api.Version; -import org.utplsql.api.exception.InvalidVersionException; import java.sql.Connection; import java.sql.SQLException; @@ -25,25 +24,9 @@ private TestRunnerStatementProvider() { * @param options TestRunnerOptions to be used * @param conn Active Connection * @return TestRunnerStatment compatible with the database framework - * @throws SQLException + * @throws SQLException if there are problems with the database access */ public static TestRunnerStatement getCompatibleTestRunnerStatement(Version databaseVersion, TestRunnerOptions options, Connection conn) throws SQLException { - AbstractTestRunnerStatement stmt = null; - - try { - if (databaseVersion.isLessThan(Version.V3_0_3)) { - stmt = new Pre303TestRunnerStatement(options, conn); - } else if (databaseVersion.isLessThan(Version.V3_1_2)) { - stmt = new Pre312TestRunnerStatement(options, conn); - } - - } catch (InvalidVersionException ignored) { - } - - if (stmt == null) { - stmt = new ActualTestRunnerStatement(options, conn); - } - - return stmt; + return DynamicTestRunnerStatement.forVersion(databaseVersion, conn, options, null); } } diff --git a/src/main/resources/utplsql-api.version b/src/main/resources/utplsql-api.version index 3fb16e7..ad96e7c 100644 --- a/src/main/resources/utplsql-api.version +++ b/src/main/resources/utplsql-api.version @@ -1 +1 @@ -${project.version}.${travisBuildNumber} \ No newline at end of file +${project.version} diff --git a/src/test/java/org/utplsql/api/AbstractDatabaseTest.java b/src/test/java/org/utplsql/api/AbstractDatabaseTest.java index 393c31e..31ac56c 100644 --- a/src/test/java/org/utplsql/api/AbstractDatabaseTest.java +++ b/src/test/java/org/utplsql/api/AbstractDatabaseTest.java @@ -11,21 +11,21 @@ public abstract class AbstractDatabaseTest { - private static String sUrl; - private static String sUser; - private static String sPass; + private static final String DB_URL; + private static final String DB_USER; + private static final String DB_PASS; static { - sUrl = EnvironmentVariableUtil.getEnvValue("DB_URL", "192.168.99.100:1521:XE"); - sUser = EnvironmentVariableUtil.getEnvValue("DB_USER", "app"); - sPass = EnvironmentVariableUtil.getEnvValue("DB_PASS", "app"); + DB_URL = EnvironmentVariableUtil.getEnvValue("DB_URL", "localhost:1521:XE"); + DB_USER = EnvironmentVariableUtil.getEnvValue("DB_USER", "app"); + DB_PASS = EnvironmentVariableUtil.getEnvValue("DB_PASS", "pass"); } private Connection conn; - private List connectionList = new ArrayList<>(); + private final List connectionList = new ArrayList<>(); public static String getUser() { - return sUser; + return DB_USER; } @BeforeEach @@ -38,7 +38,7 @@ protected Connection getConnection() { } protected synchronized Connection newConnection() throws SQLException { - Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@" + sUrl, sUser, sPass); + Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@" + DB_URL, DB_USER, DB_PASS); connectionList.add(conn); return conn; } diff --git a/src/test/java/org/utplsql/api/CompatibilityIT.java b/src/test/java/org/utplsql/api/CompatibilityIT.java index 118d386..948948a 100644 --- a/src/test/java/org/utplsql/api/CompatibilityIT.java +++ b/src/test/java/org/utplsql/api/CompatibilityIT.java @@ -19,9 +19,8 @@ void compatibleVersion() throws SQLException { @Test void skipCompatibilityCheck() throws SQLException { - CompatibilityProxy proxy = new CompatibilityProxy(getConnection(), true); + CompatibilityProxy proxy = new CompatibilityProxy(getConnection(), Version.LATEST); proxy.failOnNotCompatible(); assertTrue(proxy.isCompatible()); - } } diff --git a/src/test/java/org/utplsql/api/DBHelperIT.java b/src/test/java/org/utplsql/api/DBHelperIT.java index 8b13a5e..41f85c4 100644 --- a/src/test/java/org/utplsql/api/DBHelperIT.java +++ b/src/test/java/org/utplsql/api/DBHelperIT.java @@ -13,7 +13,7 @@ class DBHelperIT extends AbstractDatabaseTest { void getFrameworkVersion() throws SQLException { Version v = DBHelper.getDatabaseFrameworkVersion(getConnection()); assertTrue(v.isValid()); - System.out.println(v.getNormalizedString() + " - " + v.toString()); + System.out.println(v.getNormalizedString() + " - " + v); } @Test diff --git a/src/test/java/org/utplsql/api/DatabaseInformationIT.java b/src/test/java/org/utplsql/api/DatabaseInformationIT.java index 8eb4317..2844625 100644 --- a/src/test/java/org/utplsql/api/DatabaseInformationIT.java +++ b/src/test/java/org/utplsql/api/DatabaseInformationIT.java @@ -17,7 +17,7 @@ void getFrameworkVersion() throws SQLException { Version v = databaseInformation.getUtPlsqlFrameworkVersion(getConnection()); assertTrue(v.isValid()); - System.out.println(v.getNormalizedString() + " - " + v.toString()); + System.out.println(v.getNormalizedString() + " - " + v); } @Test diff --git a/src/test/java/org/utplsql/api/EnvironmentVariableUtil.java b/src/test/java/org/utplsql/api/EnvironmentVariableUtil.java new file mode 100644 index 0000000..90ca49f --- /dev/null +++ b/src/test/java/org/utplsql/api/EnvironmentVariableUtil.java @@ -0,0 +1,53 @@ +package org.utplsql.api; + +import javax.annotation.Nullable; + +/** + * This class provides an easy way to get environmental variables. + * This is mainly to improve testability but also to standardize the way how utPLSQL API and CLI read from + * environment. + *

+ * Variables are obtained from the following scopes in that order (chain breaks as soon as a value is obtained): + *

    + *
  • Properties (System.getProperty())
  • + *
  • Environment (System.getEnv())
  • + *
  • Default value
  • + *
+ *

+ * An empty string is treated the same as null. + * + * @author pesse + */ +public class EnvironmentVariableUtil { + + private EnvironmentVariableUtil() { + } + + /** + * Returns the value for a given key from environment (see class description) + * + * @param key Key of environment or property value + * @return Environment value or null + */ + public static String getEnvValue(String key) { + return getEnvValue(key, null); + } + + /** + * Returns the value for a given key from environment or a default value (see class description) + * + * @param key Key of environment or property value + * @param defaultValue Default value if nothing found + * @return Environment value or defaultValue + */ + public static String getEnvValue(String key, @Nullable String defaultValue) { + + String val = System.getProperty(key); + if (val == null || val.isEmpty()) val = System.getenv(key); + if (val == null || val.isEmpty()) val = defaultValue; + + return val; + } + + +} diff --git a/src/test/java/org/utplsql/api/EnvironmentVariableUtilTest.java b/src/test/java/org/utplsql/api/EnvironmentVariableUtilTest.java index e437cd1..c827232 100644 --- a/src/test/java/org/utplsql/api/EnvironmentVariableUtilTest.java +++ b/src/test/java/org/utplsql/api/EnvironmentVariableUtilTest.java @@ -37,7 +37,7 @@ void testGetVariableFromProperty() { @Test void testGetVariableFromDefault() { - assertEquals("defaultValue", EnvironmentVariableUtil.getEnvValue("RANDOM" + String.valueOf(System.currentTimeMillis()), "defaultValue")); + assertEquals("defaultValue", EnvironmentVariableUtil.getEnvValue("RANDOM" + System.currentTimeMillis(), "defaultValue")); } } \ No newline at end of file diff --git a/src/test/java/org/utplsql/api/OptionalFeaturesIT.java b/src/test/java/org/utplsql/api/OptionalFeaturesIT.java index c7ce27e..f8fe9b3 100644 --- a/src/test/java/org/utplsql/api/OptionalFeaturesIT.java +++ b/src/test/java/org/utplsql/api/OptionalFeaturesIT.java @@ -14,7 +14,7 @@ class OptionalFeaturesIT extends AbstractDatabaseTest { private Version getDatabaseVersion() throws SQLException { - return new CompatibilityProxy(getConnection()).getDatabaseVersion(); + return new CompatibilityProxy(getConnection()).getUtPlsqlVersion(); } @Test @@ -52,4 +52,37 @@ void customReporters() throws SQLException, InvalidVersionException { assertFalse(available); } } + + @Test + void clientCharset() throws SQLException, InvalidVersionException { + boolean available = OptionalFeatures.CLIENT_CHARACTER_SET.isAvailableFor(getConnection()); + + if (getDatabaseVersion().isGreaterOrEqualThan(Version.V3_1_2)) { + assertTrue(available); + } else { + assertFalse(available); + } + } + + @Test + void randomExecutionOrder() throws SQLException, InvalidVersionException { + boolean available = OptionalFeatures.RANDOM_EXECUTION_ORDER.isAvailableFor(getConnection()); + + if (getDatabaseVersion().isGreaterOrEqualThan(Version.V3_1_7)) { + assertTrue(available); + } else { + assertFalse(available); + } + } + + @Test + void tags() throws SQLException, InvalidVersionException { + boolean available = OptionalFeatures.TAGS.isAvailableFor(getConnection()); + + if (getDatabaseVersion().isGreaterOrEqualThan(Version.V3_1_7)) { + assertTrue(available); + } else { + assertFalse(available); + } + } } diff --git a/src/test/java/org/utplsql/api/OutputBufferIT.java b/src/test/java/org/utplsql/api/OutputBufferIT.java index c6fea1f..6dd2742 100644 --- a/src/test/java/org/utplsql/api/OutputBufferIT.java +++ b/src/test/java/org/utplsql/api/OutputBufferIT.java @@ -40,7 +40,6 @@ private Reporter createReporter() throws SQLException { @Test void printAvailableLines() throws SQLException { ExecutorService executorService = Executors.newFixedThreadPool(2); - try { final Reporter reporter = createReporter(); @@ -131,7 +130,7 @@ void getOutputFromSonarReporter() throws SQLException { void sonarReporterHasEncodingSet() throws SQLException, InvalidVersionException { CompatibilityProxy proxy = new CompatibilityProxy(newConnection()); - if (proxy.getDatabaseVersion().isGreaterOrEqualThan(Version.V3_1_2)) { + if (proxy.getUtPlsqlVersion().isGreaterOrEqualThan(Version.V3_1_2)) { Reporter reporter = new DefaultReporter(CoreReporters.UT_SONAR_TEST_REPORTER.name(), null).init(getConnection()); TestRunner tr = new TestRunner() diff --git a/src/test/java/org/utplsql/api/ReporterInspectorIT.java b/src/test/java/org/utplsql/api/ReporterInspectorIT.java index 367d9d1..4f3f13d 100644 --- a/src/test/java/org/utplsql/api/ReporterInspectorIT.java +++ b/src/test/java/org/utplsql/api/ReporterInspectorIT.java @@ -24,7 +24,6 @@ private ReporterFactory getReporterFactory() throws SQLException { @Test void testGetReporterInfo() throws SQLException, InvalidVersionException { - CompatibilityProxy proxy = new CompatibilityProxy(getConnection()); ReporterInspector inspector = ReporterInspector.create(getReporterFactory(), getConnection()); @@ -37,9 +36,9 @@ void testGetReporterInfo() throws SQLException, InvalidVersionException { assertEquals(infos.get(CoreReporters.UT_DOCUMENTATION_REPORTER.name()).getType(), ReporterInfo.Type.SQL_WITH_JAVA); assertEquals(infos.get(CoreReporters.UT_SONAR_TEST_REPORTER.name()).getType(), ReporterInfo.Type.SQL); assertEquals(infos.get(CoreReporters.UT_TEAMCITY_REPORTER.name()).getType(), ReporterInfo.Type.SQL); - assertEquals(infos.get(CoreReporters.UT_XUNIT_REPORTER.name()).getType(), ReporterInfo.Type.SQL); + assertEquals(infos.get(CoreReporters.UT_JUNIT_REPORTER.name()).getType(), ReporterInfo.Type.SQL); - if (CoreReporters.UT_COVERAGE_COBERTURA_REPORTER.isAvailableFor(proxy.getDatabaseVersion())) { + if (CoreReporters.UT_COVERAGE_COBERTURA_REPORTER.isAvailableFor(proxy.getUtPlsqlVersion())) { assertEquals(infos.get(CoreReporters.UT_COVERAGE_COBERTURA_REPORTER.name()).getType(), ReporterInfo.Type.SQL); } } diff --git a/src/test/java/org/utplsql/api/TestRunnerIT.java b/src/test/java/org/utplsql/api/TestRunnerIT.java index 414b9f9..4ceb184 100644 --- a/src/test/java/org/utplsql/api/TestRunnerIT.java +++ b/src/test/java/org/utplsql/api/TestRunnerIT.java @@ -1,8 +1,12 @@ package org.utplsql.api; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.utplsql.api.compatibility.CompatibilityProxy; +import org.utplsql.api.compatibility.OptionalFeatures; +import org.utplsql.api.db.DatabaseInformation; +import org.utplsql.api.db.DefaultDatabaseInformation; import org.utplsql.api.exception.InvalidVersionException; import org.utplsql.api.exception.SomeTestsFailedException; import org.utplsql.api.reporter.CoreReporters; @@ -30,10 +34,12 @@ void runWithDefaultParameters() throws SQLException { * This can only be run against versions >= 3.0.3 */ @Test - void runWithoutCompatibilityCheck() throws SQLException, InvalidVersionException { - CompatibilityProxy proxy = new CompatibilityProxy(getConnection()); + void runWithoutCompatibilityCheck() throws SQLException { + + DatabaseInformation databaseInformation = new DefaultDatabaseInformation(); - if (proxy.getDatabaseVersion().isGreaterOrEqualThan(Version.V3_0_3)) { + // We can only test this for the versions of the latest TestRunnerStatement-Change + if ( OptionalFeatures.RANDOM_EXECUTION_ORDER.isAvailableFor(databaseInformation.getUtPlsqlFrameworkVersion(getConnection())) ) { new TestRunner() .skipCompatibilityCheck(true) .run(getConnection()); @@ -51,7 +57,7 @@ void runWithManyReporters() throws SQLException { .addReporter(CoreReporters.UT_COVERALLS_REPORTER.name()) .addReporter(CoreReporters.UT_SONAR_TEST_REPORTER.name()) .addReporter(CoreReporters.UT_TEAMCITY_REPORTER.name()) - .addReporter(CoreReporters.UT_XUNIT_REPORTER.name()) + .addReporter(CoreReporters.UT_JUNIT_REPORTER.name()) .run(conn); } @@ -59,13 +65,14 @@ void runWithManyReporters() throws SQLException { /** * This can only be tested on frameworks >= 3.0.3 */ + @Disabled @Test void failOnErrors() throws SQLException, InvalidVersionException { Connection conn = getConnection(); CompatibilityProxy proxy = new CompatibilityProxy(conn); - if (proxy.getDatabaseVersion().isGreaterOrEqualThan(Version.V3_0_3)) { + if (proxy.getUtPlsqlVersion().isGreaterOrEqualThan(Version.V3_0_3)) { Executable throwingTestRunner = () -> new TestRunner() .failOnErrors(true) .run(conn); @@ -73,4 +80,21 @@ void failOnErrors() throws SQLException, InvalidVersionException { } } + @Test + void runWithRandomExecutionOrder() throws SQLException { + CompatibilityProxy proxy = new CompatibilityProxy(getConnection()); + + new TestRunner() + .randomTestOrder(true) + .randomTestOrderSeed(123) + .run(getConnection()); + } + + @Test + void runWithTags() throws SQLException { + new TestRunner() + .addTag("none") + .run(getConnection()); + } + } diff --git a/src/test/java/org/utplsql/api/VersionObjectTest.java b/src/test/java/org/utplsql/api/VersionObjectTest.java index 22dcd24..46cea83 100644 --- a/src/test/java/org/utplsql/api/VersionObjectTest.java +++ b/src/test/java/org/utplsql/api/VersionObjectTest.java @@ -78,6 +78,29 @@ void versionCompareTo() { assertEquals(0, base.compareTo(Version.create("2.3.4.5"))); } + @Test + void versionCompareToWithBaseNull() { + Version base = Version.create("2.3.4"); + + // Less than + assertEquals(-1, base.compareTo(Version.create("3"))); + assertEquals(-1, base.compareTo(Version.create("3.2"))); + assertEquals(-1, base.compareTo(Version.create("2.4.1"))); + assertEquals(-1, base.compareTo(Version.create("2.3.9.1"))); + assertEquals(-1, base.compareTo(Version.create("2.3.4.1"))); + assertEquals(-1, base.compareTo(Version.create("2.3.4.5"))); + assertEquals(-1, base.compareTo(Version.create("2.3.4.9"))); + + // Greater than + assertEquals(1, base.compareTo(Version.create("1"))); + assertEquals(1, base.compareTo(Version.create("1.6"))); + assertEquals(1, base.compareTo(Version.create("2.2.4"))); + assertEquals(1, base.compareTo(Version.create("2.3.3"))); + + // Equal + assertEquals(0, base.compareTo(Version.create("2.3.4"))); + } + @Test void isGreaterOrEqualThan() throws InvalidVersionException { Version base = Version.create("2.3.4.5"); @@ -98,6 +121,26 @@ void isGreaterOrEqualThan() throws InvalidVersionException { } + @Test + void isGreaterOrEqualThanWithBaseNull() throws InvalidVersionException { + Version base = Version.create("2.3.4"); + + assertTrue(base.isGreaterOrEqualThan(Version.create("1"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2.3"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2.2"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2.3.4"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2.3.3"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2.3.4.5"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2.3.4.4"))); + assertTrue(base.isGreaterOrEqualThan(Version.create("2.3.4.6"))); + + assertFalse(base.isGreaterOrEqualThan(Version.create("2.3.5"))); + assertFalse(base.isGreaterOrEqualThan(Version.create("2.4"))); + assertFalse(base.isGreaterOrEqualThan(Version.create("3"))); + + } + @Test void isGreaterOrEqualThanFails() { // Given version is invalid diff --git a/src/test/java/org/utplsql/api/db/DynamicParameterListTest.java b/src/test/java/org/utplsql/api/db/DynamicParameterListTest.java new file mode 100644 index 0000000..e3e9a17 --- /dev/null +++ b/src/test/java/org/utplsql/api/db/DynamicParameterListTest.java @@ -0,0 +1,144 @@ +package org.utplsql.api.db; + +import oracle.jdbc.OracleConnection; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.sql.CallableStatement; +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +public class DynamicParameterListTest { + + @Nested + class single_parameters { + @Test + void can_add_string() throws SQLException { + CallableStatement stmt = mock(CallableStatement.class); + + DynamicParameterList paramList = DynamicParameterList.builder() + .add("a_param", "MyString") + .build(); + + assertEquals("a_param => ?", paramList.getSql()); + + paramList.setParamsStartWithIndex(stmt, 5); + verify(stmt).setString(5, "MyString"); + } + + @Test + void can_add_int() throws SQLException { + CallableStatement stmt = mock(CallableStatement.class); + + DynamicParameterList paramList = DynamicParameterList.builder() + .add("a_param", 1234) + .build(); + + assertEquals("a_param => ?", paramList.getSql()); + + paramList.setParamsStartWithIndex(stmt, 10); + verify(stmt).setInt(10, 1234); + } + + @Test + void can_add_array() throws SQLException { + CallableStatement stmt = mock(CallableStatement.class); + OracleConnection conn = mock(OracleConnection.class); + + Object[] numArr = new Object[]{1, 2}; + + DynamicParameterList paramList = DynamicParameterList.builder() + .add("a_param", numArr, "MY_TYPE", conn) + .build(); + + assertEquals("a_param => ?", paramList.getSql()); + + paramList.setParamsStartWithIndex(stmt, 3); + verify(conn).createOracleArray("MY_TYPE", numArr); + verify(stmt).setArray(3, null); + } + + @Test + void can_add_boolean() throws SQLException { + CallableStatement stmt = mock(CallableStatement.class); + + DynamicParameterList paramList = DynamicParameterList.builder() + .add("a_bool", true) + .build(); + + assertEquals("a_bool => (case ? when 1 then true else false end)", paramList.getSql()); + + paramList.setParamsStartWithIndex(stmt, 3); + verify(stmt).setInt(3, 1); + } + } + + @Nested + class mutliple_parameters { + + @Test + void several_parameters_are_issued_in_the_correct_order() throws SQLException { + CallableStatement mockedStatement = mock(CallableStatement.class); + + DynamicParameterList parameterList = DynamicParameterList.builder() + .add("a_param1", "Param1") + .add("a_param2", "Param2") + .add("a_param3", "Param3") + .build(); + + assertEquals("a_param1 => ?, a_param2 => ?, a_param3 => ?", parameterList.getSql()); + + parameterList.setParamsStartWithIndex(mockedStatement, 10); + + verify(mockedStatement).setString(10, "Param1"); + verify(mockedStatement).setString(11, "Param2"); + verify(mockedStatement).setString(12, "Param3"); + } + + @Test + void call_with_three_different_types() throws SQLException { + + CallableStatement mockedStatement = mock(CallableStatement.class); + OracleConnection mockedConn = mock(OracleConnection.class); + + Object[] numArr = new Object[]{1, 2}; + + DynamicParameterList parameterList = DynamicParameterList.builder() + .add("a_object_owner", "MyOwner") + .add("a_num_param", 123) + .add("a_num_array", numArr, "MY_NUM_ARR", mockedConn) + .build(); + + assertEquals("a_object_owner => ?, a_num_param => ?, a_num_array => ?", parameterList.getSql()); + + parameterList.setParamsStartWithIndex(mockedStatement, 5); + + verify(mockedStatement).setString(5, "MyOwner"); + verify(mockedStatement).setInt(6, 123); + verify(mockedConn).createOracleArray("MY_NUM_ARR", numArr); + verify(mockedStatement).setArray(7, null); + } + + @Test + void when_not_accept_empty_filter_empty_elements() throws SQLException { + + CallableStatement mockedStatement = mock(CallableStatement.class); + OracleConnection mockedConn = mock(OracleConnection.class); + + DynamicParameterList parameterList = DynamicParameterList.builder() + .addIfNotEmpty("a_object_owner", (String) null) + .addIfNotEmpty("a_num_param", (Integer) null) + .addIfNotEmpty("a_num_array", new Object[]{}, "MY_NUM_ARR", mockedConn) + .build(); + + assertEquals("", parameterList.getSql()); + + parameterList.setParamsStartWithIndex(mockedStatement, 2); + + verifyNoMoreInteractions(mockedStatement); + verifyNoMoreInteractions(mockedConn); + } + } +} diff --git a/src/test/java/org/utplsql/api/outputBuffer/OutputBufferProviderIT.java b/src/test/java/org/utplsql/api/outputBuffer/OutputBufferProviderIT.java new file mode 100644 index 0000000..463e0be --- /dev/null +++ b/src/test/java/org/utplsql/api/outputBuffer/OutputBufferProviderIT.java @@ -0,0 +1,49 @@ +package org.utplsql.api.outputBuffer; + +import org.junit.jupiter.api.Test; +import org.utplsql.api.AbstractDatabaseTest; +import org.utplsql.api.Version; +import org.utplsql.api.compatibility.CompatibilityProxy; +import org.utplsql.api.exception.InvalidVersionException; +import org.utplsql.api.reporter.CoreReporters; +import org.utplsql.api.reporter.Reporter; +import org.utplsql.api.reporter.ReporterFactory; + +import java.sql.SQLException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsInstanceOf.instanceOf; + +public class OutputBufferProviderIT extends AbstractDatabaseTest { + + @Test + void testGettingPre310Version() throws SQLException { + + CompatibilityProxy proxy = new CompatibilityProxy(getConnection(), Version.V3_0_4); + ReporterFactory reporterFactory = ReporterFactory.createDefault(proxy); + + Reporter r = reporterFactory.createReporter(CoreReporters.UT_DOCUMENTATION_REPORTER.name()); + r.init(getConnection(), proxy, reporterFactory); + + OutputBuffer buffer = proxy.getOutputBuffer(r, getConnection()); + + assertThat(buffer, instanceOf(CompatibilityOutputBufferPre310.class)); + } + + @Test + void testGettingActualVersion() throws SQLException, InvalidVersionException { + CompatibilityProxy proxy = new CompatibilityProxy(getConnection(), Version.LATEST); + + // We can only test new behaviour with DB-Version >= 3.1.0 + if ( proxy.getRealDbPlsqlVersion().isGreaterOrEqualThan(Version.V3_1_0)) { + ReporterFactory reporterFactory = ReporterFactory.createDefault(proxy); + + Reporter r = reporterFactory.createReporter(CoreReporters.UT_DOCUMENTATION_REPORTER.name()); + r.init(getConnection(), proxy, reporterFactory); + + OutputBuffer buffer = proxy.getOutputBuffer(r, getConnection()); + + assertThat(buffer, instanceOf(DefaultOutputBuffer.class)); + } + } +} diff --git a/src/test/java/org/utplsql/api/outputBuffer/PLSQLOutputBufferIT.java b/src/test/java/org/utplsql/api/outputBuffer/PLSQLOutputBufferIT.java deleted file mode 100644 index b4b6aa9..0000000 --- a/src/test/java/org/utplsql/api/outputBuffer/PLSQLOutputBufferIT.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.utplsql.api.outputBuffer; - -import org.junit.jupiter.api.Test; -import org.utplsql.api.AbstractDatabaseTest; - -class PLSQLOutputBufferIT extends AbstractDatabaseTest { - - @Test - void getLines() { - - } -} diff --git a/src/test/java/org/utplsql/api/reporter/CoverageHTMLReporterAssetTest.java b/src/test/java/org/utplsql/api/reporter/CoverageHTMLReporterAssetTest.java index 41dd399..b94cc32 100644 --- a/src/test/java/org/utplsql/api/reporter/CoverageHTMLReporterAssetTest.java +++ b/src/test/java/org/utplsql/api/reporter/CoverageHTMLReporterAssetTest.java @@ -1,80 +1,65 @@ package org.utplsql.api.reporter; -import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; -import java.io.IOException; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.Path; +import java.nio.file.Paths; import static org.junit.jupiter.api.Assertions.assertTrue; +@Tag("binary") class CoverageHTMLReporterAssetTest { private static final String TEST_FOLDER = "__testAssets"; - @AfterAll - static void clearTestAssetsFolder() { - try { - Files.walkFileTree(Paths.get(TEST_FOLDER), new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - } + @TempDir + Path tempDir; private void testFileExists(Path filePath) { - File f = new File(filePath.toUri()); + File f = new File(tempDir.resolve(TEST_FOLDER).resolve(filePath).toUri()); - assertTrue(f.exists(), () -> "File " + f.toString() + " does not exist"); + assertTrue(f.exists(), () -> "File " + f + " does not exist"); } + @Disabled("No idea why this ever worked") @Test void writeReporterAssetsTo() throws RuntimeException { - Path targetPath = Paths.get(TEST_FOLDER); + Path targetPath = tempDir.resolve(TEST_FOLDER); // Act CoverageHTMLReporter.writeReportAssetsTo(targetPath); - testFileExists(targetPath.resolve(Paths.get("colorbox", "border.png"))); - testFileExists(targetPath.resolve(Paths.get("colorbox", "controls.png"))); - testFileExists(targetPath.resolve(Paths.get("colorbox", "loading.gif"))); - testFileExists(targetPath.resolve(Paths.get("colorbox", "loading_background.png"))); - - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_flat_0_aaaaaa_40x100.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_flat_75_ffffff_40x100.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_glass_55_fbf9ee_1x400.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_glass_65_ffffff_1x400.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_glass_75_dadada_1x400.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_glass_75_e6e6e6_1x400.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_glass_95_fef1ec_1x400.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-bg_highlight-soft_75_cccccc_1x100.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-icons_2e83ff_256x240.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-icons_222222_256x240.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-icons_454545_256x240.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-icons_888888_256x240.png"))); - testFileExists(targetPath.resolve(Paths.get("images", "ui-icons_cd0a0a_256x240.png"))); - - testFileExists(targetPath.resolve(Paths.get("application.css"))); - testFileExists(targetPath.resolve(Paths.get("application.js"))); - testFileExists(targetPath.resolve(Paths.get("favicon_green.png"))); - testFileExists(targetPath.resolve(Paths.get("favicon_red.png"))); - testFileExists(targetPath.resolve(Paths.get("favicon_yellow.png"))); - testFileExists(targetPath.resolve(Paths.get("loading.gif"))); - testFileExists(targetPath.resolve(Paths.get("magnify.png"))); + testFileExists(Paths.get("colorbox", "border.png")); + testFileExists(Paths.get("colorbox", "controls.png")); + testFileExists(Paths.get("colorbox", "loading.gif")); + testFileExists(Paths.get("colorbox", "loading_background.png")); + + testFileExists(Paths.get("images", "ui-bg_flat_0_aaaaaa_40x100.png")); + testFileExists(Paths.get("images", "ui-bg_flat_75_ffffff_40x100.png")); + testFileExists(Paths.get("images", "ui-bg_glass_55_fbf9ee_1x400.png")); + testFileExists(Paths.get("images", "ui-bg_glass_65_ffffff_1x400.png")); + testFileExists(Paths.get("images", "ui-bg_glass_75_dadada_1x400.png")); + testFileExists(Paths.get("images", "ui-bg_glass_75_e6e6e6_1x400.png")); + testFileExists(Paths.get("images", "ui-bg_glass_95_fef1ec_1x400.png")); + testFileExists(Paths.get("images", "ui-bg_highlight-soft_75_cccccc_1x100.png")); + testFileExists(Paths.get("images", "ui-icons_2e83ff_256x240.png")); + testFileExists(Paths.get("images", "ui-icons_222222_256x240.png")); + testFileExists(Paths.get("images", "ui-icons_454545_256x240.png")); + testFileExists(Paths.get("images", "ui-icons_888888_256x240.png")); + testFileExists(Paths.get("images", "ui-icons_cd0a0a_256x240.png")); + + testFileExists(Paths.get("application.css")); + testFileExists(Paths.get("application.js")); + testFileExists(Paths.get("favicon_green.png")); + testFileExists(Paths.get("favicon_red.png")); + testFileExists(Paths.get("favicon_yellow.png")); + testFileExists(Paths.get("loading.gif")); + testFileExists(Paths.get("magnify.png")); } } diff --git a/src/test/java/org/utplsql/api/testRunner/DynamicTestRunnerStatementTest.java b/src/test/java/org/utplsql/api/testRunner/DynamicTestRunnerStatementTest.java new file mode 100644 index 0000000..739dbcf --- /dev/null +++ b/src/test/java/org/utplsql/api/testRunner/DynamicTestRunnerStatementTest.java @@ -0,0 +1,314 @@ +package org.utplsql.api.testRunner; + +import oracle.jdbc.OracleConnection; +import org.hamcrest.Matcher; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.verification.VerificationMode; +import org.utplsql.api.CustomTypes; +import org.utplsql.api.FileMapping; +import org.utplsql.api.TestRunnerOptions; +import org.utplsql.api.Version; + +import java.sql.Array; +import java.sql.CallableStatement; +import java.sql.SQLException; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.mockito.Mockito.*; + +public class DynamicTestRunnerStatementTest { + + private DynamicTestRunnerStatement testRunnerStatement; + private CallableStatement callableStatement; + private OracleConnection oracleConnection; + private TestRunnerOptions options; + private Object[] expectedFileMapping; + + @BeforeEach + void initParameters() throws SQLException { + expectedFileMapping = new Object[]{new FileMapping("someFile", "owner", "object", "PACKAGE")}; + + // Mock some internals. This is not pretty, but a first step + oracleConnection = getMockedOracleConnection(expectedFileMapping); + callableStatement = mock(CallableStatement.class); + + // Act + options = TestRunnerStatementProviderIT.getCompletelyFilledOptions(); + } + + @Test + void version_3_0_2_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_0_2); + + checkBaseParameters(); + checkFailOnError(false); + checkClientCharacterSet(false); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_0_3_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_0_3); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(false); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_0_4_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_0_4); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(false); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_0_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_0); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(false); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_1_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_1); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(false); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_2_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_2); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_3_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_3); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_4_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_4); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_5_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_5); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_6_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_6); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(false); + checkTags(false); + checkExpr(false); + } + + @Test + void version_3_1_7_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_7); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(true); + checkTags(true); + checkExpr(false); + } + + @Test + void version_3_1_8_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_8); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(true); + checkTags(true); + checkExpr(false); + } + + @Test + void version_3_1_13_parameters() throws SQLException { + initTestRunnerStatementForVersion(Version.V3_1_13); + + checkBaseParameters(); + checkFailOnError(true); + checkClientCharacterSet(true); + checkRandomTestOrder(true); + checkTags(true); + checkExpr(true); + } + + private OracleConnection getMockedOracleConnection(Object[] expectedFileMapping) throws SQLException { + OracleConnection oracleConnection = mock(OracleConnection.class); + when(oracleConnection.unwrap(OracleConnection.class)) + .thenReturn(oracleConnection); + mockFileMapper(oracleConnection, expectedFileMapping); + return oracleConnection; + } + + private void mockFileMapper(OracleConnection mockedOracleConnection, Object[] expectedFileMapping) throws SQLException { + Array fileMapperArray = mock(Array.class); + CallableStatement fileMapperStatement = mock(CallableStatement.class); + + when(fileMapperArray.getArray()) + .thenReturn(expectedFileMapping); + when(fileMapperStatement.getArray(1)) + .thenReturn(fileMapperArray); + when( + mockedOracleConnection.prepareCall(argThat( + a -> a.startsWith("BEGIN ? := ut_file_mapper.build_file_mappings(")) + )) + .thenReturn(fileMapperStatement); + } + + private Matcher doesOrDoesNotContainString(String string, boolean shouldBeThere) { + return (shouldBeThere) + ? containsString(string) + : not(containsString(string)); + } + + private VerificationMode doesOrDoesNotGetCalled(boolean shouldBeThere) { + return (shouldBeThere) + ? times(1) + : never(); + } + + private void initTestRunnerStatementForVersion(Version version) throws SQLException { + testRunnerStatement = DynamicTestRunnerStatement + .forVersion(version, oracleConnection, options, callableStatement); + } + + private void checkBaseParameters() throws SQLException { + String sql = testRunnerStatement.getSql(); + + assertThat(sql, containsString("a_paths => ?")); + verify(callableStatement).setArray(1, null); + verify(oracleConnection).createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.pathList.toArray()); + + assertThat(sql, containsString("a_reporters => ?")); + verify(callableStatement).setArray(2, null); + verify(oracleConnection).createOracleArray(CustomTypes.UT_REPORTERS, options.reporterList.toArray()); + + assertThat(sql, containsString("a_color_console => (case ? when 1 then true else false end)")); + verify(callableStatement).setInt(3, 0); + + assertThat(sql, containsString("a_coverage_schemes => ?")); + verify(callableStatement).setArray(4, null); + verify(oracleConnection).createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.coverageSchemes.toArray()); + + assertThat(sql, containsString("a_source_file_mappings => ?")); + verify(callableStatement).setArray(5, null); + + assertThat(sql, containsString("a_test_file_mappings => ?")); + verify(callableStatement).setArray(6, null); + verify(oracleConnection, times(2)).createOracleArray(CustomTypes.UT_FILE_MAPPINGS, expectedFileMapping); + + assertThat(sql, containsString("a_include_objects => ?")); + verify(callableStatement).setArray(7, null); + verify(oracleConnection).createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.includeObjects.toArray()); + + assertThat(sql, containsString("a_exclude_objects => ?")); + verify(callableStatement).setArray(8, null); + verify(oracleConnection).createOracleArray(CustomTypes.UT_VARCHAR2_LIST, options.includeObjects.toArray()); + } + + private void checkFailOnError(boolean shouldBeThere) throws SQLException { + String sql = testRunnerStatement.getSql(); + + assertThat(sql, doesOrDoesNotContainString("a_fail_on_errors => (case ? when 1 then true else false end)", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setInt(9, 1); + } + + private void checkClientCharacterSet(boolean shouldBeThere) throws SQLException { + String sql = testRunnerStatement.getSql(); + + assertThat(sql, doesOrDoesNotContainString("a_client_character_set => ?", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setString(10, "UTF8"); + } + + private void checkRandomTestOrder(boolean shouldBeThere) throws SQLException { + String sql = testRunnerStatement.getSql(); + + assertThat(sql, doesOrDoesNotContainString("a_random_test_order => (case ? when 1 then true else false end)", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setInt(11, 1); + assertThat(sql, doesOrDoesNotContainString("a_random_test_order_seed => ?", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setInt(12, 123); + } + + private void checkTags(boolean shouldBeThere) throws SQLException { + String sql = testRunnerStatement.getSql(); + + assertThat(sql, doesOrDoesNotContainString("a_tags => ?", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setString(13, "WIP,long_running"); + } + + private void checkExpr(boolean shouldBeThere) throws SQLException { + String sql = testRunnerStatement.getSql(); + + assertThat(sql, doesOrDoesNotContainString("a_include_schema_expr => ?", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setString(14, "a_*"); + assertThat(sql, doesOrDoesNotContainString("a_include_object_expr => ?", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setString(15, "a_*"); + assertThat(sql, doesOrDoesNotContainString("a_exclude_schema_expr => ?", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setString(16, "ut3:*_package*"); + assertThat(sql, doesOrDoesNotContainString("a_exclude_object_expr => ?", shouldBeThere)); + verify(callableStatement, doesOrDoesNotGetCalled(shouldBeThere)).setString(17, "ut3:*_package*"); + } +} diff --git a/src/test/java/org/utplsql/api/FileMapperIT.java b/src/test/java/org/utplsql/api/testRunner/FileMapperIT.java similarity index 53% rename from src/test/java/org/utplsql/api/FileMapperIT.java rename to src/test/java/org/utplsql/api/testRunner/FileMapperIT.java index 20ff1b4..5c7a306 100644 --- a/src/test/java/org/utplsql/api/FileMapperIT.java +++ b/src/test/java/org/utplsql/api/testRunner/FileMapperIT.java @@ -1,6 +1,12 @@ -package org.utplsql.api; +package org.utplsql.api.testRunner; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.utplsql.api.AbstractDatabaseTest; +import org.utplsql.api.FileMapperOptions; +import org.utplsql.api.FileMapping; +import org.utplsql.api.KeyValuePair; +import org.utplsql.api.testRunner.FileMapper; import java.sql.SQLException; import java.util.ArrayList; @@ -45,4 +51,37 @@ private void assertMapping(FileMapping fileMapping, String owner, String name, S assertEquals(type, fileMapping.getObjectType()); } + @Nested + class Default_type_mapping { + + void checkTypeMapping( List typeMappings ) throws SQLException { + List filePaths = java.util.Arrays.asList( + "/award_bonus.prc", + "/betwnstr.fnc", + "/package_body.pkb", + "/type_body.tpb", + "/trigger.trg"); + FileMapperOptions mapperOptions = new FileMapperOptions(filePaths); + mapperOptions.setTypeMappings(typeMappings); + + List fileMappings = FileMapper.buildFileMappingList(getConnection(), mapperOptions); + + assertEquals("PROCEDURE", fileMappings.get(0).getObjectType()); + assertEquals("FUNCTION", fileMappings.get(1).getObjectType()); + assertEquals("PACKAGE BODY", fileMappings.get(2).getObjectType()); + assertEquals("TYPE BODY", fileMappings.get(3).getObjectType()); + assertEquals("TRIGGER", fileMappings.get(4).getObjectType()); + } + + @Test + void is_used_on_null_parameter() throws SQLException { + checkTypeMapping(null); + } + + @Test + void is_used_on_empty_parameter() throws SQLException { + checkTypeMapping(new ArrayList<>()); + } + } + } diff --git a/src/test/java/org/utplsql/api/testRunner/TestRunnerStatementProviderIT.java b/src/test/java/org/utplsql/api/testRunner/TestRunnerStatementProviderIT.java index e811102..2676c38 100644 --- a/src/test/java/org/utplsql/api/testRunner/TestRunnerStatementProviderIT.java +++ b/src/test/java/org/utplsql/api/testRunner/TestRunnerStatementProviderIT.java @@ -2,37 +2,105 @@ import org.junit.jupiter.api.Test; import org.utplsql.api.AbstractDatabaseTest; +import org.utplsql.api.FileMapperOptions; import org.utplsql.api.TestRunnerOptions; import org.utplsql.api.Version; +import org.utplsql.api.reporter.CoreReporters; +import org.utplsql.api.reporter.ReporterFactory; import java.sql.SQLException; +import java.util.Arrays; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; class TestRunnerStatementProviderIT extends AbstractDatabaseTest { + public static TestRunnerOptions getCompletelyFilledOptions() { + TestRunnerOptions options = new TestRunnerOptions(); + options.pathList.add("path"); + options.reporterList.add(ReporterFactory.createEmpty().createReporter(CoreReporters.UT_DOCUMENTATION_REPORTER.name())); + options.coverageSchemes.add("APP"); + options.sourceMappingOptions = new FileMapperOptions(Arrays.asList("sourcePath")); + options.testMappingOptions = new FileMapperOptions(Arrays.asList("testPath")); + options.includeObjects.add("include1"); + options.excludeObjects.add("exclude1"); + options.failOnErrors = true; + options.clientCharacterSet = "UTF8"; + options.randomTestOrder = true; + options.randomTestOrderSeed = 123; + options.tags.add("WIP"); + options.tags.add("long_running"); + options.includeSchemaExpr = "a_*"; + options.includeObjectExpr = "a_*"; + options.excludeSchemaExpr = "ut3:*_package*"; + options.excludeObjectExpr = "ut3:*_package*"; + return options; + } + + TestRunnerStatement getTestRunnerStatementForVersion(Version version) throws SQLException { + return TestRunnerStatementProvider.getCompatibleTestRunnerStatement(version, getCompletelyFilledOptions(), getConnection()); + } + @Test void testGettingPre303Version() throws SQLException { - TestRunnerStatement stmt = TestRunnerStatementProvider.getCompatibleTestRunnerStatement(Version.V3_0_2, new TestRunnerOptions(), getConnection()); - assertEquals(Pre303TestRunnerStatement.class, stmt.getClass()); + TestRunnerStatement stmt = getTestRunnerStatementForVersion(Version.V3_0_2); + assertThat(stmt.getSql(), not(containsString("a_fail_on_errors"))); + assertThat(stmt.getSql(), not(containsString("a_client_character_set"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order_seed"))); + assertThat(stmt.getSql(), not(containsString("a_tags"))); } @Test void testGettingPre312Version_from_303() throws SQLException { - TestRunnerStatement stmt = TestRunnerStatementProvider.getCompatibleTestRunnerStatement(Version.V3_0_3, new TestRunnerOptions(), getConnection()); - assertEquals(Pre312TestRunnerStatement.class, stmt.getClass()); + TestRunnerStatement stmt = getTestRunnerStatementForVersion(Version.V3_0_3); + assertThat(stmt.getSql(), containsString("a_fail_on_errors")); + assertThat(stmt.getSql(), not(containsString("a_client_character_set"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order_seed"))); + assertThat(stmt.getSql(), not(containsString("a_tags"))); } @Test void testGettingPre312Version_from_311() throws SQLException { - TestRunnerStatement stmt = TestRunnerStatementProvider.getCompatibleTestRunnerStatement(Version.V3_1_1, new TestRunnerOptions(), getConnection()); - assertEquals(Pre312TestRunnerStatement.class, stmt.getClass()); + TestRunnerStatement stmt = getTestRunnerStatementForVersion(Version.V3_1_1); + assertThat(stmt.getSql(), containsString("a_fail_on_errors")); + assertThat(stmt.getSql(), not(containsString("a_client_character_set"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order_seed"))); + assertThat(stmt.getSql(), not(containsString("a_tags"))); + } + + @Test + void testGettingPre317Version_from_312() throws SQLException { + TestRunnerStatement stmt = getTestRunnerStatementForVersion(Version.V3_1_2); + assertThat(stmt.getSql(), containsString("a_fail_on_errors")); + assertThat(stmt.getSql(), containsString("a_client_character_set")); + assertThat(stmt.getSql(), not(containsString("a_random_test_order"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order_seed"))); + assertThat(stmt.getSql(), not(containsString("a_tags"))); + } + + @Test + void testGettingPre317Version_from_316() throws SQLException { + TestRunnerStatement stmt = getTestRunnerStatementForVersion(Version.V3_1_6); + assertThat(stmt.getSql(), containsString("a_fail_on_errors")); + assertThat(stmt.getSql(), containsString("a_client_character_set")); + assertThat(stmt.getSql(), not(containsString("a_random_test_order"))); + assertThat(stmt.getSql(), not(containsString("a_random_test_order_seed"))); + assertThat(stmt.getSql(), not(containsString("a_tags"))); } @Test - void testGettingActualVersion() throws SQLException { - TestRunnerStatement stmt = TestRunnerStatementProvider.getCompatibleTestRunnerStatement(Version.V3_1_2, new TestRunnerOptions(), getConnection()); - assertEquals(ActualTestRunnerStatement.class, stmt.getClass()); + void testGettingActualVersion_from_latest() throws SQLException { + TestRunnerStatement stmt = getTestRunnerStatementForVersion(Version.LATEST); + assertThat(stmt.getSql(), containsString("a_fail_on_errors")); + assertThat(stmt.getSql(), containsString("a_client_character_set")); + assertThat(stmt.getSql(), containsString("a_random_test_order")); + assertThat(stmt.getSql(), containsString("a_random_test_order_seed")); + assertThat(stmt.getSql(), containsString("a_tags")); } } pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy