diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a852896 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,27 @@ +name: CI Pipeline +on: + push: + branches: + - master + pull_request: + +jobs: + Build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Set up JDK + uses: actions/setup-java@v1 + with: + java-version: 8 + + - name: Build and test + run: ./gradlew clean build -x ktlintCheck -x ktlintFormat + continue-on-error: true + + - name: Test report + uses: asadmansr/android-test-report-action@v1.2.0 + + - name: Lint + run: ./gradlew ktlintCheck ktlintFormat diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..52406d6 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,37 @@ +name: Publish +on: + workflow_dispatch: + inputs: + ci: + description: "CI pipeline name" + required: false + default: "ci.yml" + +jobs: + Publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Inject slug/short variables + uses: rlespinasse/github-slug-action@v2.x + + - name: Check CI status + run: | + output=$(curl -sSL -X GET -G -H "Accept: application/vnd.github.v3+json" -d "branch=${{ env.GITHUB_REF_SLUG }}" -d "event=push" https://api.github.com/repos/${{ github.repository }}/actions/workflows/${{ github.event.inputs.ci }}/runs | jq -r '.workflow_runs[0] | "\(.conclusion)"') + echo "::set-output name=status::$output" + id: check + + - name: Abort if CI not successful + if: steps.check.outputs.status != 'success' + run: | + echo ${{ steps.check.outputs.status }} + exit 1 + + - name: Set up JDK + uses: actions/setup-java@v1 + with: + java-version: 8 + + - name: Publish to Bintray + run: ./gradlew -P bintrayUser=${{ secrets.BINTRAY_USER }} -P bintrayKey=${{ secrets.BINTRAY_KEY }} bintrayUpload diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f1fbeb0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Mac +.DS_Store + +# Logs +*.log + +# Eclipse +.classpath +.project +.settings/ +bin/ + +# IntelliJ +.idea/ +*.iml + +# Maven +target/ + +# Gradle +build/ +.gradle/ +userHome/ +out/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..80a9786 --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ +# grpc-test + +Includes a JUnit 5 [Extension](https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/extension/Extension.html) +that can automatically release gRPC resources at the end of the test. Like [GrpcCleanupRule](https://grpc.github.io/grpc-java/javadoc/io/grpc/testing/GrpcCleanupRule.html), +but built for JUnit 5 and actively maintained. + +Requires Java 8 or later. Verified working with the latest JUnit 5 version, which you can find in the [gradle.properties](gradle.properties). + +[![](https://github.com/asarkar/grpc-test/workflows/CI%20Pipeline/badge.svg)](https://github.com/asarkar/grpc-test/actions?query=workflow%3A%22CI+Pipeline%22) + +## Installation + +You can find the latest version on Bintray. [ ![Download](https://api.bintray.com/packages/asarkar/mvn/com.asarkar.grpc%3Agrpc-test/images/download.svg) ](https://bintray.com/asarkar/mvn/com.asarkar.grpc%3Agrpc-test/_latestVersion) + +It is also on Maven Central and jcenter. + +## Usage + +Declare a `Resources` in one of the three following ways, and register `Server` and/or `ManagedChannel` instances with it. + +Get a `Resources` from: +1. A test method parameter injection, or +2. An instance variable, or +3. A static variable. + +The difference is in the lifecycle of the `Resources` object. For `#1`, a new instance is created for every test method. +`#2` is the same as `#1` unless the test class declares `@TestInstance(TestInstance.Lifecycle.PER_CLASS)`, in which case +one instance is shared among all the tests. `#3` is obviously one instance shared among all the tests. + + +``` +@ExtendWith(GrpcCleanupExtension.class) +class ExampleTestCase { + @Test + void testSuccessful(Resources resources) { + resources.register(server); // use default timeout + resources.register(channel, Duration.ofSeconds(1)); // override default timeout + resources.timeout(Duration.ofSeconds(3)); // change default timeout to 3 seconds + resources.register(channel2) // channel2 timeout is 3 seconds; server and channel timeouts didn't change + } +} + +``` + +## Contribute + +This project is a volunteer effort. You are welcome to send pull requests, ask questions, or create issues. +If you like it, you can help by spreading the word! + +## License + +Copyright 2020 Abhijit Sarkar - Released under [Apache License v2.0](LICENSE). diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..175ede9 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,142 @@ +plugins { + kotlin("jvm") + `maven-publish` + id("org.jetbrains.dokka") + id("org.jlleitschuh.gradle.ktlint") + id("com.jfrog.bintray") +} + +val projectGroup: String by project +val projectVersion: String by project +val projectDescription: String by project +group = projectGroup +version = projectVersion +description = projectDescription + +repositories { + jcenter() +} + +val jUnitVersion: String by project +val gRPCVersion: String by project +val mockitoVersion: String by project +val jUnitTestkitVersion: String by project + +dependencies { + implementation(kotlin("stdlib-jdk8")) + implementation(platform("io.grpc:grpc-bom:$gRPCVersion")) + implementation(platform("org.junit:junit-bom:$jUnitVersion")) + implementation("org.junit.jupiter:junit-jupiter-api") + implementation("io.grpc:grpc-api") + testImplementation("org.junit.jupiter:junit-jupiter") + testImplementation("org.mockito:mockito-core:$mockitoVersion") + testImplementation("org.mockito:mockito-junit-jupiter:$mockitoVersion") + testImplementation("org.junit.platform:junit-platform-testkit:$jUnitTestkitVersion") +} + +plugins.withType { + extensions.configure { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } +} + +tasks.withType { + kotlinOptions { + freeCompilerArgs = listOf("-Xjsr305=strict") + jvmTarget = "1.8" + } +} + +tasks.withType { + outputFormat = "html" + outputDirectory = "$buildDir/javadoc" +} + +val sourcesJar by tasks.creating(Jar::class) { + group = JavaBasePlugin.DOCUMENTATION_GROUP + description = "Creates a sources JAR" + archiveClassifier.set("sources") + from(sourceSets.main.get().allSource) +} + +val kdocJar by tasks.creating(Jar::class) { + group = JavaBasePlugin.DOCUMENTATION_GROUP + description = "Creates KDoc" + archiveClassifier.set("javadoc") + from(tasks.dokka) +} + +tasks.jar.configure { + finalizedBy(sourcesJar, kdocJar) +} + +val licenseName: String by project +val licenseUrl: String by project +val developerName: String by project +val developerEmail: String by project +val gitHubUsername: String by project + +val gitHubUrl: String by lazy { "github.com/$gitHubUsername/${project.name}" } + +publishing { + publications { + create("maven") { + from(components["java"]) + artifact(kdocJar) + artifact(sourcesJar) + pom { + name.set("${project.group}:${project.name}") + description.set(project.description) + url.set("https://$gitHubUrl") + licenses { + license { + name.set(licenseName) + url.set(licenseUrl) + } + } + developers { + developer { + name.set(developerName) + email.set(developerEmail) + } + } + scm { + connection.set("scm:git:git://$gitHubUrl.git") + developerConnection.set("scm:git:ssh://github.com:$gitHubUsername/${project.name}.git") + url.set("https://$gitHubUrl") + } + } + } + } +} + +val bintrayRepo: String by project +bintray { + user = (findProperty("bintrayUser") ?: System.getenv("BINTRAY_USER"))?.toString() + key = (findProperty("bintrayKey") ?: System.getenv("BINTRAY_KEY"))?.toString() + setPublications(*publishing.publications.names.toTypedArray()) + with(pkg) { + repo = bintrayRepo + name = "${project.group}:${project.name}" + desc = project.description + websiteUrl = "https://$gitHubUrl" + vcsUrl = "https://$gitHubUrl.git" + setLabels("grpc", "protobuf", "test", "junit5", "junit") + setLicenses(licenseName) + with(version) { + name = project.version.toString() + with(gpg) { + sign = true + } + with(mavenCentralSync) { + sync = true + user = (findProperty("sonatypeUser") ?: System.getenv("SONATYPE_USER"))?.toString() + password = (findProperty("sonatypePwd") ?: System.getenv("SONATYPE_PWD"))?.toString() + } + } + } + publish = true + override = false + dryRun = false +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6857123 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,20 @@ +kotlin.code.style=official + +jUnitVersion=5.6.2 +gRPCVersion=1.31.0 +mockitoVersion=3.4.6 +jUnitTestkitVersion=1.6.2 +kotlinPluginVersion=1.3.72 +dokkaPluginVersion=0.10.1 +ktlintVersion=9.3.0 +bintrayPluginVersion=1.8.5 + +projectGroup=com.asarkar.grpc +projectVersion=1.0.0 +projectDescription=JUnit5 Extension that can automatically release gRPC resources at the end of the test +licenseName=Apache-2.0 +licenseUrl=http://www.apache.org/licenses/LICENSE-2.0.txt +developerName=Abhijit Sarkar +developerEmail=contact@asarkar.com +gitHubUsername=asarkar +bintrayRepo=mvn \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..62d4c05 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..bb8b2fc --- /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-6.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..fbd7c51 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..a9f778a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,104 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..e1ec453 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,15 @@ +pluginManagement { + val kotlinPluginVersion: String by settings + val dokkaPluginVersion: String by settings + val ktlintVersion: String by settings + val bintrayPluginVersion: String by settings + plugins { + kotlin("jvm") version kotlinPluginVersion + `maven-publish` + id("org.jetbrains.dokka") version dokkaPluginVersion + id("org.jlleitschuh.gradle.ktlint") version ktlintVersion + id("com.jfrog.bintray") version bintrayPluginVersion + } +} + +rootProject.name = "grpc-test" diff --git a/src/main/kotlin/com/asarkar/grpc/test/GrpcCleanupExtension.kt b/src/main/kotlin/com/asarkar/grpc/test/GrpcCleanupExtension.kt new file mode 100644 index 0000000..64e5b9a --- /dev/null +++ b/src/main/kotlin/com/asarkar/grpc/test/GrpcCleanupExtension.kt @@ -0,0 +1,146 @@ +package com.asarkar.grpc.test + +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.extension.AfterAllCallback +import org.junit.jupiter.api.extension.AfterEachCallback +import org.junit.jupiter.api.extension.BeforeAllCallback +import org.junit.jupiter.api.extension.BeforeEachCallback +import org.junit.jupiter.api.extension.ExtensionContext +import org.junit.jupiter.api.extension.ParameterContext +import org.junit.jupiter.api.extension.ParameterResolver +import org.junit.platform.commons.JUnitException +import org.junit.platform.commons.PreconditionViolationException +import java.lang.reflect.Field +import java.lang.reflect.Modifier +import kotlin.reflect.KFunction1 + +/** + * A JUnit 5 [Extension](https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/extension/Extension.html) that can register gRPC resources and manages their automatic release at + * the end of the test. If any of the registered resources can not be successfully released, fails the test. + * Keeping in line with the [GrpcCleanupRule](https://grpc.github.io/grpc-java/javadoc/io/grpc/testing/GrpcCleanupRule.html), + * tries to force release if the test has already failed. + * + * @author Abhijit Sarkar + * @since 1.0.0 + * + * @throws [PreconditionViolationException] if a test method or class declares more than one [Resources]. + * @throws [PostconditionViolationException] if one or more registered resources can not be successfully released. + * @throws [JUnitException] if there is an unexpected problem. + */ +class GrpcCleanupExtension : + BeforeEachCallback, AfterEachCallback, ParameterResolver, BeforeAllCallback, AfterAllCallback { + private var resources: Resources? = null + private var resourcesField: Field? = null + + override fun beforeEach(ctx: ExtensionContext) { + val resources = ctx.requiredTestMethod.parameters + .filter { it.type == Resources::class.java } + if (resources.size > 1) { + throw PreconditionViolationException("At most one parameter of type Resources may be declared by a method") + } + + if (shouldAccessResourcesField(ctx)) { + trySet(ctx.requiredTestInstance) + } + } + + override fun afterEach(ctx: ExtensionContext) { + var successful = true + this.resources?.also { + getCleanUpMethod(ctx)(it) + successful = it.awaitReleased() + } + + if (shouldAccessResourcesField(ctx)) { + tryGet(ctx.requiredTestInstance)?.also { + getCleanUpMethod(ctx)(it) + if (!it.awaitReleased()) { + if (!successful) throw PostconditionViolationException("$resources and $it couldn't be released") + else throw PostconditionViolationException("$it couldn't be released") + } + } + } + if (!successful) throw PostconditionViolationException("$resources couldn't be released") + } + + override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean { + return parameterContext.parameter.type == Resources::class.java + } + + override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any { + return Resources().also { resources = it } + } + + override fun beforeAll(ctx: ExtensionContext) { + val field = findField(ctx) + + if (field != null) { + try { + field.isAccessible = true + } catch (e: ReflectiveOperationException) { + throw JUnitException("Illegal state: Cannot access Resources field", e) + } + resourcesField = field + trySet(ctx.testInstance.orElse(null)) + } + } + + override fun afterAll(ctx: ExtensionContext) { + tryGet(ctx.testInstance.orElse(null))?.also { + getCleanUpMethod(ctx)(it) + if (!it.awaitReleased()) throw PostconditionViolationException("$it couldn't be released") + } + } + + private fun shouldAccessResourcesField(ctx: ExtensionContext): Boolean { + return resourcesField != null && + ctx.testInstanceLifecycle.orElse(null) != TestInstance.Lifecycle.PER_CLASS && + !resourcesField.isStatic() + } + + private fun trySet(target: Any?) { + try { + resourcesField?.takeIf { target != null || it.isStatic() }?.set(target, Resources()) + } catch (e: ReflectiveOperationException) { + throw JUnitException("Illegal state: Cannot set Resources field", e) + } + } + + private fun tryGet(target: Any?): Resources? { + return try { + resourcesField?.takeIf { target != null || it.isStatic() }?.get(target) as Resources? + } catch (e: ReflectiveOperationException) { + throw JUnitException("Illegal state: Cannot get Resources field", e) + } + } + + private fun getCleanUpMethod(ctx: ExtensionContext): KFunction1 { + return if (ctx.executionException.isPresent) Resources::forceCleanUp else Resources::cleanUp + } + + private fun Field?.isStatic() = this != null && Modifier.isStatic(this.modifiers) + + private fun findField(ctx: ExtensionContext): Field? { + return generateSequence?, Field?>>((ctx.requiredTestClass to null)) { (clazz, field) -> + val fields = try { + clazz!!.declaredFields.filter { it.type == Resources::class.java } + } catch (e: ReflectiveOperationException) { + throw JUnitException("Illegal state: Cannot find Resources field", e) + } + if (fields.size > 1) { + throw PreconditionViolationException("At most one field of type Resources may be declared by a class") + } + val fld = fields.firstOrNull() + when { + fld != null -> (clazz to fld) + clazz.superclass != null -> (clazz.superclass to field) + else -> (null to field) + } + } + .dropWhile { it.first != null && it.second == null } + .take(1) + .iterator() + .next() + .second + } +} diff --git a/src/main/kotlin/com/asarkar/grpc/test/PostconditionViolationException.kt b/src/main/kotlin/com/asarkar/grpc/test/PostconditionViolationException.kt new file mode 100644 index 0000000..87e8960 --- /dev/null +++ b/src/main/kotlin/com/asarkar/grpc/test/PostconditionViolationException.kt @@ -0,0 +1,11 @@ +package com.asarkar.grpc.test + +import org.junit.platform.commons.JUnitException + +/** + * Thrown if a [Resource] cannot be released. + * + * @author Abhijit Sarkar + * @since 1.0.0 + */ +class PostconditionViolationException(message: String, cause: Throwable? = null) : JUnitException(message, cause) diff --git a/src/main/kotlin/com/asarkar/grpc/test/Resource.kt b/src/main/kotlin/com/asarkar/grpc/test/Resource.kt new file mode 100644 index 0000000..bcabefc --- /dev/null +++ b/src/main/kotlin/com/asarkar/grpc/test/Resource.kt @@ -0,0 +1,68 @@ +package com.asarkar.grpc.test + +import io.grpc.ManagedChannel +import io.grpc.Server +import java.time.Duration +import java.util.concurrent.TimeUnit + +/** + * An abstraction of a resource used by the test that will be released at the end. + * + * @author Abhijit Sarkar + * @since 1.0.0 + */ +interface Resource { + fun cleanUp() + + fun forceCleanUp() + + fun awaitReleased(duration: Duration): Boolean +} + +sealed class AbstractResource(private val e: E) : Resource { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as AbstractResource<*> + + return e == other.e + } + + override fun hashCode(): Int { + return e.hashCode() + } + + override fun toString(): String { + return e.toString() + } +} + +internal class ManagedChannelResource internal constructor(private val channel: ManagedChannel) : + AbstractResource(channel) { + override fun cleanUp() { + channel.shutdown() + } + + override fun forceCleanUp() { + channel.shutdownNow() + } + + override fun awaitReleased(duration: Duration): Boolean { + return channel.awaitTermination(duration.toNanos(), TimeUnit.NANOSECONDS) + } +} + +internal class ServerResource internal constructor(private val server: Server) : AbstractResource(server) { + override fun cleanUp() { + server.shutdown() + } + + override fun forceCleanUp() { + server.shutdownNow() + } + + override fun awaitReleased(duration: Duration): Boolean { + return server.awaitTermination(duration.toNanos(), TimeUnit.NANOSECONDS) + } +} diff --git a/src/main/kotlin/com/asarkar/grpc/test/Resources.kt b/src/main/kotlin/com/asarkar/grpc/test/Resources.kt new file mode 100644 index 0000000..51f3c37 --- /dev/null +++ b/src/main/kotlin/com/asarkar/grpc/test/Resources.kt @@ -0,0 +1,107 @@ +package com.asarkar.grpc.test + +import io.grpc.ManagedChannel +import io.grpc.Server +import java.time.Duration +import java.time.Instant +import java.util.Objects + +/** + * A collection of [Resource]s used by the test that will be released at the end. + * + * @author Abhijit Sarkar + * @since 1.0.0 + */ +class Resources { + private val resources = mutableMapOf() + private var timeout = Duration.ofSeconds(5) + + /** + * Registers the given server with the extension. Once registered, the server will be automatically + * shutdown at the end of the test. + * + * @param server server that will be registered. + * @param timeout a positive time limit for the server to shutdown. If it fails to shutdown + * in time, the test will fail. Defaults to 5 seconds. + * + * @return this + */ + fun register(server: T, timeout: Duration = this.timeout): Resources { + return this.apply { this@Resources.resources[ServerResource(server)] = timeout } + } + + /** + * Registers the given channel with the extension. Once registered, the channel will be automatically + * closed at the end of the test. + * + * @param channel channel that will be registered. + * @param timeout a positive time limit for the channel to close. If it fails to close + * in time, the test will fail. Defaults to 5 seconds. + * + * @return this + */ + fun register(channel: T, timeout: Duration = this.timeout): Resources { + return this.apply { + this@Resources.resources[ + ManagedChannelResource(channel) + ] = timeout + } + } + + /** + * A positive time limit for the registered resources to be released. If the resources fail to + * release in time, the test will fail. Defaults to 5 seconds. Calling this method does not change + * the timeout for the resources previously registered. + * + * @param timeout + * + * @return this + */ + fun timeout(timeout: Duration): Resources { + return this.apply { this@Resources.timeout = timeout } + } + + internal fun cleanUp() { + resources.keys.forEach { it.cleanUp() } + } + + internal fun forceCleanUp() { + resources.keys.forEach { it.forceCleanUp() } + } + + internal fun awaitReleased(): Boolean { + val start = Instant.now() + var successful = true + resources.forEach { (r, t) -> + try { + val timeout = t.minus(Duration.between(Instant.now(), start)) + if (timeout.isNegative || !r.awaitReleased(timeout)) { + successful = false + r.forceCleanUp() + } + } catch (e: InterruptedException) { + successful = false + Thread.currentThread().interrupt() + r.forceCleanUp() + } + } + return successful + } + + override fun toString(): String { + return if (resources.isEmpty()) "Resources[]" else "Resources${resources.keys.map { it.toString() }}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Resources + + return resources.keys == other.resources.keys + } + + override fun hashCode(): Int { + return Objects.hashCode(resources.keys) + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase.kt b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase.kt new file mode 100644 index 0000000..c135467 --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase.kt @@ -0,0 +1,56 @@ +package com.asarkar.grpc.test + +import io.grpc.ManagedChannel +import io.grpc.Server +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.ArgumentMatchers +import org.mockito.Mockito +import java.lang.Thread.sleep +import java.time.Duration +import java.util.concurrent.TimeUnit + +@ExtendWith(GrpcCleanupExtension::class) +class ExampleTestCase { + private var server = Mockito.mock(Server::class.java) + private var channel = Mockito.mock(ManagedChannel::class.java) + + @Test + fun testSuccessful(resources: Resources) { + Mockito.`when`(server.awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java))) + .thenReturn(true) + Mockito.`when`(channel.awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java))) + .thenReturn(true) + resources.register(server).register(channel) + } + + @Test + fun testFailedShutdown(resources: Resources) { + Mockito.`when`(server.awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java))) + .thenReturn(true) + resources.register(server).register(channel) + } + + @Test + fun testException(resources: Resources) { + Mockito.`when`(server.awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java))) + .thenReturn(true) + Mockito.`when`(channel.awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java))) + .thenReturn(true) + resources.register(server).register(channel) + throw RuntimeException("Boom") + } + + @Test + fun testTimeout(resources: Resources) { + Mockito.`when`(server.awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java))) + .thenAnswer { sleep(1000); true } + resources.register(server).register(channel, Duration.ofMillis(500)) + } + + @Test + fun testMultipleParameters(resources: Resources, resources2: Resources) { + resources.register(server) + resources2.register(server) + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase2.kt b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase2.kt new file mode 100644 index 0000000..8363d60 --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase2.kt @@ -0,0 +1,27 @@ +package com.asarkar.grpc.test + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.Mockito + +@ExtendWith(GrpcCleanupExtension::class) +class ExampleTestCase2 { + private var resources: Resources? = null + private val setOfResources: Set = mutableSetOf() + private val set = Mockito.spy(setOfResources) + + @Test + fun test1() { + setOfResources.plus(resources) + } + + @Test + fun test2() { + setOfResources.plus(resources) + } + + @Test + fun test3() { + setOfResources.plus(resources) + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase3.kt b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase3.kt new file mode 100644 index 0000000..17d1aa5 --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase3.kt @@ -0,0 +1,29 @@ +package com.asarkar.grpc.test + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.Mockito + +@ExtendWith(GrpcCleanupExtension::class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class ExampleTestCase3 { + private var resources: Resources? = null + private val setOfResources: Set = mutableSetOf() + private val set = Mockito.spy(setOfResources) + + @Test + fun test1() { + setOfResources.plus(resources) + } + + @Test + fun test2() { + setOfResources.plus(resources) + } + + @Test + fun test3() { + setOfResources.plus(resources) + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase4.kt b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase4.kt new file mode 100644 index 0000000..ba1be5d --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase4.kt @@ -0,0 +1,30 @@ +package com.asarkar.grpc.test + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(GrpcCleanupExtension::class) +class ExampleTestCase4 { + @Test + fun test1() { + setOfResources.add(resources) + } + + @Test + fun test2() { + setOfResources.add(resources) + } + + @Test + fun test3() { + setOfResources.add(resources) + } + + companion object { + @JvmStatic + internal val setOfResources: MutableSet = mutableSetOf() + + @JvmStatic + private var resources: Resources? = null + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase5.kt b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase5.kt new file mode 100644 index 0000000..10e438b --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase5.kt @@ -0,0 +1,20 @@ +package com.asarkar.grpc.test + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.Mockito + +open class BaseTestCase { + protected var resources: Resources? = null +} + +@ExtendWith(GrpcCleanupExtension::class) +class ExampleTestCase5 : BaseTestCase() { + private val setOfResources: Set = mutableSetOf() + private val set = Mockito.spy(setOfResources) + + @Test + fun testInheritResource() { + setOfResources.plus(super.resources) + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase6.kt b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase6.kt new file mode 100644 index 0000000..6d83142 --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/ExampleTestCase6.kt @@ -0,0 +1,14 @@ +package com.asarkar.grpc.test + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(GrpcCleanupExtension::class) +class ExampleTestCase6 { + private var resources: Resources? = null + private var resources2: Resources? = null + + @Test + fun testMultipleInstances() { + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/GrpcCleanupExtensionIntegrationTests.kt b/src/test/kotlin/com/asarkar/grpc/test/GrpcCleanupExtensionIntegrationTests.kt new file mode 100644 index 0000000..16d444a --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/GrpcCleanupExtensionIntegrationTests.kt @@ -0,0 +1,272 @@ +package com.asarkar.grpc.test + +import io.grpc.ManagedChannel +import io.grpc.Server +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.platform.commons.PreconditionViolationException +import org.junit.platform.engine.discovery.DiscoverySelectors.selectClass +import org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod +import org.junit.platform.testkit.engine.EngineTestKit +import org.junit.platform.testkit.engine.EventConditions.event +import org.junit.platform.testkit.engine.EventConditions.finishedSuccessfully +import org.junit.platform.testkit.engine.EventConditions.finishedWithFailure +import org.junit.platform.testkit.engine.TestExecutionResultConditions.instanceOf +import org.mockito.ArgumentMatchers +import org.mockito.Mockito +import org.mockito.listeners.MockCreationListener +import java.util.concurrent.TimeUnit + +class GrpcCleanupExtensionIntegrationTests { + @Test + fun testSuccessful() { + val mocks = mutableListOf() + val listener = MockCreationListener { mock, _ -> mocks.add(mock) } + Mockito.framework().addListener(listener) + EngineTestKit.engine("junit-jupiter") + .selectors( + selectMethod( + ExampleTestCase::class.java, + ExampleTestCase::class.java.getDeclaredMethod("testSuccessful", Resources::class.java) + ) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 1, + event(finishedSuccessfully()) + ) + + assertThat(mocks).hasSize(2) + + val server = mocks.find { it is Server } as Server? + assertThat(server).isNotNull + Mockito.verify(server)!!.shutdown() + Mockito.verify(server)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + val channel = mocks.find { it is ManagedChannel } as ManagedChannel? + assertThat(channel).isNotNull + Mockito.verify(channel)!!.shutdown() + Mockito.verify(channel)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + } + + @Test + fun testFailedShutdown() { + val mocks = mutableListOf() + val listener = MockCreationListener { mock, _ -> mocks.add(mock) } + Mockito.framework().addListener(listener) + EngineTestKit.engine("junit-jupiter") + .selectors( + selectMethod( + ExampleTestCase::class.java, + ExampleTestCase::class.java.getDeclaredMethod("testFailedShutdown", Resources::class.java) + ) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 1, + event(finishedWithFailure(instanceOf(PostconditionViolationException::class.java))) + ) + + assertThat(mocks).hasSize(2) + + val server = mocks.find { it is Server } as Server? + assertThat(server).isNotNull + Mockito.verify(server)!!.shutdown() + Mockito.verify(server)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + val channel = mocks.find { it is ManagedChannel } as ManagedChannel? + assertThat(channel).isNotNull + Mockito.verify(channel)!!.shutdown() + Mockito.verify(channel)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + } + + @Test + fun testException() { + val mocks = mutableListOf() + val listener = MockCreationListener { mock, _ -> mocks.add(mock) } + Mockito.framework().addListener(listener) + EngineTestKit.engine("junit-jupiter") + .selectors( + selectMethod( + ExampleTestCase::class.java, + ExampleTestCase::class.java.getDeclaredMethod("testException", Resources::class.java) + ) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 1, + event(finishedWithFailure(instanceOf(RuntimeException::class.java))) + ) + + assertThat(mocks).hasSize(2) + + val server = mocks.find { it is Server } as Server? + assertThat(server).isNotNull + Mockito.verify(server)!!.shutdownNow() + Mockito.verify(server)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + val channel = mocks.find { it is ManagedChannel } as ManagedChannel? + assertThat(channel).isNotNull + Mockito.verify(channel)!!.shutdownNow() + Mockito.verify(channel)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + } + + @Test + fun testTimeout() { + val mocks = mutableListOf() + val listener = MockCreationListener { mock, _ -> mocks.add(mock) } + Mockito.framework().addListener(listener) + EngineTestKit.engine("junit-jupiter") + .selectors( + selectMethod( + ExampleTestCase::class.java, + ExampleTestCase::class.java.getDeclaredMethod("testTimeout", Resources::class.java) + ) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 1, + event(finishedWithFailure(instanceOf(PostconditionViolationException::class.java))) + ) + assertThat(mocks).hasSize(2) + + val server = mocks.find { it is Server } as Server? + assertThat(server).isNotNull + Mockito.verify(server)!!.shutdown() + Mockito.verify(server)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + val channel = mocks.find { it is ManagedChannel } as ManagedChannel? + assertThat(channel).isNotNull + Mockito.verify(channel)!!.shutdown() + Mockito.verify(channel)!! + .awaitTermination(ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit::class.java)) + } + + @Test + fun testReinitializeInstanceVariableForEachTest() { + val mocks = mutableListOf() + val listener = MockCreationListener { mock, _ -> mocks.add(mock) } + Mockito.framework().addListener(listener) + EngineTestKit.engine("junit-jupiter") + .selectors( + selectClass(ExampleTestCase2::class.java) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 3, + event(finishedSuccessfully()) + ) + + assertThat(mocks).allMatch { it is Set<*> } + assertThat(mocks.map { it as Set<*> }.toSet()).hasSize(3) + } + + @Test + fun testInitializeInstanceVariableOnlyOnce() { + val mocks = mutableListOf() + val listener = MockCreationListener { mock, _ -> mocks.add(mock) } + Mockito.framework().addListener(listener) + EngineTestKit.engine("junit-jupiter") + .selectors( + selectClass(ExampleTestCase3::class.java) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 3, + event(finishedSuccessfully()) + ) + + assertThat(mocks).allMatch { it is Set<*> } + assertThat(mocks.map { it as Set<*> }.toSet()).hasSize(1) + } + + @Test + fun testInitializeStaticVariableOnlyOnce() { + EngineTestKit.engine("junit-jupiter") + .selectors( + selectClass(ExampleTestCase4::class.java) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 3, + event(finishedSuccessfully()) + ) + + assertThat(ExampleTestCase4.setOfResources).hasSize(1) + } + + @Test + fun testInheritResource() { + val mocks = mutableListOf() + val listener = MockCreationListener { mock, _ -> mocks.add(mock) } + Mockito.framework().addListener(listener) + EngineTestKit.engine("junit-jupiter") + .selectors( + selectClass(ExampleTestCase5::class.java) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 1, + event(finishedSuccessfully()) + ) + + assertThat(mocks).allMatch { it is Set<*> } + assertThat(mocks.map { it as Set<*> }.toSet()).hasSize(1) + } + + @Test + fun testMultipleParameters() { + EngineTestKit.engine("junit-jupiter") + .selectors( + selectMethod( + ExampleTestCase::class.java, + ExampleTestCase::class.java.getDeclaredMethod( + "testMultipleParameters", Resources::class.java, Resources::class.java + ) + ) + ) + .execute() + .testEvents() + .assertThatEvents() + .haveExactly( + 1, + event(finishedWithFailure(instanceOf(PreconditionViolationException::class.java))) + ) + } + + @Test + fun testMultipleInstances() { + EngineTestKit.engine("junit-jupiter") + .selectors( + selectClass( + ExampleTestCase6::class.java + ) + ) + .execute() + .allEvents() + .assertThatEvents() + .haveExactly( + 1, + event(finishedWithFailure(instanceOf(PreconditionViolationException::class.java))) + ) + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/GrpcCleanupExtensionTests.kt b/src/test/kotlin/com/asarkar/grpc/test/GrpcCleanupExtensionTests.kt new file mode 100644 index 0000000..08d815c --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/GrpcCleanupExtensionTests.kt @@ -0,0 +1,17 @@ +package com.asarkar.grpc.test + +import org.assertj.core.api.Assertions +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(GrpcCleanupExtension::class) +class GrpcCleanupExtensionTests { + private var resources: Resources? = null + + @Test + fun testParameterInjection(resources: Resources) { + Assertions.assertThat(this.resources).isNotNull + Assertions.assertThat(resources).isNotNull + Assertions.assertThat(resources).isNotSameAs(this.resources) + } +} diff --git a/src/test/kotlin/com/asarkar/grpc/test/ResourcesTest.kt b/src/test/kotlin/com/asarkar/grpc/test/ResourcesTest.kt new file mode 100644 index 0000000..6ad0333 --- /dev/null +++ b/src/test/kotlin/com/asarkar/grpc/test/ResourcesTest.kt @@ -0,0 +1,34 @@ +package com.asarkar.grpc.test + +import io.grpc.Server +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.mockito.Mockito + +class ResourcesTest { + @Test + fun testEquality() { + val server = Mockito.mock(Server::class.java) + val resources1 = Resources().apply { register(server) } + val resources2 = Resources().apply { register(server) } + + assertThat(resources1).isEqualTo(resources2) + } + + @Test + fun testHashCode() { + val server = Mockito.mock(Server::class.java) + val resources = Resources().apply { register(server) } + + assertThat(resources.hashCode()).isEqualTo(server.hashCode()) + } + + @Test + fun testToString() { + val server = Mockito.mock(Server::class.java, "mock") + val resources = Resources().apply { register(server) } + + assertThat(resources.toString()).isEqualTo("Resources[mock]") + assertThat(Resources().toString()).isEqualTo("Resources[]") + } +}