diff --git a/.github/ci-gradle.properties b/.github/ci-gradle.properties new file mode 100644 index 000000000..e69de29bb diff --git a/.github/workflows/composescreenshot.yml b/.github/workflows/composescreenshot.yml new file mode 100644 index 000000000..c717f8305 --- /dev/null +++ b/.github/workflows/composescreenshot.yml @@ -0,0 +1,24 @@ +# Workflow name +name: Compose Preview Screenshot +on: + # When it will be triggered + # And in which branch + pull_request: + branches: [ main ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set Up JDK + uses: actions/setup-java@v3 + with: + distribution: 'zulu' # See 'Supported distributions' for available options + java-version: '17' + cache: 'gradle' + + - name: Build project and run screenshot tests + working-directory: ./ui/PreviewScreenshot + run: ./gradlew validateDebugScreenshotTest diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml new file mode 100644 index 000000000..41735cbf2 --- /dev/null +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -0,0 +1,16 @@ +name: Validate Gradle Wrapper + +on: + push: + branches: [ main ] + + pull_request: + branches: [ main ] + +jobs: + validation: + name: Validation + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: gradle/wrapper-validation-action@v1 diff --git a/.github/workflows/test-all.yml b/.github/workflows/test-all.yml new file mode 100644 index 000000000..2c0b5d626 --- /dev/null +++ b/.github/workflows/test-all.yml @@ -0,0 +1,43 @@ +# Workflow name +name: Build + Test all +on: + # When it will be triggered + # And in which branch + pull_request: + branches: [ main ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Enable KVM group perms + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + ls /dev/kvm + + - name: Set Up JDK + uses: actions/setup-java@v3 + with: + distribution: 'zulu' # See 'Supported distributions' for available options + java-version: '17' + cache: 'gradle' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Setup Android SDK + uses: android-actions/setup-android@v3 + + - name: Build project and run local and device tests + run: ./test_all.sh + + - name: Upload test reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-reports + path: '**/app/build/reports/androidTests' diff --git a/.gitignore b/.gitignore index 473d7f1e4..2e822ca17 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ build .settings/ .classpath bazel-* +.DS_Store diff --git a/BUILD.bazel b/BUILD.bazel index 37d1372c7..114654e5c 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -46,5 +46,9 @@ platform( name: "dockerPrivileged" value: "true" } + properties: { + name: "gceMachineType" + value: "n1-standard-2" + } """, ) diff --git a/README.md b/README.md index 396c6c9e2..09c9728d1 100644 --- a/README.md +++ b/README.md @@ -5,46 +5,48 @@ A collection of samples demonstrating different frameworks and techniques for au ### Espresso Samples -**[BasicSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/BasicSample)** - Basic Espresso sample +**[BasicSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/BasicSample)** - Basic Espresso sample -**[CustomMatcherSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/CustomMatcherSample)** - Shows how to extend Espresso to match the *hint* property of an EditText +**[CustomMatcherSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/CustomMatcherSample)** - Shows how to extend Espresso to match the *hint* property of an EditText -**[DataAdapterSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/DataAdapterSample)** - Showcases the `onData()` entry point for Espresso, for lists and AdapterViews +**[DataAdapterSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/DataAdapterSample)** - Showcases the `onData()` entry point for Espresso, for lists and AdapterViews -**[FragmentScenarioSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/FragmentScenarioSample)** - Basic usage of `FragmentScenario` with Espresso. +**[FragmentScenarioSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/FragmentScenarioSample)** - Basic usage of `FragmentScenario` with Espresso. -**[IdlingResourceSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/IdlingResourceSample)** - Synchronization with background jobs +**[IdlingResourceSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/IdlingResourceSample)** - Synchronization with background jobs -**[IntentsBasicSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/IntentsBasicSample)** - Basic usage of `intended()` and `intending()` +**[IntentsBasicSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/IntentsBasicSample)** - Basic usage of `intended()` and `intending()` -**[IntentsAdvancedSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/IntentsAdvancedSample)** - Simulates a user fetching a bitmap using the camera +**[IntentsAdvancedSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/IntentsAdvancedSample)** - Simulates a user fetching a bitmap using the camera -**[MultiWindowSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/MultiWindowSample)** - Shows how to point Espresso to different windows +**[MultiWindowSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/MultiWindowSample)** - Shows how to point Espresso to different windows -**[RecyclerViewSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/RecyclerViewSample)** - RecyclerView actions for Espresso +**[RecyclerViewSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/RecyclerViewSample)** - RecyclerView actions for Espresso -**[WebBasicSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/WebBasicSample)** - Use Espresso-web to interact with WebViews +**[ScreenshotSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/ScreenshotSample)** - Screenshot capturing and saving using Espresso and androidx.test.core APIs -**[BasicSampleBundled](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/BasicSampleBundled)** - Basic sample for Eclipse and other IDEs +**[WebBasicSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/WebBasicSample)** - Use Espresso-web to interact with WebViews -**[MultiProcessSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/MultiProcessSample)** - Showcases how to use multiprocess Espresso. +**[BasicSampleBundled](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/BasicSampleBundled)** - Basic sample for Eclipse and other IDEs + +**[MultiProcessSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/MultiProcessSample)** - Showcases how to use multiprocess Espresso. ### UiAutomator Sample -**[BasicSample](https://github.com/googlesamples/android-testing/tree/master/ui/uiautomator/BasicSample)** - Basic UI Automator sample +**[BasicSample](https://github.com/googlesamples/android-testing/tree/main/ui/uiautomator/BasicSample)** - Basic UI Automator sample ### AndroidJUnitRunner Sample -**[AndroidJunitRunnerSample](https://github.com/googlesamples/android-testing/tree/master/runner/AndroidJunitRunnerSample)** - Showcases test annotations, parameterized tests and testsuite creation +**[AndroidJunitRunnerSample](https://github.com/googlesamples/android-testing/tree/main/runner/AndroidJunitRunnerSample)** - Showcases test annotations, parameterized tests and testsuite creation ### JUnit4 Rules Sample **All previous samples use ActivityTestRule or IntentsTestRule but there's one specific to ServiceTestRule: -**[BasicSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/BasicSample)** - Simple usage of `ActivityTestRule` +**[BasicSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/BasicSample)** - Simple usage of `ActivityTestRule` -**[IntentsBasicSample](https://github.com/googlesamples/android-testing/blob/master/ui/espresso/IntentsBasicSample)** - Simple usage of `IntentsTestRule` +**[IntentsBasicSample](https://github.com/googlesamples/android-testing/blob/main/ui/espresso/IntentsBasicSample)** - Simple usage of `IntentsTestRule` -**[ServiceTestRuleSample](https://github.com/googlesamples/android-testing/tree/master/integration/ServiceTestRuleSample)** - Simple usage of `ServiceTestRule` +**[ServiceTestRuleSample](https://github.com/googlesamples/android-testing/tree/main/integration/ServiceTestRuleSample)** - Simple usage of `ServiceTestRule` Prerequisites -------------- diff --git a/WORKSPACE b/WORKSPACE index e293c6948..868cb6fde 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -2,12 +2,7 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external") # Set the path to your local SDK installation, or use the ANDROID_HOME environment variable. -android_sdk_repository( - name = "androidsdk", - api_level = 28, - build_tools_version = "28.0.2", - # path = "/path/to/sdk", -) +android_sdk_repository(name = "androidsdk") # Required for running emulator tests on RBE on Bazel CI android_ndk_repository(name = "androidndk") diff --git a/bazelci/buildkite-pipeline.yml b/bazelci/buildkite-pipeline.yml index c95da91e9..89474fcfe 100644 --- a/bazelci/buildkite-pipeline.yml +++ b/bazelci/buildkite-pipeline.yml @@ -1,24 +1,95 @@ # https://github.com/googlesamples/android-testing#experimental-bazel-support --- platforms: - ubuntu1604: - build_targets: - - "//..." - test_flags: - - "--config=remote_android" - - "--flaky_test_attempts=3" - test_targets: - - "//..." - - "-//ui/espresso/AccessibilitySample/..." ubuntu1804: build_targets: - "//..." + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_23_x86" # BazelCI does not have Android Emulator + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_22_x86" + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_21_x86" + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_19_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_23_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_22_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_21_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_19_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_23_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_22_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_21_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_19_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_23_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_22_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_21_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_19_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_23_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_22_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_21_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_19_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_23_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_22_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_21_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_19_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_23_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_22_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_21_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_19_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_23_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_22_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_21_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_19_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_23_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_22_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_21_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_19_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_23_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_22_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_21_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_19_x86" test_flags: - "--config=remote_android" - "--flaky_test_attempts=3" test_targets: - "//..." - "-//ui/espresso/AccessibilitySample/..." + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_23_x86" # BazelCI does not have Android Emulator + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_22_x86" + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_21_x86" + - "-//ui/uiautomator/BasicSample:BasicSampleInstrumentationTest_19_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_23_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_22_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_21_x86" + - "-//ui/espresso/RecyclerViewSample:RecyclerViewSampleInstrumentationTest_19_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_23_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_22_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_21_x86" + - "-//ui/espresso/MultiWindowSample:MultiWindowSampleInstrumentationTest_19_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_23_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_22_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_21_x86" + - "-//ui/espresso/IntentsBasicSample:IntentsBasicSampleInstrumentationTest_19_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_23_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_22_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_21_x86" + - "-//ui/espresso/IntentsAdvancedSample:IntentsAdvancedSampleInstrumentationTest_19_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_23_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_22_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_21_x86" + - "-//ui/espresso/IdlingResourceSample:IdlingResourceSampleInstrumentationTest_19_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_23_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_22_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_21_x86" + - "-//ui/espresso/DataAdapterSample:DataAdapterSampleInstrumentationTest_19_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_23_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_22_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_21_x86" + - "-//ui/espresso/CustomMatcherSample:CustomMatcherSampleInstrumentationTest_19_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_23_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_22_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_21_x86" + - "-//ui/espresso/BasicSample:BasicSampleInstrumentationTest_19_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_23_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_22_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_21_x86" + - "-//ui/espresso/AccessibilitySample:BasicSampleInstrumentationTest_19_x86" macos: # Testing does not work for macos and windows yet build_targets: # Results of `bazel query 'kind(android_binary, //...)' diff --git a/integration/ServiceTestRuleSample/app/build.gradle b/integration/ServiceTestRuleSample/app/build.gradle index 6a1e40b1e..5d2f7c613 100644 --- a/integration/ServiceTestRuleSample/app/build.gradle +++ b/integration/ServiceTestRuleSample/app/build.gradle @@ -1,28 +1,42 @@ -apply plugin: 'com.android.application' +apply plugin: "com.android.application" android { - compileSdkVersion 30 - buildToolsVersion rootProject.buildToolsVersion + compileSdk 34 defaultConfig { applicationId "com.example.android.testing.integrationtesting.ServiceTestRuleSample" - minSdkVersion 14 - targetSdkVersion 30 + minSdkVersion 21 + targetSdkVersion 34 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } - lintOptions { - abortOnError false - } productFlavors { } + testOptions { + managedDevices { + devices { + // run with ../gradlew nexusOneApi30DebugAndroidTest + nexusOneApi30(com.android.build.api.dsl.ManagedVirtualDevice) { + // A lower resolution device is used here for better emulator performance + device = "Nexus One" + apiLevel = 30 + // Also use the AOSP ATD image for better emulator performance + systemImageSource = "aosp-atd" + } + } + } + } + namespace "com.example.android.testing.ServiceTestRuleSample" + lint { + abortOnError false + } } dependencies { // Testing-only dependencies - androidTestImplementation 'androidx.test:core:' + rootProject.coreVersion; - androidTestImplementation 'androidx.test.ext:junit:' + rootProject.extJUnitVersion; - androidTestImplementation 'androidx.test:runner:' + rootProject.runnerVersion; - androidTestImplementation 'androidx.test:rules:' + rootProject.rulesVersion; + androidTestImplementation "androidx.test:core:" + rootProject.coreVersion; + androidTestImplementation "androidx.test.ext:junit:" + rootProject.extJUnitVersion; + androidTestImplementation "androidx.test:runner:" + rootProject.runnerVersion; + androidTestImplementation "androidx.test:rules:" + rootProject.rulesVersion; } diff --git a/integration/ServiceTestRuleSample/app/src/main/AndroidManifest.xml b/integration/ServiceTestRuleSample/app/src/main/AndroidManifest.xml index d881131aa..5dc076f8c 100644 --- a/integration/ServiceTestRuleSample/app/src/main/AndroidManifest.xml +++ b/integration/ServiceTestRuleSample/app/src/main/AndroidManifest.xml @@ -16,8 +16,7 @@ --> - + '} + 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=`basename "$0"` +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" +MAX_FD=maximum -warn ( ) { +warn () { echo "$*" -} +} >&2 -die ( ) { +die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# 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\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -82,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + 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 @@ -90,75 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + 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 -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +# 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/integration/ServiceTestRuleSample/gradlew.bat b/integration/ServiceTestRuleSample/gradlew.bat index aec99730b..ac1b06f93 100644 --- a/integration/ServiceTestRuleSample/gradlew.bat +++ b/integration/ServiceTestRuleSample/gradlew.bat @@ -1,3 +1,19 @@ +@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 @@ -8,20 +24,23 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set 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 +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,34 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_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=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/projects.conf b/projects.conf index 01e271ab1..f9b14cdb2 100644 --- a/projects.conf +++ b/projects.conf @@ -5,6 +5,7 @@ ui/espresso/AccessibilitySample ui/espresso/BasicSample ui/espresso/CustomMatcherSample ui/espresso/DataAdapterSample +ui/espresso/EspressoDeviceSample ui/espresso/FragmentScenarioSample ui/espresso/IdlingResourceSample ui/espresso/IntentsAdvancedSample @@ -12,7 +13,7 @@ ui/espresso/IntentsBasicSample ui/espresso/MultiWindowSample ui/espresso/MultiProcessSample ui/espresso/RecyclerViewSample +ui/espresso/ScreenshotSample ui/espresso/WebBasicSample ui/uiautomator/BasicSample -unit/BasicSample -unit/BasicUnitAndroidTest +unit/BasicNativeAndroidTest diff --git a/renovate.json b/renovate.json new file mode 100644 index 000000000..abf4b0566 --- /dev/null +++ b/renovate.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "local>android/.github:renovate-config" + ] +} diff --git a/runner/AndroidJunitRunnerSample/app/build.gradle b/runner/AndroidJunitRunnerSample/app/build.gradle index 5d7057c1b..072763155 100644 --- a/runner/AndroidJunitRunnerSample/app/build.gradle +++ b/runner/AndroidJunitRunnerSample/app/build.gradle @@ -1,13 +1,12 @@ -apply plugin: 'com.android.application' +apply plugin: "com.android.application" android { - compileSdkVersion 30 - buildToolsVersion rootProject.buildToolsVersion + compileSdk 34 defaultConfig { applicationId "com.example.android.testing.androidjunitrunnersample" - minSdkVersion 14 - targetSdkVersion 30 + minSdkVersion 21 + targetSdkVersion 34 versionCode 1 versionName "1.0" @@ -16,27 +15,44 @@ android { buildTypes { release { minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } productFlavors { } + testOptions { + managedDevices { + devices { + // run with ../gradlew nexusOneApi30DebugAndroidTest + nexusOneApi30(com.android.build.api.dsl.ManagedVirtualDevice) { + // A lower resolution device is used here for better emulator performance + device = "Nexus One" + apiLevel = 30 + // Also use the AOSP ATD image for better emulator performance + systemImageSource = "aosp-atd" + } + } + } + } + useLibrary "android.test.runner" - useLibrary 'android.test.runner' - - useLibrary 'android.test.base' - useLibrary 'android.test.mock' + useLibrary "android.test.base" + useLibrary "android.test.mock" + namespace "com.example.android.testing.androidjunitrunnersample" } dependencies { // App's dependencies, including test - implementation 'androidx.annotation:annotation:' + rootProject.androidxAnnotationVersion; - implementation 'com.google.guava:guava:' + rootProject.guavaVersion + implementation "androidx.annotation:annotation:" + rootProject.androidxAnnotationVersion; + implementation "com.google.guava:guava:" + rootProject.guavaVersion // Testing-only dependencies - androidTestImplementation 'androidx.test:core:' + rootProject.coreVersion; - androidTestImplementation 'androidx.test.ext:junit:' + rootProject.extJUnitVersion; - androidTestImplementation 'androidx.test:runner:' + rootProject.runnerVersion; - androidTestImplementation 'androidx.test.espresso:espresso-core:' + rootProject.espressoVersion; + androidTestImplementation "androidx.test:core:" + rootProject.coreVersion; + androidTestImplementation "androidx.test.ext:junit:" + rootProject.extJUnitVersion; + androidTestImplementation "androidx.test:runner:" + rootProject.runnerVersion; + androidTestImplementation "androidx.test.espresso:espresso-core:" + rootProject.espressoVersion; + + // https://truth.dev/ + androidTestImplementation "com.google.truth:truth:" + rootProject.truthVersion; } diff --git a/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorAddParameterizedTest.java b/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorAddParameterizedTest.java index 33cd8c560..8b2634103 100644 --- a/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorAddParameterizedTest.java +++ b/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorAddParameterizedTest.java @@ -16,26 +16,23 @@ package com.example.android.testing.androidjunitrunnersample; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.runners.Parameterized.Parameters; + +import androidx.test.filters.SmallTest; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import androidx.test.filters.SmallTest; - -import java.lang.Iterable; import java.util.Arrays; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.runners.Parameterized.Parameters; - /** * JUnit4 tests for the calculator's add logic. * - *

This test uses a Junit4s Parameterized tests features which uses annotations to pass + *

This test uses Junit4s Parameterized tests features which uses annotations to pass * parameters into a unit test. The way this works is that you have to use the {@link Parameterized} * runner to run your tests. *

@@ -73,7 +70,7 @@ public static Iterable data() { * to reuse them in your tests. */ public CalculatorAddParameterizedTest(double operandOne, double operandTwo, - double expectedResult) { + double expectedResult) { mOperandOne = operandOne; mOperandTwo = operandTwo; @@ -88,7 +85,7 @@ public void setUp() { @Test public void testAdd_TwoNumbers() { double resultAdd = mCalculator.add(mOperandOne, mOperandTwo); - assertThat(resultAdd, is(equalTo(mExpectedResult))); + assertThat(resultAdd).isEqualTo(mExpectedResult); } -} \ No newline at end of file +} diff --git a/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorTest.java b/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorTest.java index f51bc094d..f6797a081 100644 --- a/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorTest.java +++ b/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorTest.java @@ -16,16 +16,15 @@ package com.example.android.testing.androidjunitrunnersample; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import static com.google.common.truth.Truth.assertThat; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SmallTest; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + /** @@ -45,25 +44,25 @@ public void setUp() { @Test public void addTwoNumbers() { double resultAdd = mCalculator.add(1d, 1d); - assertThat(resultAdd, is(equalTo(2d))); + assertThat(resultAdd).isEqualTo(2d); } @Test public void subTwoNumbers() { double resultSub = mCalculator.sub(1d, 1d); - assertThat(resultSub, is(equalTo(0d))); + assertThat(resultSub).isEqualTo(0d); } @Test public void subWorksWithNegativeResult() { double resultSub = mCalculator.sub(1d, 17d); - assertThat(resultSub, is(equalTo(-16d))); + assertThat(resultSub).isEqualTo(-16d); } @Test public void divTwoNumbers() { double resultDiv = mCalculator.div(32d,2d); - assertThat(resultDiv, is(equalTo(16d))); + assertThat(resultDiv).isEqualTo(16d); } @Test(expected = IllegalArgumentException.class) @@ -74,7 +73,7 @@ public void divDivideByZeroThrows() { @Test public void mulTwoNumbers() { double resultMul = mCalculator.mul(32d, 2d); - assertThat(resultMul, is(equalTo(64d))); + assertThat(resultMul).isEqualTo(64d); } } \ No newline at end of file diff --git a/runner/AndroidJunitRunnerSample/app/src/main/AndroidManifest.xml b/runner/AndroidJunitRunnerSample/app/src/main/AndroidManifest.xml index ed5bc18ae..bdbe7358c 100644 --- a/runner/AndroidJunitRunnerSample/app/src/main/AndroidManifest.xml +++ b/runner/AndroidJunitRunnerSample/app/src/main/AndroidManifest.xml @@ -15,8 +15,7 @@ limitations under the License. --> - + + android:label="@string/app_name" + android:exported="true"> diff --git a/runner/AndroidJunitRunnerSample/build.gradle b/runner/AndroidJunitRunnerSample/build.gradle index 70a6beec1..2ae25590d 100644 --- a/runner/AndroidJunitRunnerSample/build.gradle +++ b/runner/AndroidJunitRunnerSample/build.gradle @@ -1,13 +1,14 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + ext.agpVersion = "8.5.0" repositories { // Insert local test repo here - jcenter() google() + mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:4.0.1' + classpath "com.android.tools.build:gradle:$agpVersion" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -17,18 +18,19 @@ buildscript { allprojects { repositories { // Insert local test repo here - jcenter() google() + mavenCentral() } } ext { - buildToolsVersion = "30.0.2" - androidxAnnotationVersion = "1.1.0" - guavaVersion = "29.0-android" - coreVersion = "1.4.0-alpha04" - extJUnitVersion = "1.1.3-alpha04" - runnerVersion = "1.4.0-alpha04" - rulesVersion = "1.4.0-alpha04" - espressoVersion = "3.4.0-alpha04" + buildToolsVersion = "32.0.0" + androidxAnnotationVersion = "1.5.0" + guavaVersion = "31.1-android" + coreVersion = "1.6.1" + extJUnitVersion = "1.2.1" + runnerVersion = "1.6.1" + rulesVersion = "1.6.1" + espressoVersion = "3.6.1" + truthVersion = "1.1.3" } diff --git a/runner/AndroidJunitRunnerSample/gradle.properties b/runner/AndroidJunitRunnerSample/gradle.properties index cbbc44ba0..be3166792 100644 --- a/runner/AndroidJunitRunnerSample/gradle.properties +++ b/runner/AndroidJunitRunnerSample/gradle.properties @@ -16,5 +16,8 @@ # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true +android.defaults.buildfeatures.buildconfig=true +android.nonFinalResIds=false +android.nonTransitiveRClass=false android.useAndroidX=true android.useAndroidX=true diff --git a/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.jar b/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.jar index 8c0fb64a8..41d9927a4 100644 Binary files a/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.jar and b/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.jar differ diff --git a/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.properties b/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.properties index 8e4f539c0..48c0a02ca 100644 --- a/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.properties +++ b/runner/AndroidJunitRunnerSample/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Tue May 19 20:39:22 PDT 2020 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip diff --git a/runner/AndroidJunitRunnerSample/gradlew b/runner/AndroidJunitRunnerSample/gradlew index 91a7e269e..1b6c78733 100755 --- a/runner/AndroidJunitRunnerSample/gradlew +++ b/runner/AndroidJunitRunnerSample/gradlew @@ -1,79 +1,129 @@ -#!/usr/bin/env bash +#!/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 UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/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/. +# ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# 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=`basename "$0"` +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" +MAX_FD=maximum -warn ( ) { +warn () { echo "$*" -} +} >&2 -die ( ) { +die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# 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\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -82,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + 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 @@ -90,75 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + 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 -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +# 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/runner/AndroidJunitRunnerSample/gradlew.bat b/runner/AndroidJunitRunnerSample/gradlew.bat index aec99730b..ac1b06f93 100644 --- a/runner/AndroidJunitRunnerSample/gradlew.bat +++ b/runner/AndroidJunitRunnerSample/gradlew.bat @@ -1,3 +1,19 @@ +@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 @@ -8,20 +24,23 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set 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 +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,34 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_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=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/runner/AndroidTestOrchestratorSample/README.md b/runner/AndroidTestOrchestratorSample/README.md index a9e671d19..4ac8bdd45 100644 --- a/runner/AndroidTestOrchestratorSample/README.md +++ b/runner/AndroidTestOrchestratorSample/README.md @@ -4,7 +4,7 @@ The Android Test Orchestrator allows you to run each of your app's tests in isol See https://developer.android.com/training/testing/junit-runner#using-android-test-orchestrator for more background. This sample is a subset of the AndroidJUnitRunner sample, but it -ilustrates how to enable the Android Test Orchestrator in the app/build.gradle file. +illustrates how to enable the Android Test Orchestrator in the app/build.gradle file. This project uses the Gradle build system. You don't need an IDE to build and execute it but Android Studio is recommended. @@ -14,11 +14,10 @@ This project uses the Gradle build system. You don't need an IDE to build and ex 1. Check out the relevant code: * The application under test is located in `src/main/java` * Tests are in `src/androidTest/java` -1. Create the test configuration with a custom runner: `androidx.test.runner.AndroidJUnitRunner` +1. Create the test configuration * Open *Run* menu | *Edit Configurations* * Add a new *Android Tests* configuration * Choose a module - * Add a *Specific instrumentation runner*: `androidx.test.runner.AndroidJUnitRunner` 1. Connect a device or start an emulator * Turn animations off. (On your device, under Settings->Developer options disable the following 3 settings: "Window animation scale", "Transition animation scale" and "Animator duration scale") diff --git a/runner/AndroidTestOrchestratorSample/app/build.gradle b/runner/AndroidTestOrchestratorSample/app/build.gradle index 5510a5f98..ddd122498 100644 --- a/runner/AndroidTestOrchestratorSample/app/build.gradle +++ b/runner/AndroidTestOrchestratorSample/app/build.gradle @@ -1,45 +1,56 @@ -apply plugin: 'com.android.application' +apply plugin: "com.android.application" android { - compileSdkVersion 30 - buildToolsVersion rootProject.buildToolsVersion + compileSdk 34 defaultConfig { applicationId "com.example.android.testing.androidtestorchestratorsample" - minSdkVersion 14 - targetSdkVersion 30 + minSdkVersion 21 + targetSdkVersion 34 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArguments clearPackageData: "true" } buildTypes { release { minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } productFlavors { } - useLibrary 'android.test.runner' - - useLibrary 'android.test.base' - useLibrary 'android.test.mock' - testOptions { - execution 'ANDROIDX_TEST_ORCHESTRATOR' + execution "ANDROIDX_TEST_ORCHESTRATOR" + managedDevices { + devices { + // run with ../gradlew nexusOneApi30DebugAndroidTest + nexusOneApi30(com.android.build.api.dsl.ManagedVirtualDevice) { + // A lower resolution device is used here for better emulator performance + device = "Nexus One" + apiLevel = 30 + // Also use the AOSP ATD image for better emulator performance + systemImageSource = "aosp-atd" + } + } + } } + namespace "com.example.android.testing.androidtestorchestratorsample" } dependencies { // App's dependencies, including test - implementation 'androidx.annotation:annotation:' + rootProject.androidxAnnotationVersion; - implementation 'com.google.guava:guava:' + rootProject.guavaVersion + implementation "androidx.annotation:annotation:" + rootProject.androidxAnnotationVersion; + implementation "com.google.guava:guava:" + rootProject.guavaVersion // Testing-only dependencies - androidTestImplementation 'androidx.test:core:' + rootProject.coreVersion; - androidTestImplementation 'androidx.test.ext:junit:' + rootProject.extJUnitVersion; - androidTestImplementation 'androidx.test:runner:' + rootProject.runnerVersion; - androidTestImplementation 'androidx.test.espresso:espresso-core:' + rootProject.espressoVersion; - androidTestUtil 'androidx.test:orchestrator:' + rootProject.runnerVersion; + androidTestImplementation "androidx.test:core:" + rootProject.coreVersion; + androidTestImplementation "androidx.test.ext:junit:" + rootProject.extJUnitVersion; + androidTestImplementation "androidx.test:runner:" + rootProject.runnerVersion; + androidTestImplementation "androidx.test:monitor:" + rootProject.monitorVersion; + androidTestImplementation "androidx.test.espresso:espresso-core:" + rootProject.espressoVersion; + androidTestImplementation "com.google.truth:truth:" + rootProject.truthVersion; + androidTestUtil "androidx.test:orchestrator:" + rootProject.orchestratorVersion; + } diff --git a/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorAddParameterizedTest.java b/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorAddParameterizedTest.java index 63c9e7146..6730ecd6b 100644 --- a/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorAddParameterizedTest.java +++ b/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorAddParameterizedTest.java @@ -16,6 +16,8 @@ package com.example.android.testing.androidtestorchestratorsample; +import static com.google.common.truth.Truth.assertThat; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,9 +28,6 @@ import java.lang.Iterable; import java.util.Arrays; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; import static org.junit.runners.Parameterized.Parameters; @@ -88,6 +87,6 @@ public void setUp() { @Test public void testAdd_TwoNumbers() { double resultAdd = mCalculator.add(mOperandOne, mOperandTwo); - assertThat(resultAdd, is(equalTo(mExpectedResult))); + assertThat(resultAdd).isEqualTo(mExpectedResult); } } \ No newline at end of file diff --git a/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorInstrumentationTest.java b/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorInstrumentationTest.java index 80b31bae5..95de2fb8a 100644 --- a/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorInstrumentationTest.java +++ b/runner/AndroidTestOrchestratorSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorInstrumentationTest.java @@ -16,6 +16,7 @@ package com.example.android.testing.androidtestorchestratorsample; +import androidx.test.platform.graphics.HardwareRendererCompat; import junit.framework.TestSuite; import org.junit.Before; diff --git a/runner/AndroidTestOrchestratorSample/app/src/main/AndroidManifest.xml b/runner/AndroidTestOrchestratorSample/app/src/main/AndroidManifest.xml index 2561a31af..aeed9db04 100644 --- a/runner/AndroidTestOrchestratorSample/app/src/main/AndroidManifest.xml +++ b/runner/AndroidTestOrchestratorSample/app/src/main/AndroidManifest.xml @@ -15,8 +15,7 @@ limitations under the License. --> - + + android:label="@string/app_name" + android:exported="true"> diff --git a/runner/AndroidTestOrchestratorSample/build.gradle b/runner/AndroidTestOrchestratorSample/build.gradle index 70a6beec1..0d83b3c4b 100644 --- a/runner/AndroidTestOrchestratorSample/build.gradle +++ b/runner/AndroidTestOrchestratorSample/build.gradle @@ -1,13 +1,14 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + ext.agpVersion = "8.5.0" repositories { // Insert local test repo here - jcenter() google() + mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:4.0.1' + classpath "com.android.tools.build:gradle:$agpVersion" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -17,18 +18,20 @@ buildscript { allprojects { repositories { // Insert local test repo here - jcenter() google() + mavenCentral() } } ext { - buildToolsVersion = "30.0.2" - androidxAnnotationVersion = "1.1.0" - guavaVersion = "29.0-android" - coreVersion = "1.4.0-alpha04" - extJUnitVersion = "1.1.3-alpha04" - runnerVersion = "1.4.0-alpha04" - rulesVersion = "1.4.0-alpha04" - espressoVersion = "3.4.0-alpha04" + androidxAnnotationVersion = "1.5.0" + guavaVersion = "31.1-android" + coreVersion = "1.6.1" + extJUnitVersion = "1.2.1" + runnerVersion = "1.6.1" + monitorVersion = "1.7.1" + rulesVersion = "1.6.1" + espressoVersion = "3.6.1" + orchestratorVersion = "1.5.0" + truthVersion = "1.1.3" } diff --git a/runner/AndroidTestOrchestratorSample/gradle.properties b/runner/AndroidTestOrchestratorSample/gradle.properties index 6e4b74401..66096adfa 100644 --- a/runner/AndroidTestOrchestratorSample/gradle.properties +++ b/runner/AndroidTestOrchestratorSample/gradle.properties @@ -16,5 +16,8 @@ # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true +android.defaults.buildfeatures.buildconfig=true +android.nonFinalResIds=false +android.nonTransitiveRClass=false android.useAndroidX=true android.useAndroidX=true \ No newline at end of file diff --git a/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.jar b/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.jar index 8c0fb64a8..41d9927a4 100644 Binary files a/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.jar and b/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.jar differ diff --git a/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.properties b/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.properties index 8e4f539c0..48c0a02ca 100644 --- a/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.properties +++ b/runner/AndroidTestOrchestratorSample/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Tue May 19 20:39:22 PDT 2020 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-all.zip diff --git a/runner/AndroidTestOrchestratorSample/gradlew b/runner/AndroidTestOrchestratorSample/gradlew index 91a7e269e..1b6c78733 100755 --- a/runner/AndroidTestOrchestratorSample/gradlew +++ b/runner/AndroidTestOrchestratorSample/gradlew @@ -1,79 +1,129 @@ -#!/usr/bin/env bash +#!/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 UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/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/. +# ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# 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=`basename "$0"` +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" +MAX_FD=maximum -warn ( ) { +warn () { echo "$*" -} +} >&2 -die ( ) { +die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# 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\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -82,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + 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 @@ -90,75 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + 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 -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +# 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/runner/AndroidTestOrchestratorSample/gradlew.bat b/runner/AndroidTestOrchestratorSample/gradlew.bat index aec99730b..ac1b06f93 100644 --- a/runner/AndroidTestOrchestratorSample/gradlew.bat +++ b/runner/AndroidTestOrchestratorSample/gradlew.bat @@ -1,3 +1,19 @@ +@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 @@ -8,20 +24,23 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set 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 +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,34 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_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=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/.gitignore b/runner/AndroidTestOrchestratorWithTestCoverageSample/.gitignore new file mode 100644 index 000000000..03eee2ade --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/.gitignore @@ -0,0 +1,6 @@ +.gradle +/local.properties +.idea +*.iml +.DS_Store +build diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/README.md b/runner/AndroidTestOrchestratorWithTestCoverageSample/README.md new file mode 100644 index 000000000..42e9df801 --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/README.md @@ -0,0 +1,25 @@ +# AndroidTestOrchestrator with test coverage sample + +The Android Test Orchestrator allows you to run each of your app's tests in isolation, enabling greater reliability. +See https://developer.android.com/training/testing/junit-runner#using-android-test-orchestrator for more background. + +This sample is a subset of the AndroidJUnitRunner sample, but it +illustrates how to enable Jacoco test coverage report with the Android Test Orchestrator in the app/build.gradle file. + +This project uses the Gradle build system. You don't need an IDE to build and execute it but Android Studio is recommended. + +1. Download the project code, preferably using `git clone`. +1. Open the Android SDK Manager (*Tools* Menu | *Android*). +1. In Android Studio, select *File* | *Open...* and point to the top-level `./build.gradle` file. +1. Check out the relevant code: + * The application under test is located in `src/main/java` + * Tests are in `src/androidTest/java` +1. Connect a device or start an emulator: + * Turn animations off. + (On your device, under Settings->Developer options disable the following 3 settings: "Window animation scale", "Transition animation scale" and "Animator duration scale") +1. Run the newly created configuration. + +The application will be started on the device/emulator and a series of actions will be performed automatically. + +If you are using Android Studio, the *Run* window will show the test results. +The test coverage report will be generated in `app/build/reports/coverage/androidTest/debug/index.html`. diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/build.gradle b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/build.gradle new file mode 100644 index 000000000..ae0284998 --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/build.gradle @@ -0,0 +1,41 @@ +apply plugin: "com.android.application" + +android { + compileSdk 33 + defaultConfig { + applicationId "com.example.android.testing.androidtestorchestratorsample" + minSdkVersion 14 + targetSdkVersion 33 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + testInstrumentationRunnerArguments clearPackageData: "true" + testInstrumentationRunnerArguments useTestStorageService: "true" + } + buildTypes { + debug { + testCoverageEnabled true + } + } + testOptions { + execution "ANDROIDX_TEST_ORCHESTRATOR" + } + namespace "com.example.android.testing.androidtestorchestratorsample" +} + +dependencies { + // App's dependencies, including test + implementation "androidx.annotation:annotation:" + rootProject.androidxAnnotationVersion + implementation "com.google.guava:guava:" + rootProject.guavaVersion + + // Testing-only dependencies + androidTestImplementation "androidx.test:core:" + rootProject.coreVersion + androidTestImplementation "androidx.test.ext:junit:" + rootProject.extJUnitVersion + androidTestImplementation "androidx.test:runner:" + rootProject.runnerVersion + androidTestImplementation "androidx.test.espresso:espresso-core:" + rootProject.espressoVersion + androidTestImplementation "com.google.truth:truth:" + rootProject.truthVersion; + androidTestUtil "androidx.test:orchestrator:" + rootProject.orchestratorVersion + androidTestUtil "androidx.test.services:test-services:" + rootProject.testServicesVersion + +} diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorAddParameterizedTest.java b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorAddParameterizedTest.java new file mode 100644 index 000000000..6730ecd6b --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorAddParameterizedTest.java @@ -0,0 +1,92 @@ +/* + * Copyright 2020, The Android Open Source Project + * + * 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. + */ + +package com.example.android.testing.androidtestorchestratorsample; + +import static com.google.common.truth.Truth.assertThat; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import androidx.test.filters.SmallTest; + +import java.lang.Iterable; +import java.util.Arrays; + +import static org.junit.runners.Parameterized.Parameters; + + +/** + * JUnit4 tests for the calculator's add logic. + * + *

This test uses a Junit4s Parameterized tests features which uses annotations to pass + * parameters into a unit test. The way this works is that you have to use the {@link Parameterized} + * runner to run your tests. + *

+ */ +@RunWith(Parameterized.class) +@SmallTest +public class CalculatorAddParameterizedTest { + + /** + * @return {@link Iterable} that contains the values that should be passed to the constructor. + * In this example we are going to use three parameters: operand one, operand two and the + * expected result. + */ + @Parameters + public static Iterable data() { + return Arrays.asList(new Object[][]{ + {0, 0, 0}, + {0, -1, -1}, + {2, 2, 4}, + {8, 8, 16}, + {16, 16, 32}, + {32, 0, 32}, + {64, 64, 128}}); + } + + private final double mOperandOne; + private final double mOperandTwo; + private final double mExpectedResult; + + private Calculator mCalculator; + + /** + * Constructor that takes in the values specified in + * {@link CalculatorAddParameterizedTest#data()}. The values need to be saved to fields in order + * to reuse them in your tests. + */ + public CalculatorAddParameterizedTest(double operandOne, double operandTwo, + double expectedResult) { + + mOperandOne = operandOne; + mOperandTwo = operandTwo; + mExpectedResult = expectedResult; + } + + @Before + public void setUp() { + mCalculator = new Calculator(); + } + + @Test + public void testAdd_TwoNumbers() { + double resultAdd = mCalculator.add(mOperandOne, mOperandTwo); + assertThat(resultAdd).isEqualTo(mExpectedResult); + } +} \ No newline at end of file diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorInstrumentationTest.java b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorInstrumentationTest.java new file mode 100644 index 000000000..80b31bae5 --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/androidTest/java/com/example/android/testing/androidtestorchestratorsample/CalculatorInstrumentationTest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2020, The Android Open Source Project + * + * 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. + */ + +package com.example.android.testing.androidtestorchestratorsample; + +import junit.framework.TestSuite; + +import org.junit.Before; +import org.junit.Test; +import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; +import org.junit.runner.RunWith; + +import androidx.test.core.app.ActivityScenario; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.filters.LargeTest; +import androidx.test.runner.AndroidJUnitRunner; + +import static androidx.test.core.app.ApplicationProvider.getApplicationContext; +import static androidx.test.espresso.Espresso.onView; +import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard; +import static androidx.test.espresso.action.ViewActions.typeText; +import static androidx.test.espresso.assertion.ViewAssertions.matches; +import static androidx.test.espresso.matcher.ViewMatchers.withId; +import static androidx.test.espresso.matcher.ViewMatchers.withText; + +/** + * JUnit4 Ui Tests for {@link CalculatorActivity} using the {@link AndroidJUnitRunner} with the + * Android Test Orchestrator. + * This class uses the JUnit4 syntax for tests. + *

+ * With the new AndroidJUnit runner you can run both JUnit3 and JUnit4 tests in a single test + * suite. The {@link AndroidRunnerBuilder} which extends JUnit's + * {@link AllDefaultPossibilitiesBuilder} will create a single {@link + * TestSuite} from all tests and run them. + */ +@RunWith(AndroidJUnit4.class) +@LargeTest +public class CalculatorInstrumentationTest { + + /** + * Use {@link ActivityScenario} to create and launch of the activity. + */ + @Before + public void launchActivity() { + ActivityScenario.launch(CalculatorActivity.class); + } + + @Test + public void noOperandShowsComputationError() { + final String expectedResult = getApplicationContext().getString(R.string.computationError); + onView(withId(R.id.operation_add_btn)).perform(click()); + onView(withId(R.id.operation_result_text_view)).check(matches(withText(expectedResult))); + } + + @Test + public void typeOperandsAndPerformAddOperation() { + performOperation(R.id.operation_add_btn, "16.0", "16.0", "32.0"); + } + + @Test + public void typeOperandsAndPerformSubOperation() { + performOperation(R.id.operation_sub_btn, "32.0", "16.0", "16.0"); + } + + @Test + public void typeOperandsAndPerformDivOperation() { + performOperation(R.id.operation_div_btn, "128.0", "16.0", "8.0"); + } + + @Test + public void divZeroForOperandTwoShowsError() { + final String expectedResult = getApplicationContext().getString(R.string.computationError); + performOperation(R.id.operation_div_btn, "128.0", "0.0", expectedResult); + } + + @Test + public void typeOperandsAndPerformMulOperation() { + performOperation(R.id.operation_mul_btn, "16.0", "16.0", "256.0"); + } + + private void performOperation(int btnOperationResId, String operandOne, + String operandTwo, String expectedResult) { + // Type the two operands in the EditText fields + onView(withId(R.id.operand_one_edit_text)).perform(typeText(operandOne), + closeSoftKeyboard()); + onView(withId(R.id.operand_two_edit_text)).perform(typeText(operandTwo), + closeSoftKeyboard()); + + // Click on a given operation button + onView(withId(btnOperationResId)).perform(click()); + + // Check the expected test is displayed in the Ui + onView(withId(R.id.operation_result_text_view)).check(matches(withText(expectedResult))); + } + +} diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/AndroidManifest.xml b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..e034b2643 --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/AndroidManifest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/java/com/example/android/testing/androidtestorchestratorsample/Calculator.java b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/java/com/example/android/testing/androidtestorchestratorsample/Calculator.java new file mode 100644 index 000000000..b7a17d12e --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/java/com/example/android/testing/androidtestorchestratorsample/Calculator.java @@ -0,0 +1,57 @@ +/* + * Copyright 2020, The Android Open Source Project + * + * 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. + */ + +package com.example.android.testing.androidtestorchestratorsample; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * A simple calculator with a basic set of operations. + */ +public class Calculator { + + public enum Operator {ADD, SUB, DIV, MUL} + + /** + * Addition operation + */ + public double add(double firstOperand, double secondOperand) { + return firstOperand + secondOperand; + } + + /** + * Substract operation + */ + public double sub(double firstOperand, double secondOperand) { + return firstOperand - secondOperand; + } + + /** + * Divide operation + */ + public double div(double firstOperand, double secondOperand) { + checkArgument(secondOperand != 0, "secondOperand must be != 0, you cannot divide by zero"); + return firstOperand / secondOperand; + } + + /** + * Multiply operation + */ + public double mul(double firstOperand, double secondOperand) { + + return firstOperand * secondOperand; + } +} diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/java/com/example/android/testing/androidtestorchestratorsample/CalculatorActivity.java b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/java/com/example/android/testing/androidtestorchestratorsample/CalculatorActivity.java new file mode 100644 index 000000000..d745a3210 --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/java/com/example/android/testing/androidtestorchestratorsample/CalculatorActivity.java @@ -0,0 +1,138 @@ +/* + * Copyright 2020, The Android Open Source Project + * + * 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. + */ + +package com.example.android.testing.androidtestorchestratorsample; + +import android.app.Activity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; + +/** + * {@link android.app.Activity} which contains a simple calculator. Numbers can be entered in the + * two {@link EditText} fields and result can be obtained by pressing one of the + * operation {@link Button}s at the bottom. + */ +public class CalculatorActivity extends Activity { + + private static final String TAG = "CalculatorActivity"; + + private Calculator mCalculator; + + private EditText mOperandOneEditText; + private EditText mOperandTwoEditText; + + private TextView mResultTextView; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_calculator); + mCalculator = new Calculator(); + mResultTextView = (TextView) findViewById(R.id.operation_result_text_view); + mOperandOneEditText = (EditText) findViewById(R.id.operand_one_edit_text); + mOperandTwoEditText = (EditText) findViewById(R.id.operand_two_edit_text); + } + + /** + * OnClick method that is called when the add {@link Button} is pressed. + */ + public void onAdd(View view) { + compute(Calculator.Operator.ADD); + } + + /** + * OnClick method that is called when the substract {@link Button} is pressed. + */ + public void onSub(View view) { + compute(Calculator.Operator.SUB); + } + + /** + * OnClick method that is called when the divide {@link Button} is pressed. + */ + public void onDiv(View view) { + try { + compute(Calculator.Operator.DIV); + } catch (IllegalArgumentException iae) { + Log.e(TAG, "IllegalArgumentException", iae); + mResultTextView.setText(getString(R.string.computationError)); + } + } + + /** + * OnClick method that is called when the multiply {@link Button} is pressed. + */ + public void onMul(View view) { + compute(Calculator.Operator.MUL); + } + + private void compute(Calculator.Operator operator) { + double operandOne; + double operandTwo; + try { + operandOne = getOperand(mOperandOneEditText); + operandTwo = getOperand(mOperandTwoEditText); + } catch (NumberFormatException nfe) { + Log.e(TAG, "NumberFormatException", nfe); + mResultTextView.setText(getString(R.string.computationError)); + return; + } + + String result; + switch (operator) { + case ADD: + result = String.valueOf(mCalculator.add(operandOne, operandTwo)); + break; + case SUB: + result = String.valueOf(mCalculator.sub(operandOne, operandTwo)); + break; + case DIV: + result = String.valueOf(mCalculator.div(operandOne, operandTwo)); + break; + case MUL: + result = String.valueOf(mCalculator.mul(operandOne, operandTwo)); + break; + default: + result = getString(R.string.computationError); + break; + } + mResultTextView.setText(result); + } + + /** + * @return the operand value which was entered in an {@link EditText} as a double + */ + private static Double getOperand(EditText operandEditText) { + String operandText = getOperandText(operandEditText); + return Double.valueOf(operandText); + } + + /** + * @return the operand text which was entered in an {@link EditText}. + */ + private static String getOperandText(EditText operandEditText) { + String operandText = operandEditText.getText().toString(); + if (TextUtils.isEmpty(operandText)) { + throw new NumberFormatException("operand cannot be empty!"); + } + return operandText; + } +} diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-hdpi/ic_launcher.png b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100755 index 000000000..965ac9624 Binary files /dev/null and b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-mdpi/ic_launcher.png b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100755 index 000000000..df52c5278 Binary files /dev/null and b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-xhdpi/ic_launcher.png b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100755 index 000000000..3d479bfe7 Binary files /dev/null and b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-xxhdpi/ic_launcher.png b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-xxhdpi/ic_launcher.png new file mode 100755 index 000000000..c85d90b05 Binary files /dev/null and b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/layout/activity_calculator.xml b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/layout/activity_calculator.xml new file mode 100644 index 000000000..60f5e3565 --- /dev/null +++ b/runner/AndroidTestOrchestratorWithTestCoverageSample/app/src/main/res/layout/activity_calculator.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + +