diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..26ade2b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +name: CI +on: + push: + branches: + - main + pull_request: + +# Ensures that only one task per branch/environment will run at a time. +concurrency: + group: test-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + with: + # https://adoptium.net + distribution: 'temurin' + java-version: '17' + cache: 'gradle' + - name: Build + run: ./gradlew shadowJar --no-daemon diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..176b49c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,26 @@ +name: Release + +on: + push: + tags: + - "v*.*.*" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + with: + # https://adoptium.net + distribution: 'temurin' + java-version: '17' + cache: 'gradle' + - name: Build + run: ./gradlew shadowJar --no-daemon + - name: Release + uses: softprops/action-gh-release@v1 + with: + files: build/libs/codewars-junit-runner.jar + fail_on_unmatched_files: true + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ccc787e --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.gradle/ +.vscode/ +bin/ +build/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c19e668 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Qualified, Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b62e6a7 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# JUnit Runner + +Standalone JUnit runner for Codewars. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..9a14737 --- /dev/null +++ b/build.gradle @@ -0,0 +1,33 @@ +plugins { + // Create jar with dependencies + id 'com.github.johnrengelman.shadow' version '7.1.2' + id 'java' +} + +repositories { + mavenCentral() +} + +group = 'com.codewars' +version = '0.0.1' + +dependencies { + implementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' + implementation 'org.junit.jupiter:junit-jupiter-params:5.8.2' + implementation 'org.junit.platform:junit-platform-launcher:1.8.2' + implementation 'org.junit.jupiter:junit-jupiter-engine:5.8.2' + implementation 'org.junit.vintage:junit-vintage-engine:5.8.2' +} + +jar { + manifest { + attributes 'Main-Class': 'com.codewars.junit5.TestRunner' + } +} + +shadowJar { + // Always output build/libs/codewars-junit-runner.jar + archiveBaseName.set('codewars-junit-runner') + archiveClassifier.set('') + archiveVersion.set('') +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..41dfb87 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..f27bba6 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'junit-runner' diff --git a/src/main/java/com/codewars/junit5/CodewarsListener.java b/src/main/java/com/codewars/junit5/CodewarsListener.java new file mode 100644 index 0000000..801c62f --- /dev/null +++ b/src/main/java/com/codewars/junit5/CodewarsListener.java @@ -0,0 +1,213 @@ +package com.codewars.junit5; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.lang.Throwable; +import java.util.Optional; +import java.util.Map; +import java.util.NavigableSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.stream.Collectors; + +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.reporting.ReportEntry; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.TestPlan; + +// https://github.com/junit-team/junit5/blob/master/junit-platform-console/src/main/java/org/junit/platform/console/tasks/XmlReportData.java +public class CodewarsListener implements TestExecutionListener { + private int failures; + private int testCount; + private final Map startInstants = new ConcurrentHashMap<>(); + private final Map endInstants = new ConcurrentHashMap<>(); + private final ConcurrentHashMap> reportEntries = new ConcurrentHashMap<>(); + private final Clock clock; + + CodewarsListener() { + failures = 0; + testCount = 0; + clock = Clock.systemDefaultZone(); + } + + @Override + public void testPlanExecutionStarted(TestPlan testPlan) { + // System.out.printf("\nTestPlan Execution Started: %s\n", testPlan); + } + + @Override + public void testPlanExecutionFinished(TestPlan testPlan) { + // System.out.printf("\nTestPlan Execution Finished: %s\n", testPlan); + } + + @Override + public void dynamicTestRegistered(TestIdentifier testIdentifier) { + // System.out.printf("\nDynamic Test Registered: %s - %s\n", + // testIdentifier.getDisplayName(), testIdentifier.getUniqueId()); + } + + @Override + public void executionStarted(TestIdentifier testIdentifier) { + // Skip root identifer, e.g., [engine:junit-jupiter] + if (!testIdentifier.getParentId().isPresent()) { + return; + } + markStarted(testIdentifier); + if (testIdentifier.isContainer()) { + System.out.printf("\n%s\n", testIdentifier.getDisplayName()); + } else if (testIdentifier.isTest()) { + ++testCount; + System.out.printf("\n%s\n", testIdentifier.getDisplayName()); + } + } + + // TODO consider adding `` and display properly + @Override + public void executionSkipped(TestIdentifier testIdentifier, String reason) { + if (testIdentifier.isContainer()) { + System.out.printf("\n[SKIPPED] %s\n", testIdentifier.getDisplayName()); + if (reason != null && reason != "") { + System.out.printf("\n%s\n", reason); + } + System.out.println("\n"); + } else if (testIdentifier.isTest()) { + System.out.printf("\n[SKIPPED] %s\n", testIdentifier.getDisplayName()); + if (reason != null && reason != "") { + System.out.printf("\n%s\n", reason); + } + System.out.println("\n"); + } + } + + @Override + public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { + // Skip root identifer, e.g., [engine:junit-jupiter] + if (!testIdentifier.getParentId().isPresent()) { + return; + } + markFinished(testIdentifier); + outputReportEntries(testIdentifier); + + switch (testExecutionResult.getStatus()) { + case SUCCESSFUL: + if (testIdentifier.isTest()) { + System.out.println("\nTest Passed"); + } + System.out.printf("\n%d\n", getDuration(testIdentifier)); + break; + + case ABORTED: // assumptions not met + if (testIdentifier.isTest()) { + ++failures; + Optional th = testExecutionResult.getThrowable(); + if (th.isPresent()) { + outputFailure("Aborted", th.get()); + } else { + System.out.println("\nAborted for unknown cause"); + } + } + System.out.printf("\n%d\n", getDuration(testIdentifier)); + break; + + case FAILED: + if (testIdentifier.isTest()) { + ++failures; + Optional th = testExecutionResult.getThrowable(); + if (th.isPresent()) { + outputFailure("Failed", th.get()); + } else { + System.out.println("\nFailed for unknown cause"); + } + } + System.out.printf("\n%d\n", getDuration(testIdentifier)); + break; + + default: + throw new Error("Unsupported execution status:" + testExecutionResult.getStatus()); + } + } + + // > In JUnit Jupiter you should use `TestReporter` where you used to print + // information to `stdout` or `stderr` in JUnit 4. + // ```java + // @Test + // void reportSingleValue(TestReporter testReporter) { + // testReporter.publishEntry("a key", "a value"); + // } + // ``` + public void reportingEntryPublished(TestIdentifier testIdentifier, ReportEntry entry) { + reportEntries(testIdentifier).add(reportEntryToString(entry)); + } + + public int failures() { + return failures; + } + + public int testCount() { + return testCount; + } + + private static void outputFailure(String kind, Throwable throwable) { + String msg = throwable.getMessage(); + if (msg == null) { + System.out.printf("\nTest %s\n", kind); + } else { + System.out.printf("\n%s\n", formatMessage(msg)); + } + System.out.printf("\n%s\n", formatMessage(readStackTrace(throwable))); + } + + // Read the stacktrace of the supplied {@link Throwable} into a String. + // https://github.com/junit-team/junit5/blob/946c5980074f466de0688297a6d661d32679599a/junit-platform-commons/src/main/java/org/junit/platform/commons/util/ExceptionUtils.java#L76 + private static String readStackTrace(Throwable throwable) { + StringWriter sw = new StringWriter(); + try (PrintWriter pw = new PrintWriter(sw)) { + throwable.printStackTrace(pw); + } + return sw.toString(); + } + + private void markStarted(TestIdentifier testIdentifier) { + this.startInstants.put(testIdentifier, this.clock.instant()); + } + + private void markFinished(TestIdentifier testIdentifier) { + this.endInstants.put(testIdentifier, this.clock.instant()); + } + + private long getDuration(TestIdentifier testIdentifier) { + Instant start = this.startInstants.getOrDefault(testIdentifier, Instant.EPOCH); + Instant end = this.endInstants.getOrDefault(testIdentifier, start); + return Duration.between(start, end).toMillis(); + } + + private static String formatMessage(final String s) { + return (s == null) ? "" : s.replaceAll("\n", "<:LF:>"); + } + + private NavigableSet reportEntries(TestIdentifier testIdentifier) { + return this.reportEntries.computeIfAbsent(testIdentifier, k -> new ConcurrentSkipListSet()); + } + + private void outputReportEntries(TestIdentifier testIdentifier) { + NavigableSet entries = reportEntries(testIdentifier); + if (entries.isEmpty()) + return; + + String reports = entries.stream().collect(Collectors.joining("\n\n")); + System.out.printf("\n%s\n", formatMessage(reports)); + } + + private String reportEntryToString(ReportEntry entry) { + return entry + .getKeyValuePairs() + .entrySet() + .stream() + .map(e -> e.getKey() + " = " + e.getValue()) + .collect(Collectors.joining("\n")); + } +} diff --git a/src/main/java/com/codewars/junit5/TestRunner.java b/src/main/java/com/codewars/junit5/TestRunner.java new file mode 100644 index 0000000..c7df9ce --- /dev/null +++ b/src/main/java/com/codewars/junit5/TestRunner.java @@ -0,0 +1,155 @@ +package com.codewars.junit5; + +import static java.util.Collections.emptyList; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClasspathRoots; +import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Stream; + +import org.junit.platform.commons.JUnitException; +import org.junit.platform.engine.discovery.ClasspathRootSelector; +import org.junit.platform.launcher.core.LauncherFactory; + +public class TestRunner { + private List classpathEntries = emptyList(); + + // Runs all tests found in given classpaths + // `java -jar junit-runner.jar + // './jars/*:./classes/java/main:./classe/java/test'` + public static void main(String[] args) throws Exception { + if (args.length != 1) { + System.err.println("Missing classpath"); + System.exit(1); + } + + // There's some race in shutdown hooks registered by Spring Boot. + // HACK Don't run shutdown hooks to avoid the following exception: + // Exception in thread "SpringContextShutdownHook" + // java.lang.NoClassDefFoundError: ch/qos/logback/classic/spi/ThrowableProxy + int status = new TestRunner(args[0]).execute(); + Runtime.getRuntime().halt(status); + // System.exit(status); + } + + private TestRunner(String classPath) { + this.classpathEntries = Arrays.stream(classPath.split(File.pathSeparator)) + .flatMap(this::expandWildcard) + .collect(toList()); + } + + private int execute() throws Exception { + return callWithCustomClassLoader(() -> executeTests()); + } + + private int executeTests() { + var listener = new CodewarsListener(); + var launcher = LauncherFactory.create(); + launcher.registerTestExecutionListeners(listener); + var discoveryRequest = request().selectors(createClasspathRootSelectors()).build(); + launcher.execute(discoveryRequest); + if (listener.testCount() == 0) { // no tests found + return 2; + } + if (listener.failures() > 0) { + return 1; + } + return 0; + } + + private List createClasspathRootSelectors() { + var rootDirs = new LinkedHashSet<>(getAllClasspathRootDirectories()); + var dirs = this.classpathEntries.stream().filter(Files::isDirectory).filter(Files::exists) + .collect(toList()); + rootDirs.addAll(dirs); + return selectClasspathRoots(rootDirs); + } + + private Optional createCustomClassLoader() { + var entries = this.classpathEntries.stream().filter(Files::exists) + .collect(toList()); + if (!entries.isEmpty()) { + var urls = entries.stream().map(this::toURL).toArray(URL[]::new); + return Optional.of(URLClassLoader.newInstance(urls, getDefaultClassLoader())); + } + return Optional.empty(); + } + + private URL toURL(Path path) { + try { + return path.toUri().toURL(); + } catch (Exception ex) { + throw new JUnitException("Invalid classpath entry: " + path, ex); + } + } + + private Stream expandWildcard(String spath) { + if (!spath.endsWith("*")) { + return Stream.of(Paths.get(spath)); + } + + try { + var path = Paths.get(spath.substring(0, spath.length() - 1)); + if (path.toFile().isDirectory()) { + return Files.list(path).filter(p -> p.getFileName().toString().endsWith(".jar")); + } + // Invalid entry + return Stream.empty(); + } catch (IOException e) { + e.printStackTrace(); + return Stream.empty(); + } + } + + private Set getAllClasspathRootDirectories() { + return Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator)) + .map(Paths::get) + .filter(Files::isDirectory) + .collect(toSet()); + } + + private ClassLoader getDefaultClassLoader() { + try { + var contextClassLoader = Thread.currentThread().getContextClassLoader(); + if (contextClassLoader != null) { + return contextClassLoader; + } + } catch (Throwable t) { + // ignore + } + return ClassLoader.getSystemClassLoader(); + } + + T callWithCustomClassLoader(Callable callable) throws Exception { + var customClassLoader = createCustomClassLoader(); + if (!customClassLoader.isPresent()) { + return callable.call(); + } + + var loader = customClassLoader.get(); + var originalClassLoader = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(loader); + return callable.call(); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + if (loader instanceof AutoCloseable) { + ((AutoCloseable) loader).close(); + } + } + } +}