├── .idea
├── .name
├── .gitignore
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── compiler.xml
└── misc.xml
├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── themes.xml
│ │ │ ├── values-land
│ │ │ │ └── dimens.xml
│ │ │ ├── values-w1240dp
│ │ │ │ └── dimens.xml
│ │ │ ├── values-w600dp
│ │ │ │ └── dimens.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── menu
│ │ │ │ └── menu_main.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── layout
│ │ │ │ ├── content_main.xml
│ │ │ │ ├── fragment_first.xml
│ │ │ │ ├── activity_main.xml
│ │ │ │ └── fragment_second.xml
│ │ │ ├── navigation
│ │ │ │ └── nav_graph.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── emergetools
│ │ │ │ └── relaxexamples
│ │ │ │ ├── FirstFragment.kt
│ │ │ │ ├── SecondFragment.kt
│ │ │ │ ├── DeepActivity.kt
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── emergetools
│ │ │ └── relaxexamples
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── emergetools
│ │ └── relaxexamples
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── relax
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── emergetools
│ │ │ └── relax
│ │ │ ├── internal
│ │ │ ├── FlowInterceptor.kt
│ │ │ ├── DebugInterceptor.kt
│ │ │ └── TracingInterceptor.kt
│ │ │ ├── Relax.kt
│ │ │ ├── FlowErrorHandler.kt
│ │ │ ├── FlowConfig.kt
│ │ │ ├── RelaxSelector.kt
│ │ │ └── Flow.kt
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── emergetools
│ │ │ └── relax
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── emergetools
│ │ └── relax
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── tests
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── emergetools
│ │ └── relaxtests
│ │ ├── FindObjectTest.kt
│ │ ├── ClickTest.kt
│ │ ├── LongClickTest.kt
│ │ ├── InputTextTest.kt
│ │ └── LaunchTest.kt
└── build.gradle.kts
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── CHANGELOG.md
├── settings.gradle.kts
├── gradle.properties
├── .gitignore
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/.idea/.name:
--------------------------------------------------------------------------------
1 | Relax
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/relax/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/tests/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/relax/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 |
--------------------------------------------------------------------------------
/relax/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w1240dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 200dp
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EmergeTools/relax/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/internal/FlowInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax.internal
2 |
3 | interface FlowInterceptor {
4 | fun intercept(event: String, call: () -> T): T
5 | }
6 |
--------------------------------------------------------------------------------
/tests/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 12 12:19:52 EST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/Relax.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax
2 |
3 | object Relax {
4 |
5 | internal val TAG = "Relax"
6 |
7 | operator fun invoke(packageName: String, config: FlowConfig = FlowConfig(), flow: Flow.() -> Unit) {
8 | Flow(packageName, config).flow()
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Relax Changelog
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7 |
8 | ## Unreleased
9 |
10 | ### Added
11 |
12 | - `clickable` selector.
13 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/internal/DebugInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax.internal
2 |
3 | import android.util.Log
4 | import com.emergetools.relax.Relax
5 |
6 | object DebugInterceptor : FlowInterceptor {
7 | override fun intercept(event: String, call: () -> T): T {
8 | Log.d(Relax.TAG, event)
9 | return call()
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 |
9 | dependencyResolutionManagement {
10 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
11 | repositories {
12 | google()
13 | mavenCentral()
14 | }
15 | }
16 |
17 | rootProject.name = "Relax"
18 | include(":app")
19 | include(":relax")
20 | include(":tests")
21 |
--------------------------------------------------------------------------------
/relax/src/test/java/com/emergetools/relax/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax
2 |
3 | import org.junit.Assert.assertEquals
4 | import org.junit.Test
5 |
6 | /**
7 | * Example local unit test, which will execute on the development machine (host).
8 | *
9 | * See [testing documentation](http://d.android.com/tools/testing).
10 | */
11 | class ExampleUnitTest {
12 | @Test
13 | fun addition_isCorrect() {
14 | assertEquals(4, 2 + 2)
15 | }
16 | }
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/FlowErrorHandler.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax
2 |
3 | interface FlowErrorHandler {
4 | fun onError(error: Throwable)
5 | }
6 |
7 | object NoOpFlowErrorHandler : FlowErrorHandler {
8 | override fun onError(error: Throwable) {
9 | // Do nothing.
10 | }
11 | }
12 |
13 | object DefaultFlowErrorHandler : FlowErrorHandler {
14 | override fun onError(error: Throwable) {
15 | throw error
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/internal/TracingInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax.internal
2 |
3 | import android.os.Trace
4 |
5 |
6 | object TracingInterceptor : FlowInterceptor {
7 |
8 | private val PREFIX = "relax."
9 |
10 | override fun intercept(event: String, call: () -> T): T {
11 | Trace.beginSection("$PREFIX$event")
12 | val result = call()
13 | Trace.endSection()
14 | return result
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/test/java/com/emergetools/relaxexamples/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxexamples
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/FlowConfig.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax
2 |
3 | data class FlowConfig(
4 | val debug: Boolean = false,
5 | val trace: Boolean = false,
6 | /** In milliseconds */
7 | val waitForIdleTimeout: Long = 10_000,
8 | val scrollToMaxSwipes: Int = 30,
9 | val swipeSteps: Int = 100,
10 | val errorHandler: FlowErrorHandler = DefaultFlowErrorHandler,
11 | /** In milliseconds */
12 | val launchTimeout: Long = 5_000,
13 | /** In milliseconds */
14 | val reportFullyDrawnTimeout: Long = 10_000
15 | )
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Relax Examples
3 | Settings
4 |
5 | First Fragment
6 | Second Fragment
7 | Next
8 | Previous
9 |
10 | Hello first fragment
11 | Hello second fragment. Arg: %1$s
12 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/relax/src/androidTest/java/com/emergetools/relax/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax
2 |
3 | import androidx.test.ext.junit.runners.AndroidJUnit4
4 | import androidx.test.platform.app.InstrumentationRegistry
5 | import org.junit.Assert.*
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | /**
10 | * Instrumented test, which will execute on an Android device.
11 | *
12 | * See [testing documentation](http://d.android.com/tools/testing).
13 | */
14 | @RunWith(AndroidJUnit4::class)
15 | class ExampleInstrumentedTest {
16 | @Test
17 | fun useAppContext() {
18 | // Context of the app under test.
19 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
20 | assertEquals("com.emergetools.relax.test", appContext.packageName)
21 | }
22 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.kts.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/relax/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.kts.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
19 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/emergetools/relaxexamples/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxexamples
2 |
3 | import android.widget.Button
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 | import com.emergetools.relax.*
6 | import org.junit.Assert.*
7 | import org.junit.Test
8 | import org.junit.runner.RunWith
9 |
10 | @RunWith(AndroidJUnit4::class)
11 | class ExampleInstrumentedTest {
12 |
13 | @Test
14 | fun test() {
15 | val config = FlowConfig(debug = true)
16 | Relax("com.emergetools.relaxexamples", config) {
17 | pressHome()
18 | launch()
19 | click("id/fab")
20 | click(Button::class.java)
21 | optional {
22 | scrollForward("Hello first fragment")
23 | click("Doesn't exist")
24 | }
25 | click {
26 | classNameMatches(".+\\.Button")
27 | textStartsWith("N")
28 | }
29 | assertExists {
30 | enabled(true)
31 | scrollable(false)
32 | text("PREVIOUS")
33 | }
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/app/src/main/res/navigation/nav_graph.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
17 |
18 |
23 |
24 |
27 |
28 |
--------------------------------------------------------------------------------
/tests/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.test")
3 | id("org.jetbrains.kotlin.android")
4 | }
5 |
6 | android {
7 | namespace = "com.emergetools.relaxtests"
8 | compileSdk = 33
9 |
10 | compileOptions {
11 | sourceCompatibility = JavaVersion.VERSION_1_8
12 | targetCompatibility = JavaVersion.VERSION_1_8
13 | }
14 |
15 | kotlinOptions {
16 | jvmTarget = "1.8"
17 | }
18 |
19 | defaultConfig {
20 | minSdk = 23
21 | targetSdk = 33
22 |
23 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
24 | }
25 |
26 | buildTypes {
27 | create("release") {
28 | isDebuggable = true
29 | signingConfig = getByName("debug").signingConfig
30 | }
31 | }
32 |
33 | targetProjectPath = ":app"
34 |
35 | experimentalProperties["android.experimental.self-instrumenting"] = true
36 | }
37 |
38 | dependencies {
39 | implementation("androidx.test.ext:junit:1.1.4")
40 | implementation("androidx.test:runner:1.5.1")
41 | implementation(project(":relax"))
42 | }
43 |
44 | androidComponents {
45 | beforeVariants(selector().all()) {
46 | it.enable = it.buildType == "release"
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/tests/src/main/java/com/emergetools/relaxtests/FindObjectTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxtests
2 |
3 | import androidx.test.ext.junit.runners.AndroidJUnit4
4 | import androidx.test.uiautomator.UiObjectNotFoundException
5 | import com.emergetools.relax.Relax
6 | import org.junit.Assert.assertThrows
7 | import org.junit.Assert.assertTrue
8 | import org.junit.Test
9 | import org.junit.runner.RunWith
10 |
11 | @RunWith(AndroidJUnit4::class)
12 | class FindObjectTest {
13 |
14 | @Test
15 | fun findObject() {
16 | Relax("com.emergetools.relaxexamples") {
17 | pressHome()
18 | launch()
19 | val obj = findObject("NEXT")
20 |
21 | assertTrue(obj.exists())
22 | }
23 | }
24 |
25 | @Test
26 | fun findObjectDoesntExist() {
27 | Relax("com.emergetools.relaxexamples") {
28 | pressHome()
29 | launch()
30 |
31 | assertThrows(UiObjectNotFoundException::class.java) {
32 | findObject("DOESN'T EXIST")
33 | }
34 | }
35 | }
36 |
37 | @Test
38 | fun optionalFindObject() {
39 | Relax("com.emergetools.relaxexamples") {
40 | pressHome()
41 | launch()
42 |
43 | optional {
44 | findObject("DOESN'T EXIST")
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_first.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
28 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/tests/src/main/java/com/emergetools/relaxtests/ClickTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxtests
2 |
3 | import android.widget.Button
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 | import androidx.test.uiautomator.UiObjectNotFoundException
6 | import com.emergetools.relax.Relax
7 | import org.junit.Assert.assertThrows
8 | import org.junit.Test
9 | import org.junit.runner.RunWith
10 |
11 | @RunWith(AndroidJUnit4::class)
12 | class ClickTest {
13 |
14 | @Test
15 | fun click() {
16 | Relax("com.emergetools.relaxexamples") {
17 | pressHome()
18 | launch()
19 |
20 | click("NEXT")
21 | click("id/button_second")
22 | click(Button::class.java)
23 | click {
24 | textMatches("P.+")
25 | }
26 | }
27 | }
28 |
29 | @Test
30 | fun clickObjectDoesntExist() {
31 | Relax("com.emergetools.relaxexamples") {
32 | pressHome()
33 | launch()
34 |
35 | assertThrows(UiObjectNotFoundException::class.java) {
36 | click("DOESN'T EXIST")
37 | }
38 | }
39 | }
40 |
41 | @Test
42 | fun optionalClick() {
43 | Relax("com.emergetools.relaxexamples") {
44 | pressHome()
45 | launch()
46 |
47 | optional {
48 | click("DOESN'T EXIST")
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/java/com/emergetools/relaxexamples/FirstFragment.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxexamples
2 |
3 | import android.os.Bundle
4 | import androidx.fragment.app.Fragment
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import androidx.navigation.fragment.findNavController
9 | import com.emergetools.relaxexamples.databinding.FragmentFirstBinding
10 |
11 | /**
12 | * A simple [Fragment] subclass as the default destination in the navigation.
13 | */
14 | class FirstFragment : Fragment() {
15 |
16 | private var _binding: FragmentFirstBinding? = null
17 |
18 | // This property is only valid between onCreateView and
19 | // onDestroyView.
20 | private val binding get() = _binding!!
21 |
22 | override fun onCreateView(
23 | inflater: LayoutInflater, container: ViewGroup?,
24 | savedInstanceState: Bundle?
25 | ): View? {
26 |
27 | _binding = FragmentFirstBinding.inflate(inflater, container, false)
28 | return binding.root
29 |
30 | }
31 |
32 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
33 | super.onViewCreated(view, savedInstanceState)
34 |
35 | binding.buttonFirst.setOnClickListener {
36 | findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
37 | }
38 | }
39 |
40 | override fun onDestroyView() {
41 | super.onDestroyView()
42 | _binding = null
43 | }
44 | }
--------------------------------------------------------------------------------
/tests/src/main/java/com/emergetools/relaxtests/LongClickTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxtests
2 |
3 | import android.widget.Button
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 | import androidx.test.uiautomator.UiObjectNotFoundException
6 | import com.emergetools.relax.Relax
7 | import org.junit.Assert.assertThrows
8 | import org.junit.Test
9 | import org.junit.runner.RunWith
10 |
11 | @RunWith(AndroidJUnit4::class)
12 | class LongClickTest {
13 |
14 | @Test
15 | fun longClick() {
16 | Relax("com.emergetools.relaxexamples") {
17 | pressHome()
18 | launch()
19 |
20 | longClick("NEXT")
21 | longClick("id/button_second")
22 | longClick(Button::class.java)
23 | longClick {
24 | textMatches("P.+")
25 | }
26 | }
27 | }
28 |
29 | @Test
30 | fun longClickObjectDoesntExist() {
31 | Relax("com.emergetools.relaxexamples") {
32 | pressHome()
33 | launch()
34 |
35 | assertThrows(UiObjectNotFoundException::class.java) {
36 | longClick("DOESN'T EXIST")
37 | }
38 | }
39 | }
40 |
41 | @Test
42 | fun optionalLongClick() {
43 | Relax("com.emergetools.relaxexamples") {
44 | pressHome()
45 | launch()
46 |
47 | optional {
48 | longClick("DOESN'T EXIST")
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/java/com/emergetools/relaxexamples/SecondFragment.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxexamples
2 |
3 | import android.os.Bundle
4 | import androidx.fragment.app.Fragment
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import androidx.navigation.fragment.findNavController
9 | import com.emergetools.relaxexamples.databinding.FragmentSecondBinding
10 |
11 | /**
12 | * A simple [Fragment] subclass as the second destination in the navigation.
13 | */
14 | class SecondFragment : Fragment() {
15 |
16 | private var _binding: FragmentSecondBinding? = null
17 |
18 | // This property is only valid between onCreateView and
19 | // onDestroyView.
20 | private val binding get() = _binding!!
21 |
22 | override fun onCreateView(
23 | inflater: LayoutInflater, container: ViewGroup?,
24 | savedInstanceState: Bundle?
25 | ): View? {
26 |
27 | _binding = FragmentSecondBinding.inflate(inflater, container, false)
28 | return binding.root
29 |
30 | }
31 |
32 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
33 | super.onViewCreated(view, savedInstanceState)
34 |
35 | binding.buttonSecond.setOnClickListener {
36 | findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
37 | }
38 | }
39 |
40 | override fun onDestroyView() {
41 | super.onDestroyView()
42 | _binding = null
43 | }
44 | }
--------------------------------------------------------------------------------
/tests/src/main/java/com/emergetools/relaxtests/InputTextTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxtests
2 |
3 | import android.widget.EditText
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 | import androidx.test.uiautomator.By
6 | import androidx.test.uiautomator.UiObjectNotFoundException
7 | import com.emergetools.relax.Relax
8 | import org.junit.Assert.assertNotNull
9 | import org.junit.Assert.assertThrows
10 | import org.junit.Test
11 | import org.junit.runner.RunWith
12 |
13 | @RunWith(AndroidJUnit4::class)
14 | class InputTextTest {
15 |
16 | @Test
17 | fun inputText() {
18 | Relax("com.emergetools.relaxexamples") {
19 | pressHome()
20 | launch()
21 | click("NEXT")
22 | inputText("Felix", EditText::class.java)
23 |
24 | assertNotNull(device.findObject(By.text("Felix")))
25 | }
26 | }
27 |
28 | @Test
29 | fun inputTextObjectDoesntExist() {
30 | Relax("com.emergetools.relaxexamples") {
31 | pressHome()
32 | launch()
33 | click("NEXT")
34 |
35 | assertThrows(UiObjectNotFoundException::class.java) {
36 | inputText("Felix", "DOESN'T EXIST")
37 | }
38 | }
39 | }
40 |
41 | @Test
42 | fun optionalInputText() {
43 | Relax("com.emergetools.relaxexamples") {
44 | pressHome()
45 | launch()
46 | click("NEXT")
47 |
48 | optional {
49 | inputText("Felix", "DOESN'T EXIST")
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
21 |
22 |
23 |
24 |
25 |
33 |
34 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.application")
3 | id("org.jetbrains.kotlin.android")
4 | }
5 |
6 | android {
7 | namespace = "com.emergetools.relaxexamples"
8 | compileSdk = 33
9 |
10 | defaultConfig {
11 | applicationId = "com.emergetools.relaxexamples"
12 | minSdk = 23
13 | targetSdk = 33
14 | versionCode = 1
15 | versionName = "1.0"
16 |
17 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | isMinifyEnabled = false
23 | proguardFiles(
24 | getDefaultProguardFile("proguard-android-optimize.txt"),
25 | "proguard-rules.pro"
26 | )
27 | signingConfig = getByName("debug").signingConfig
28 | }
29 | }
30 | compileOptions {
31 | sourceCompatibility = JavaVersion.VERSION_1_8
32 | targetCompatibility = JavaVersion.VERSION_1_8
33 | }
34 | kotlinOptions {
35 | jvmTarget = "1.8"
36 | }
37 | buildFeatures {
38 | viewBinding = true
39 | }
40 | }
41 |
42 | dependencies {
43 | implementation("androidx.core:core-ktx:1.9.0")
44 | implementation("androidx.appcompat:appcompat:1.5.1")
45 | implementation("com.google.android.material:material:1.7.0")
46 | implementation("androidx.constraintlayout:constraintlayout:2.1.4")
47 | implementation("androidx.navigation:navigation-fragment-ktx:2.5.3")
48 | implementation("androidx.navigation:navigation-ui-ktx:2.5.3")
49 | testImplementation("junit:junit:4.13.2")
50 | androidTestImplementation("androidx.test.ext:junit:1.1.4")
51 | androidTestImplementation(project(":relax"))
52 | }
53 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.aar
4 | *.ap_
5 | *.aab
6 |
7 | # Files for the ART/Dalvik VM
8 | *.dex
9 |
10 | # Java class files
11 | *.class
12 |
13 | # Generated files
14 | bin/
15 | gen/
16 | out/
17 | # Uncomment the following line in case you need and you don't have the release build type files in your app
18 | # release/
19 |
20 | # Gradle files
21 | .gradle/
22 | build/
23 |
24 | # Local configuration file (sdk path, etc)
25 | local.properties
26 |
27 | # Proguard folder generated by Eclipse
28 | proguard/
29 |
30 | # Log Files
31 | *.log
32 |
33 | # Android Studio Navigation editor temp files
34 | .navigation/
35 |
36 | # Android Studio captures folder
37 | captures/
38 |
39 | # IntelliJ
40 | *.iml
41 | .idea/workspace.xml
42 | .idea/tasks.xml
43 | .idea/gradle.xml
44 | .idea/assetWizardSettings.xml
45 | .idea/dictionaries
46 | .idea/libraries
47 | # Android Studio 3 in .gitignore file.
48 | .idea/caches
49 | .idea/modules.xml
50 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you
51 | .idea/navEditor.xml
52 |
53 | # Keystore files
54 | # Uncomment the following lines if you do not want to check your keystore files in.
55 | #*.jks
56 | #*.keystore
57 |
58 | # External native build folder generated in Android Studio 2.2 and later
59 | .externalNativeBuild
60 | .cxx/
61 |
62 | # Google Services (e.g. APIs or Firebase)
63 | # google-services.json
64 |
65 | # Freeline
66 | freeline.py
67 | freeline/
68 | freeline_project_description.json
69 |
70 | # fastlane
71 | fastlane/report.xml
72 | fastlane/Preview.html
73 | fastlane/screenshots
74 | fastlane/test_output
75 | fastlane/readme.md
76 |
77 | # Version control
78 | vcs.xml
79 |
80 | # lint
81 | lint/intermediates/
82 | lint/generated/
83 | lint/outputs/
84 | lint/tmp/
85 | # lint/reports/
86 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_second.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
30 |
31 |
40 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
15 |
18 |
19 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
32 |
33 |
34 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/tests/src/main/java/com/emergetools/relaxtests/LaunchTest.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxtests
2 |
3 | import android.content.Intent
4 | import android.content.pm.PackageManager.MATCH_DEFAULT_ONLY
5 | import android.provider.Settings
6 | import androidx.test.ext.junit.runners.AndroidJUnit4
7 | import androidx.test.uiautomator.By
8 | import com.emergetools.relax.Relax
9 | import org.junit.Assert.assertNotNull
10 | import org.junit.Test
11 | import org.junit.runner.RunWith
12 |
13 | @RunWith(AndroidJUnit4::class)
14 | class LaunchTest {
15 |
16 | @Test
17 | fun launch() {
18 | Relax("com.emergetools.relaxexamples") {
19 | pressHome()
20 | waitForReportFullyDrawn {
21 | launch()
22 | }
23 | // uiAutomation.executeShellCommand("logcat")
24 |
25 | // assertNotNull(device.findObject(By.pkg(packageName)))
26 | }
27 | }
28 |
29 | @Test
30 | fun launchArbitraryPackage() {
31 | Relax("com.emergetools.relaxexamples") {
32 | pressHome()
33 | val intent = Intent(Settings.ACTION_SETTINGS)
34 |
35 | @Suppress("DEPRECATION")
36 | val resolveInfos = appContext.packageManager.queryIntentActivities(intent, MATCH_DEFAULT_ONLY)
37 | val settingsPackageName = resolveInfos.first().activityInfo.packageName
38 | launch(settingsPackageName)
39 |
40 | assertNotNull(device.findObject(By.pkg(settingsPackageName)))
41 | }
42 | }
43 |
44 | @Test
45 | fun launchWithLink() {
46 | Relax("com.emergetools.relaxexamples") {
47 | pressHome()
48 | launchWithLink("emerge://deep")
49 |
50 | assertNotNull(device.findObject(By.pkg(packageName)))
51 | }
52 | }
53 |
54 | @Test
55 | fun coldLaunch() {
56 | Relax("com.emergetools.relaxexamples") {
57 | pressHome()
58 | coldLaunch()
59 |
60 | assertNotNull(device.findObject(By.pkg(packageName)))
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/app/src/main/java/com/emergetools/relaxexamples/DeepActivity.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxexamples
2 |
3 | import android.os.Bundle
4 | import com.google.android.material.snackbar.Snackbar
5 | import androidx.appcompat.app.AppCompatActivity
6 | import androidx.navigation.findNavController
7 | import androidx.navigation.ui.AppBarConfiguration
8 | import androidx.navigation.ui.navigateUp
9 | import androidx.navigation.ui.setupActionBarWithNavController
10 | import android.view.Menu
11 | import android.view.MenuItem
12 | import com.emergetools.relaxexamples.databinding.ActivityMainBinding
13 |
14 | class DeepActivity : AppCompatActivity() {
15 |
16 | private lateinit var appBarConfiguration: AppBarConfiguration
17 | private lateinit var binding: ActivityMainBinding
18 |
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 |
22 | binding = ActivityMainBinding.inflate(layoutInflater)
23 | setContentView(binding.root)
24 |
25 | setSupportActionBar(binding.toolbar)
26 |
27 | val navController = findNavController(R.id.nav_host_fragment_content_main)
28 | appBarConfiguration = AppBarConfiguration(navController.graph)
29 | setupActionBarWithNavController(navController, appBarConfiguration)
30 |
31 | binding.fab.setOnClickListener { view ->
32 | Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
33 | .setAction("Action", null).show()
34 | }
35 | }
36 |
37 | override fun onCreateOptionsMenu(menu: Menu): Boolean {
38 | // Inflate the menu; this adds items to the action bar if it is present.
39 | menuInflater.inflate(R.menu.menu_main, menu)
40 | return true
41 | }
42 |
43 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
44 | // Handle action bar item clicks here. The action bar will
45 | // automatically handle clicks on the Home/Up button, so long
46 | // as you specify a parent activity in AndroidManifest.xml.
47 | return when (item.itemId) {
48 | R.id.action_settings -> true
49 | else -> super.onOptionsItemSelected(item)
50 | }
51 | }
52 |
53 | override fun onSupportNavigateUp(): Boolean {
54 | val navController = findNavController(R.id.nav_host_fragment_content_main)
55 | return navController.navigateUp(appBarConfiguration)
56 | || super.onSupportNavigateUp()
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/app/src/main/java/com/emergetools/relaxexamples/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relaxexamples
2 |
3 | import android.os.Bundle
4 | import com.google.android.material.snackbar.Snackbar
5 | import androidx.appcompat.app.AppCompatActivity
6 | import androidx.navigation.findNavController
7 | import androidx.navigation.ui.AppBarConfiguration
8 | import androidx.navigation.ui.navigateUp
9 | import androidx.navigation.ui.setupActionBarWithNavController
10 | import android.view.Menu
11 | import android.view.MenuItem
12 | import com.emergetools.relaxexamples.databinding.ActivityMainBinding
13 |
14 | class MainActivity : AppCompatActivity() {
15 |
16 | private lateinit var appBarConfiguration: AppBarConfiguration
17 | private lateinit var binding: ActivityMainBinding
18 |
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 |
22 | binding = ActivityMainBinding.inflate(layoutInflater)
23 | setContentView(binding.root)
24 |
25 | setSupportActionBar(binding.toolbar)
26 |
27 | val navController = findNavController(R.id.nav_host_fragment_content_main)
28 | appBarConfiguration = AppBarConfiguration(navController.graph)
29 | setupActionBarWithNavController(navController, appBarConfiguration)
30 |
31 | binding.fab.setOnClickListener { view ->
32 | Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
33 | .setAction("Action", null).show()
34 | }
35 |
36 | reportFullyDrawn()
37 | }
38 |
39 | override fun onCreateOptionsMenu(menu: Menu): Boolean {
40 | // Inflate the menu; this adds items to the action bar if it is present.
41 | menuInflater.inflate(R.menu.menu_main, menu)
42 | return true
43 | }
44 |
45 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
46 | // Handle action bar item clicks here. The action bar will
47 | // automatically handle clicks on the Home/Up button, so long
48 | // as you specify a parent activity in AndroidManifest.xml.
49 | return when (item.itemId) {
50 | R.id.action_settings -> true
51 | else -> super.onOptionsItemSelected(item)
52 | }
53 | }
54 |
55 | override fun onSupportNavigateUp(): Boolean {
56 | val navController = findNavController(R.id.nav_host_fragment_content_main)
57 | return navController.navigateUp(appBarConfiguration)
58 | || super.onSupportNavigateUp()
59 | }
60 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/relax/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.library")
3 | id("org.jetbrains.kotlin.android")
4 | `maven-publish`
5 | signing
6 | }
7 |
8 | group = "com.emergetools.test"
9 | version = "0.1.0"
10 |
11 | android {
12 | namespace = "com.emergetools.relax"
13 | compileSdk = 33
14 |
15 | defaultConfig {
16 | minSdk = 23
17 | targetSdk = 33
18 |
19 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
20 | consumerProguardFiles("consumer-rules.pro")
21 | }
22 |
23 | buildTypes {
24 | release {
25 | isMinifyEnabled = false
26 | proguardFiles(
27 | getDefaultProguardFile("proguard-android-optimize.txt"),
28 | "proguard-rules.pro"
29 | )
30 | }
31 | }
32 |
33 | compileOptions {
34 | sourceCompatibility = JavaVersion.VERSION_1_8
35 | targetCompatibility = JavaVersion.VERSION_1_8
36 | }
37 |
38 | kotlinOptions {
39 | jvmTarget = "1.8"
40 | }
41 |
42 | publishing {
43 | singleVariant("release") {
44 | withJavadocJar()
45 | withSourcesJar()
46 | }
47 | }
48 | }
49 |
50 | dependencies {
51 | implementation("androidx.test.ext:junit:1.1.4")
52 | implementation("androidx.tracing:tracing:1.1.0")
53 | api("androidx.test.uiautomator:uiautomator:2.2.0")
54 | testImplementation("junit:junit:4.13.2")
55 | }
56 |
57 | val ossrhUsername: String? by project
58 | val ossrhPassword: String? by project
59 |
60 | publishing {
61 | repositories {
62 | maven {
63 | name = "SonatypeStaging"
64 | url = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/")
65 | credentials {
66 | username = ossrhUsername
67 | password = ossrhPassword
68 | }
69 | }
70 |
71 | maven {
72 | name = "SonatypeSnapshots"
73 | url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")
74 | credentials {
75 | username = ossrhUsername
76 | password = ossrhPassword
77 | }
78 | }
79 | }
80 |
81 | publications {
82 | register("release") {
83 | artifactId = "relax"
84 |
85 | afterEvaluate {
86 | from(components["release"])
87 | }
88 |
89 | pom {
90 | name.set("Relax")
91 | description.set("Clear and concise Android UI tests using UI Automator")
92 | url.set("https://github.com/EmergeTools/relax")
93 | licenses {
94 | license {
95 | name.set("The Apache License, Version 2.0")
96 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
97 | }
98 | }
99 | scm {
100 | url.set("https://github.com/EmergeTools/relax")
101 | }
102 | developers {
103 | developer {
104 | id.set("nathanael")
105 | name.set("Nathanael Silverman")
106 | email.set("nathanael@emergetools.com")
107 | }
108 | developer {
109 | id.set("ryan")
110 | name.set("Ryan Brooks")
111 | email.set("ryan@emergetools.com")
112 | }
113 | }
114 | }
115 | }
116 | }
117 | }
118 |
119 | signing {
120 | sign(publishing.publications["release"])
121 | }
122 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | xmlns:android
23 |
24 | ^$
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | xmlns:.*
34 |
35 | ^$
36 |
37 |
38 | BY_NAME
39 |
40 |
41 |
42 |
43 |
44 |
45 | .*:id
46 |
47 | http://schemas.android.com/apk/res/android
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | .*:name
57 |
58 | http://schemas.android.com/apk/res/android
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | name
68 |
69 | ^$
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 | style
79 |
80 | ^$
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | .*
90 |
91 | ^$
92 |
93 |
94 | BY_NAME
95 |
96 |
97 |
98 |
99 |
100 |
101 | .*
102 |
103 | http://schemas.android.com/apk/res/android
104 |
105 |
106 | ANDROID_ATTRIBUTE_ORDER
107 |
108 |
109 |
110 |
111 |
112 |
113 | .*
114 |
115 | .*
116 |
117 |
118 | BY_NAME
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/RelaxSelector.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax
2 |
3 | import androidx.test.uiautomator.UiSelector
4 |
5 | class RelaxSelector(
6 | private val packageName: String,
7 | private var uiSelector: UiSelector = UiSelector()
8 | ) {
9 |
10 | fun checkable(checkable: Boolean) = apply {
11 | uiSelector = uiSelector.checkable(checkable)
12 | }
13 |
14 | fun checked(checked: Boolean) = apply {
15 | uiSelector = uiSelector.checked(checked)
16 | }
17 |
18 | fun child(select: RelaxSelector.() -> Unit) = apply {
19 | val selector = RelaxSelector(packageName).apply(select).toUiSelector()
20 | uiSelector = uiSelector.childSelector(selector)
21 | }
22 |
23 | fun className(type: Class<*>) = apply {
24 | uiSelector = uiSelector.className(type)
25 | }
26 |
27 | fun className(className: String) = apply {
28 | uiSelector = uiSelector.className(className)
29 | }
30 |
31 | fun classNameMatches(regex: String) = apply {
32 | uiSelector = uiSelector.classNameMatches(regex)
33 | }
34 |
35 | fun clickable(clickable: Boolean) = apply {
36 | uiSelector = uiSelector.clickable(clickable)
37 | }
38 |
39 | fun description(description: String) = apply {
40 | uiSelector = uiSelector.description(description)
41 | }
42 |
43 | fun descriptionContains(description: String) = apply {
44 | uiSelector = uiSelector.descriptionContains(description)
45 | }
46 |
47 | fun descriptionMatches(regex: String) = apply {
48 | uiSelector = uiSelector.descriptionMatches(regex)
49 | }
50 |
51 | fun descriptionStartsWith(description: String) = apply {
52 | uiSelector = uiSelector.descriptionStartsWith(description)
53 | }
54 |
55 | fun enabled(enabled: Boolean) = apply {
56 | uiSelector = uiSelector.enabled(enabled)
57 | }
58 |
59 | fun focusable(focusable: Boolean) = apply {
60 | uiSelector = uiSelector.focusable(focusable)
61 | }
62 |
63 | fun focused(focused: Boolean) = apply {
64 | uiSelector = uiSelector.focused(focused)
65 | }
66 |
67 | fun index(index: Int) = apply {
68 | uiSelector = uiSelector.index(index)
69 | }
70 |
71 | fun instance(instance: Int) = apply {
72 | uiSelector = uiSelector.instance(instance)
73 | }
74 |
75 | fun longClickable(longClickable: Boolean) = apply {
76 | uiSelector = uiSelector.longClickable(longClickable)
77 | }
78 |
79 | fun packageName(packageName: String) = apply {
80 | uiSelector = uiSelector.packageName(packageName)
81 | }
82 |
83 | fun packageNameMatches(regex: String) = apply {
84 | uiSelector = uiSelector.packageNameMatches(regex)
85 | }
86 |
87 | fun parent(select: RelaxSelector.() -> Unit) = apply {
88 | val selector = RelaxSelector(packageName).apply(select).toUiSelector()
89 | uiSelector = uiSelector.fromParent(selector)
90 | }
91 |
92 | fun resId(resId: String) = apply {
93 | val id = when {
94 | resId.startsWith("id/") -> "$packageName:$resId"
95 | resId.contains(":id/") -> resId
96 | else -> "$packageName:id/$resId"
97 | }
98 | uiSelector = uiSelector.resourceId(id)
99 | }
100 |
101 | fun resIdMatches(regex: String) = apply {
102 | uiSelector = uiSelector.resourceIdMatches(regex)
103 | }
104 |
105 | fun scrollable(scrollable: Boolean) = apply {
106 | uiSelector = uiSelector.scrollable(scrollable)
107 | }
108 |
109 | fun selected(selected: Boolean) = apply {
110 | uiSelector = uiSelector.selected(selected)
111 | }
112 |
113 | fun text(text: String) = apply {
114 | uiSelector = uiSelector.text(text)
115 | }
116 |
117 | fun textContains(text: String) = apply {
118 | uiSelector = uiSelector.textContains(text)
119 | }
120 |
121 | fun textMatches(regex: String) = apply {
122 | uiSelector = uiSelector.textMatches(regex)
123 | }
124 |
125 | fun textOrResId(textOrResId: String) = apply {
126 | uiSelector = when {
127 | textOrResId.startsWith("id/") -> {
128 | uiSelector.resourceId("$packageName:$textOrResId")
129 | }
130 | textOrResId.contains(":id/") -> uiSelector.resourceId(textOrResId)
131 | else -> uiSelector.text(textOrResId)
132 | }
133 | }
134 |
135 | fun textStartsWith(text: String) = apply {
136 | uiSelector = uiSelector.textStartsWith(text)
137 | }
138 |
139 | fun toUiSelector(): UiSelector {
140 | return uiSelector
141 | }
142 |
143 | override fun toString(): String {
144 | return StringBuilder()
145 | .append(RelaxSelector::class.java.simpleName)
146 | .append('[')
147 | .append(uiSelector.toString())
148 | .append(']')
149 | .toString()
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Relax
2 |
3 | Relax is a lightweight wrapper around Android's UI Automator library. It helps write clear and concise UI tests:
4 |
5 | ```kotlin
6 | Relax("com.example.myapp") {
7 | pressHome()
8 | launch()
9 | inputText("me@example.com", "id/email")
10 | inputText("v3ry_s3cur3", "id/password")
11 | click("Login")
12 | assertExists {
13 | textStartsWith("Welcome")
14 | }
15 | }
16 | ```
17 |
18 | Rather than:
19 |
20 | ```kotlin
21 | val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
22 | device.pressHome()
23 | device.wait(Until.hasObject(By.pkg(device.launcherPackageName).depth(0)), 5_000)
24 |
25 | val context = ApplicationProvider.getApplicationContext()
26 | val packageName = "com.example.myapp"
27 | val intent = context.packageManager.getLaunchIntentForPackage(packageName)!!
28 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
29 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
30 | context.startActivity(intent)
31 | device.wait(Until.hasObject(By.pkg(packageName).depth(0)), 5_000)
32 |
33 | device.findObject(UiSelector().resourceId("$packageName:id/email")).text = "me@example.com"
34 | device.findObject(UiSelector().resourceId("$packageName:id/password")).text = "v3ry_s3cur3"
35 | device.findObject(UiSelector().text("Login")).click()
36 | device.waitForIdle()
37 |
38 | assertTrue(device.findObject(UiSelector().textStartsWith("Welcome")).exists())
39 | ```
40 |
41 | ## Installation
42 |
43 | In your project's `build.gradle`:
44 |
45 | ```kotlin
46 | dependencies {
47 | androidTestImplementation("com.emergetools.test:relax:0.1.0")
48 | // or use implementation if in test module
49 | }
50 | ```
51 |
52 | **⚠️ Relax is currently in an experimental state and is subject to breaking changes.**
53 |
54 | ## Getting Started
55 |
56 | Relax allows you to build UI test flows as a sequence of actions:
57 |
58 | ```kotlin
59 | Relax("") {
60 | // Arbitrary actions
61 | }
62 | ```
63 |
64 | ## Application Management
65 |
66 | Launch the application:
67 | ```kotlin
68 | launch()
69 | ```
70 |
71 | Using a deeplink:
72 | ```kotlin
73 | launchWithLink("custom://…")
74 | ```
75 |
76 | Force-stop the application (requires `com.android.test` module):
77 | ```kotlin
78 | forceStop()
79 | ```
80 |
81 | Clear all data associated with the application package (requires `com.android.test` module):
82 | ```kotlin
83 | clearData()
84 | ```
85 |
86 | ## Click
87 |
88 | By exact text:
89 | ```kotlin
90 | click("Text")
91 | ```
92 |
93 | By id:
94 | ```kotlin
95 | click("id/my_view_id")
96 | ```
97 |
98 | By class:
99 | ```kotlin
100 | click(Button::class.java)
101 | ```
102 |
103 | Comprehensive selector:
104 | ```kotlin
105 | click {
106 | textContains("Milk")
107 | checkable(true)
108 | // …
109 | }
110 | ```
111 |
112 | On specific coordinates:
113 | ```kotlin
114 | click(x, y)
115 | ```
116 |
117 | To long click simply use `longClick` instead of `click`.
118 |
119 | ## Input Text
120 |
121 | ```kotlin
122 | inputText("Ob-la-di", "Input Label")
123 | inputText("ob-la-da", "id/input")
124 | inputText("life goes on", EditText::class.java)
125 | inputText("brah") {
126 | // Arbitrary selectors
127 | }
128 | ```
129 |
130 | ## Scroll
131 |
132 | ```kotlin
133 | scrollForward("Text")
134 | scrollBackward("id/list")
135 | scrollToBeginning {
136 | // Arbitrary selectors
137 | }
138 | scrollToEnd(maxSwipes = 2, "id/list")
139 | ```
140 |
141 | ## Swipe
142 |
143 | ```kotlin
144 | swipeUp("Text")
145 | swipeDown("id/carousel")
146 | swipeLeft(CarouselView::class.java)
147 | swipeRight {
148 | // Arbitrary selectors
149 | }
150 | ```
151 |
152 | ## System Buttons
153 |
154 | ```kotlin
155 | pressHome()
156 | pressBack()
157 | ```
158 |
159 | ## Selectors
160 |
161 | The same selectors as [`UiSelector`](https://developer.android.com/reference/androidx/test/uiautomator/UiSelector) are available:
162 |
163 | ```kotlin
164 | click { // Or any other action that accepts selectors
165 | checkable(true)
166 | checked(true)
167 | child {
168 | // Arbitrary child selectors
169 | }
170 | className(MyView::class.java)
171 | className("com.example.myapp.MyView")
172 | classNameMatches("regex")
173 | description("description")
174 | descriptionContains("cript")
175 | descriptionMatches("regex")
176 | descriptionStartsWith("desc")
177 | enabled(true)
178 | focusable(true)
179 | focused(true)
180 | index(0)
181 | instance(0)
182 | longClickable(true)
183 | packageName("com.example.myapp")
184 | packageNameMatches("regex")
185 | parent {
186 | // Arbitrary parent selectors
187 | }
188 | resId("my_id")
189 | resIdMatches("regex")
190 | scrollable(true)
191 | selected(true)
192 | text("Text")
193 | textContains("x")
194 | textMatches("regex")
195 | textStartsWith("Te")
196 | }
197 | ```
198 |
199 | ## Assert
200 |
201 | ```kolint
202 | assertExists("Text")
203 | assertExists("id/my_view")
204 | assertNotExists(MyView::class.java)
205 | assertNotExists {
206 | // Arbitrary selectors
207 | }
208 | ```
209 |
210 | ## Handle Errors
211 |
212 | By default if an object cannot be found or an action cannot be completed the test will fail. This behavior can be easily modified.
213 |
214 | Making some actions optional:
215 | ```kotlin
216 | optional {
217 | inputText("SAVE10", "Coupon")
218 | }
219 | click("Purchase")
220 | ```
221 |
222 | Ignoring all failures by default:
223 | ```kotlin
224 | val config = FlowConfig(errorHandler = NoOpFlowErrorHandler)
225 | Relax("id", config) {
226 | // …
227 | }
228 | ```
229 |
230 | Custom error handler:
231 | ```kotlin
232 | val errorHandler = object : FlowErrorHandler {
233 | override fun onError(error: Throwable) {
234 | // …
235 | }
236 | }
237 | val config = FlowConfig(errorHandler = errorHandler)
238 | Relax("id", config) {
239 | // …
240 | }
241 | ```
242 |
243 | ## UI Automator Interoperability
244 |
245 | Relax is a lightweight wrapper around UI Automator, therefore it's easy to leverage the full feature set of UI Automator. For example:
246 |
247 | ```kotlin
248 | Relax(/* … */) {
249 | if (!device.isScreenOn) device.wakeUp()
250 | launch()
251 | click("Next")
252 | device.takeScreenshot(storePath)
253 | // …
254 | }
255 | ```
256 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/relax/src/main/java/com/emergetools/relax/Flow.kt:
--------------------------------------------------------------------------------
1 | package com.emergetools.relax
2 |
3 | import android.app.Instrumentation
4 | import android.app.UiAutomation
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.net.Uri
8 | import android.os.Build
9 | import android.os.ParcelFileDescriptor
10 | import androidx.test.core.app.ApplicationProvider
11 | import androidx.test.platform.app.InstrumentationRegistry
12 | import androidx.test.uiautomator.*
13 | import com.emergetools.relax.internal.DebugInterceptor
14 | import com.emergetools.relax.internal.TracingInterceptor
15 | import org.junit.Assert
16 | import java.util.concurrent.Executors
17 | import java.util.concurrent.TimeUnit
18 | import java.util.concurrent.TimeoutException
19 |
20 | class Flow(val packageName: String, val config: FlowConfig) {
21 |
22 | val appContext: Context get() = ApplicationProvider.getApplicationContext()
23 |
24 | val instrumentation: Instrumentation get() = InstrumentationRegistry.getInstrumentation()
25 |
26 | val device: UiDevice get() = UiDevice.getInstance(instrumentation)
27 |
28 | val uiAutomation: UiAutomation
29 | get() {
30 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
31 | instrumentation.getUiAutomation(Configurator.getInstance().uiAutomationFlags)
32 | } else {
33 | instrumentation.uiAutomation
34 | }
35 | }
36 |
37 | private val interceptors = listOfNotNull(
38 | if (config.debug) DebugInterceptor else null,
39 | if (config.trace) TracingInterceptor else null
40 | )
41 |
42 | init {
43 | // Ensures UiDevice is properly initialized. UiObject has a deprecated constructor which is still used internally by UI Automator but fails if
44 | // UiDevice was not first initialized with an Instrumentation instance.
45 | device
46 | }
47 |
48 | fun optional(flow: Flow.() -> Unit) = intercept {
49 | Flow(packageName, config.copy(errorHandler = NoOpFlowErrorHandler)).flow()
50 | }
51 |
52 | /**
53 | * Waits for the accessibility event stream to become idle. If the timeout is reached the
54 | * function returns normally with no errors.
55 | *
56 | * @param timeout in milliseconds, default to the config value
57 | */
58 | fun waitForIdle(timeout: Long = config.waitForIdleTimeout) = intercept {
59 | device.waitForIdle(timeout)
60 | }
61 |
62 | fun waitForReportFullyDrawn(
63 | timeout: Long = config.reportFullyDrawnTimeout,
64 | unit: TimeUnit = TimeUnit.MILLISECONDS,
65 | block: () -> Unit
66 | ) {
67 | uiAutomation.executeShellCommand("timeout ${unit.toSeconds(timeout)} logcat -T 1 -v raw -s ActivityTaskManager:I").use { fileDescriptor ->
68 | ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor).use { inputStream ->
69 | val executor = Executors.newSingleThreadExecutor()
70 | val future = executor.submit {
71 | inputStream.bufferedReader().lineSequence()
72 | .find { it.startsWith("Fully drawn $packageName") }
73 | inputStream.close()
74 | }
75 |
76 | block()
77 |
78 | try {
79 | future.get()
80 | } catch (e: TimeoutException) {
81 | config.errorHandler.onError(e)
82 | } finally {
83 | executor.shutdownNow()
84 | }
85 | }
86 | }
87 | }
88 |
89 | /**
90 | * Simulates a short press on the HOME button and waits for the system launcher to appear.
91 | *
92 | * @return true if successful, false otherwise
93 | */
94 | fun pressHome(): Boolean = intercept {
95 | device.pressHome().also { result ->
96 | if (!result) error(UnsupportedOperationException("pressHome"))
97 | waitForlaunch(device.launcherPackageName)
98 | }
99 | }
100 |
101 | /**
102 | * Simulates a short press on the BACK button and waits for the application to become idle.
103 | *
104 | * @return true if successful, false otherwise
105 | */
106 | fun pressBack(): Boolean = intercept {
107 | device.pressBack().also { result ->
108 | if (!result) error(UnsupportedOperationException("pressBack"))
109 | waitForIdle()
110 | }
111 | }
112 |
113 | /**
114 | * Force-stops the application. Requires using a "com.android.test" module.
115 | *
116 | * @param packageName the package name of the application to force-stop, defaults to the flow's
117 | * package name
118 | */
119 | fun forceStop(packageName: String = this.packageName) = intercept {
120 | device.executeShellCommand("am force-stop $packageName")
121 | }
122 |
123 | /**
124 | * Deletes all data associated with the package. Requires using a "com.android.test" module.
125 | *
126 | * @param packageName the package name of the application to clear, defaults to the flow's
127 | * package name
128 | */
129 | fun clearData(packageName: String = this.packageName) = intercept {
130 | device.executeShellCommand("pm clear $packageName")
131 | }
132 |
133 | /**
134 | * Launches the application and waits for it to appear.
135 | *
136 | * @param packageName the package name of the application to launch, defaults to the flow's
137 | * package name
138 | */
139 | fun launch(packageName: String = this.packageName) = intercept {
140 | val intent =
141 | checkNotNull(appContext.packageManager.getLaunchIntentForPackage(packageName)) {
142 | "Could not find launch intent for app $packageName"
143 | }
144 | // Clear out any previous instances
145 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
146 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
147 | appContext.startActivity(intent)
148 |
149 | waitForlaunch(packageName)
150 | }
151 |
152 | /**
153 | * Launches the application using a link and waits for it to appear.
154 | */
155 | fun launchWithLink(link: String) = intercept {
156 | val intent = Intent(Intent.ACTION_VIEW)
157 | intent.data = Uri.parse(link)
158 |
159 | // Clear out any previous instances
160 | intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
161 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
162 | appContext.startActivity(intent)
163 |
164 | waitForlaunch()
165 | }
166 |
167 | /**
168 | * "Cold" launches the application and waits for it to appear. This is a shortcut for
169 | * force-stopping the application and launching it again. Requires using a "com.android.test"
170 | * module.
171 | */
172 | fun coldLaunch(packageName: String = this.packageName) = intercept {
173 | forceStop(packageName)
174 | launch(packageName)
175 | }
176 |
177 | /**
178 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
179 | * otherwise searches for the element whose visible text matches exactly. Matching is
180 | * case-sensitive.
181 | * @return A UiObject which represents a view that matches the criteria.
182 | */
183 | fun findObject(textOrResId: String) = findObject {
184 | textOrResId(textOrResId)
185 | }
186 |
187 | /**
188 | * If the object exists, calls [block] on it and returns its return value, otherwise returns
189 | * [default].
190 | */
191 | private fun findObject(
192 | select: RelaxSelector.() -> Unit,
193 | default: T,
194 | block: (UiObject) -> T
195 | ): T {
196 | val obj = findObject(select)
197 | return if (obj.exists()) block(obj) else default
198 | }
199 |
200 | /**
201 | * @return A UiObject which represents a view that matches the criteria.
202 | */
203 | fun findObject(select: RelaxSelector.() -> Unit): UiObject = intercept {
204 | val selector = RelaxSelector(packageName).apply(select).toUiSelector()
205 | device.findObject(selector).also {
206 | if (!it.exists()) error(UiObjectNotFoundException(it.selector.toString()))
207 | }
208 | }
209 |
210 | /**
211 | * Performs a click at the center of the visible bounds of the UI element that matches the
212 | * criteria.
213 | *
214 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
215 | * otherwise searches for the element whose visible text matches exactly. Matching is
216 | * case-sensitive.
217 | * @return true if successful, false otherwise
218 | */
219 | fun click(textOrResId: String): Boolean = click { textOrResId(textOrResId) }
220 |
221 | /**
222 | * Performs a click at the center of the visible bounds of the UI element that matches the
223 | * criteria.
224 | *
225 | * @return true if successful, false otherwise
226 | */
227 | fun click(type: Class<*>): Boolean = click { className(type) }
228 |
229 | /**
230 | * Performs a click at the center of the visible bounds of the UI element that matches the
231 | * criteria.
232 | *
233 | * @return true if successful, false otherwise
234 | */
235 | fun click(select: RelaxSelector.() -> Unit): Boolean = intercept {
236 | findObject(select, false) {
237 | it.click().also { result ->
238 | if (!result) error(UnsupportedOperationException("click ${it.selector}"))
239 | waitForIdle()
240 | }
241 | }
242 | }
243 |
244 | /**
245 | * Performs a click at arbitrary coordinates.
246 | *
247 | * @return true if successful, false otherwise
248 | */
249 | fun click(x: Int, y: Int): Boolean = intercept {
250 | device.click(x, y).also { result ->
251 | if (!result) error(UnsupportedOperationException("click [x=$x, y=$y]"))
252 | waitForIdle()
253 | }
254 | }
255 |
256 | /**
257 | * Performs a long click at the center of the visible bounds of the UI element that matches the
258 | * criteria.
259 | *
260 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
261 | * otherwise searches for the element whose visible text matches exactly. Matching is
262 | * case-sensitive.
263 | * @return true if successful, false otherwise
264 | */
265 | fun longClick(textOrResId: String): Boolean = longClick {
266 | textOrResId(textOrResId)
267 | }
268 |
269 | /**
270 | * Performs a long click at the center of the visible bounds of the UI element that matches the
271 | * criteria.
272 | *
273 | * @return true if successful, false otherwise
274 | */
275 | fun longClick(type: Class<*>): Boolean = longClick { className(type) }
276 |
277 | /**
278 | * Performs a long click at the center of the visible bounds of the UI element that matches the
279 | * criteria.
280 | *
281 | * @return true if successful, false otherwise
282 | */
283 | fun longClick(select: RelaxSelector.() -> Unit): Boolean = intercept {
284 | findObject(select, false) {
285 | it.longClick().also { result ->
286 | if (!result) error(UnsupportedOperationException("longClick ${it.selector}"))
287 | waitForIdle()
288 | }
289 | }
290 | }
291 |
292 | /**
293 | * Sets the text in an editable field, after clearing the field's content. The search criteria
294 | * must reference a UI element that is editable.
295 | *
296 | * @param inputText the text to set
297 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
298 | * otherwise searches for the element whose visible text matches exactly. Matching is
299 | * case-sensitive.
300 | * @return true if successful, false otherwise
301 | */
302 | fun inputText(inputText: String, textOrResId: String) = inputText(inputText) {
303 | textOrResId(textOrResId)
304 | }
305 |
306 | /**
307 | * Sets the text in an editable field, after clearing the field's content. The search criteria
308 | * must reference a UI element that is editable.
309 | *
310 | * @param inputText the text to set
311 | * @return true if successful, false otherwise
312 | */
313 | fun inputText(inputText: String, type: Class<*>) = inputText(inputText) {
314 | className(type)
315 | }
316 |
317 | /**
318 | * Sets the text in an editable field, after clearing the field's content. The search criteria
319 | * must reference a UI element that is editable.
320 | *
321 | * @param inputText the text to set
322 | * @return true if successful, false otherwise
323 | */
324 | fun inputText(inputText: String, select: RelaxSelector.() -> Unit): Boolean = intercept {
325 | findObject(select, false) {
326 | it.setText(inputText).also { result ->
327 | if (!result) error(UnsupportedOperationException("inputText $inputText ${it.selector}"))
328 | waitForIdle()
329 | }
330 | }
331 | }
332 |
333 | /**
334 | * @param text Searches for the element whose visible text matches exactly. Matching is
335 | * case-sensitive.
336 | * @return UiScrollable instance that meets the criteria
337 | */
338 | fun scrollable(textOrResId: String): UiScrollable {
339 | return scrollable { textOrResId(textOrResId) }
340 | }
341 |
342 | /**
343 | * @return UiScrollable instance that meets the criteria
344 | */
345 | fun scrollable(type: Class<*>): UiScrollable {
346 | return scrollable { className(type) }
347 | }
348 |
349 | /**
350 | * If the object exists, calls [block] on it and returns its return value, otherwise returns
351 | * [default].
352 | */
353 | private fun scrollable(
354 | select: RelaxSelector.() -> Unit,
355 | default: T,
356 | block: (UiScrollable) -> T
357 | ): T {
358 | val obj = scrollable(select)
359 | return if (obj.exists()) block(obj) else default
360 | }
361 |
362 | /**
363 | * @return UiScrollable instance that meets the criteria
364 | */
365 | fun scrollable(select: RelaxSelector.() -> Unit): UiScrollable {
366 | val selector = RelaxSelector(packageName).apply(select).toUiSelector()
367 | return UiScrollable(selector).also {
368 | if (!it.exists()) error(UiObjectNotFoundException(it.selector.toString()))
369 | }
370 | }
371 |
372 | /**
373 | * Performs a forward scroll. If the swipe direction is set to vertical, then the swipes will be
374 | * performed from bottom to top. If the swipe direction is set to horizontal, then the swipes
375 | * will be performed from right to left. Make sure to take into account devices configured with
376 | * right-to-left languages like Arabic and Hebrew.
377 | *
378 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
379 | * otherwise searches for the element whose visible text matches exactly. Matching is
380 | * case-sensitive.
381 | * @return true if scrolled, false if can't scroll anymore
382 | */
383 | fun scrollForward(textOrResId: String): Boolean = scrollForward {
384 | textOrResId(textOrResId)
385 | }
386 |
387 | /**
388 | * Performs a forward scroll. If the swipe direction is set to vertical, then the swipes will be
389 | * performed from bottom to top. If the swipe direction is set to horizontal, then the swipes
390 | * will be performed from right to left. Make sure to take into account devices configured with
391 | * right-to-left languages like Arabic and Hebrew.
392 | *
393 | * @return true if scrolled, false if can't scroll anymore
394 | */
395 | fun scrollForward(type: Class<*>): Boolean = scrollForward {
396 | className(type)
397 | }
398 |
399 | /**
400 | * Performs a forward scroll. If the swipe direction is set to vertical, then the swipes will be
401 | * performed from bottom to top. If the swipe direction is set to horizontal, then the swipes
402 | * will be performed from right to left. Make sure to take into account devices configured with
403 | * right-to-left languages like Arabic and Hebrew.
404 | *
405 | * @return true if scrolled, false if can't scroll anymore
406 | */
407 | fun scrollForward(select: RelaxSelector.() -> Unit): Boolean = intercept {
408 | scrollable(select, false) {
409 | it.scrollForward().also { result ->
410 | if (!result) error(UnsupportedOperationException("scrollForward ${it.selector}"))
411 | }
412 | }
413 | }
414 |
415 | /**
416 | * Performs a backward scroll. If the swipe direction is set to vertical, then the swipes will
417 | * be performed from top to bottom. If the swipe direction is set to horizontal, then the swipes
418 | * will be performed from left to right. Make sure to take into account devices configured with
419 | * right-to-left languages like Arabic and Hebrew.
420 | *
421 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
422 | * otherwise searches for the element whose visible text matches exactly. Matching is
423 | * case-sensitive.
424 | * @return true if scrolled, false if can't scroll anymore
425 | */
426 | fun scrollBackward(textOrResId: String): Boolean = scrollBackward {
427 | textOrResId(textOrResId)
428 | }
429 |
430 | /**
431 | * Performs a backward scroll. If the swipe direction is set to vertical, then the swipes will
432 | * be performed from top to bottom. If the swipe direction is set to horizontal, then the swipes
433 | * will be performed from left to right. Make sure to take into account devices configured with
434 | * right-to-left languages like Arabic and Hebrew.
435 | *
436 | * @return true if scrolled, false if can't scroll anymore
437 | */
438 | fun scrollBackward(type: Class<*>): Boolean = scrollBackward {
439 | className(type)
440 | }
441 |
442 | /**
443 | * Performs a backward scroll. If the swipe direction is set to vertical, then the swipes will
444 | * be performed from top to bottom. If the swipe direction is set to horizontal, then the swipes
445 | * will be performed from left to right. Make sure to take into account devices configured with
446 | * right-to-left languages like Arabic and Hebrew.
447 | *
448 | * @return true if scrolled, false if can't scroll anymore
449 | */
450 | fun scrollBackward(select: RelaxSelector.() -> Unit): Boolean = intercept {
451 | scrollable(select, false) {
452 | it.scrollBackward().also { result ->
453 | if (!result) error(UnsupportedOperationException("scrollBackward ${it.selector}"))
454 | }
455 | }
456 | }
457 |
458 | /**
459 | * Scrolls to the end of a scrollable layout element. The end can be at the bottom-most edge in
460 | * the case of vertical controls, or the right-most edge for horizontal controls. Make sure to
461 | * take into account devices configured with right-to-left languages like Arabic and Hebrew.
462 | *
463 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
464 | * otherwise searches for the element whose visible text matches exactly. Matching is
465 | * case-sensitive.
466 | * @return true if scrolled, false if can't scroll anymore
467 | */
468 | fun scrollToEnd(
469 | maxSwipes: Int = config.scrollToMaxSwipes,
470 | textOrResId: String
471 | ): Boolean = scrollToEnd(maxSwipes) { textOrResId(textOrResId) }
472 |
473 |
474 | /**
475 | * Scrolls to the end of a scrollable layout element. The end can be at the bottom-most edge in
476 | * the case of vertical controls, or the right-most edge for horizontal controls. Make sure to
477 | * take into account devices configured with right-to-left languages like Arabic and Hebrew.
478 | *
479 | * @return true if scrolled, false if can't scroll anymore
480 | */
481 | fun scrollToEnd(
482 | maxSwipes: Int = config.scrollToMaxSwipes,
483 | type: Class<*>
484 | ): Boolean = scrollToEnd(maxSwipes) { className(type) }
485 |
486 | /**
487 | * Scrolls to the end of a scrollable layout element. The end can be at the bottom-most edge in
488 | * the case of vertical controls, or the right-most edge for horizontal controls. Make sure to
489 | * take into account devices configured with right-to-left languages like Arabic and Hebrew.
490 | *
491 | * @return true if scrolled, false if can't scroll anymore
492 | */
493 | fun scrollToEnd(
494 | maxSwipes: Int = config.scrollToMaxSwipes,
495 | select: RelaxSelector.() -> Unit
496 | ): Boolean = intercept {
497 | scrollable(select, false) {
498 | it.scrollToEnd(maxSwipes).also { result ->
499 | if (!result) error(UnsupportedOperationException("scrollToEnd ${it.selector}"))
500 | }
501 | }
502 | }
503 |
504 | /**
505 | * Scrolls to the beginning of a scrollable layout element. The beginning can be at the top-most
506 | * edge in the case of vertical controls, or the left-most edge for horizontal controls. Make
507 | * sure to take into account devices configured with right-to-left languages like Arabic and
508 | * Hebrew.
509 | *
510 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
511 | * otherwise searches for the element whose visible text matches exactly. Matching is
512 | * case-sensitive.
513 | * @return true if scrolled, false if can't scroll anymore
514 | */
515 | fun scrollToBeginning(
516 | maxSwipes: Int = config.scrollToMaxSwipes,
517 | textOrResId: String
518 | ): Boolean = scrollToBeginning(maxSwipes) { textOrResId(textOrResId) }
519 |
520 | /**
521 | * Scrolls to the beginning of a scrollable layout element. The beginning can be at the top-most
522 | * edge in the case of vertical controls, or the left-most edge for horizontal controls. Make
523 | * sure to take into account devices configured with right-to-left languages like Arabic and
524 | * Hebrew.
525 | *
526 | * @return true if scrolled, false if can't scroll anymore
527 | */
528 | fun scrollToBeginning(
529 | maxSwipes: Int = config.scrollToMaxSwipes,
530 | type: Class<*>
531 | ): Boolean = scrollToBeginning(maxSwipes) { className(type) }
532 |
533 | /**
534 | * Scrolls to the beginning of a scrollable layout element. The beginning can be at the top-most
535 | * edge in the case of vertical controls, or the left-most edge for horizontal controls. Make
536 | * sure to take into account devices configured with right-to-left languages like Arabic and
537 | * Hebrew.
538 | *
539 | * @return true if scrolled, false if can't scroll anymore
540 | */
541 | fun scrollToBeginning(
542 | maxSwipes: Int = config.scrollToMaxSwipes,
543 | select: RelaxSelector.() -> Unit
544 | ): Boolean = intercept {
545 | scrollable(select, false) {
546 | it.scrollToBeginning(maxSwipes).also { result ->
547 | if (!result) error(UnsupportedOperationException("scrollToBeginning ${it.selector}"))
548 | }
549 | }
550 | }
551 |
552 | /**
553 | * Performs the swipe down action on the UiObject. The swipe gesture can be performed over any
554 | * surface. The targeted UI element does not need to be scrollable.
555 | *
556 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
557 | * otherwise searches for the element whose visible text matches exactly. Matching is
558 | * case-sensitive.
559 | * @return true if successful, false otherwise
560 | */
561 | fun swipeDown(textOrResId: String): Boolean = swipeDown { textOrResId(textOrResId) }
562 |
563 | /**
564 | * Performs the swipe down action on the UiObject. The swipe gesture can be performed over any
565 | * surface. The targeted UI element does not need to be scrollable.
566 | *
567 | * @return true if successful, false otherwise
568 | */
569 | fun swipeDown(type: Class<*>): Boolean = swipeDown { className(type) }
570 |
571 | /**
572 | * Performs the swipe down action on the UiObject. The swipe gesture can be performed over any
573 | * surface. The targeted UI element does not need to be scrollable.
574 | *
575 | * @return true if successful, false otherwise
576 | */
577 | fun swipeDown(select: RelaxSelector.() -> Unit): Boolean = intercept {
578 | findObject(select, false) {
579 | it.swipeDown(config.swipeSteps).also { result ->
580 | if (!result) error(UnsupportedOperationException("swipeDown ${it.selector}"))
581 | }
582 | }
583 | }
584 |
585 | /**
586 | * Performs the swipe left action on the UiObject. The swipe gesture can be performed over any
587 | * surface. The targeted UI element does not need to be scrollable.
588 | *
589 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
590 | * otherwise searches for the element whose visible text matches exactly. Matching is
591 | * case-sensitive.
592 | * @return true if successful, false otherwise
593 | */
594 | fun swipeLeft(textOrResId: String): Boolean = swipeLeft { textOrResId(textOrResId) }
595 |
596 | /**
597 | * Performs the swipe left action on the UiObject. The swipe gesture can be performed over any
598 | * surface. The targeted UI element does not need to be scrollable.
599 | *
600 | * @return true if successful, false otherwise
601 | */
602 | fun swipeLeft(type: Class<*>): Boolean = swipeLeft { className(type) }
603 |
604 | /**
605 | * Performs the swipe left action on the UiObject. The swipe gesture can be performed over any
606 | * surface. The targeted UI element does not need to be scrollable.
607 | *
608 | * @return true if successful, false otherwise
609 | */
610 | fun swipeLeft(select: RelaxSelector.() -> Unit): Boolean = intercept {
611 | findObject(select, false) {
612 | it.swipeLeft(config.swipeSteps).also { result ->
613 | if (!result) error(UnsupportedOperationException("swipeLeft ${it.selector}"))
614 | }
615 | }
616 | }
617 |
618 | /**
619 | * Performs the swipe right action on the UiObject. The swipe gesture can be performed over any
620 | * surface. The targeted UI element does not need to be scrollable.
621 | *
622 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
623 | * otherwise searches for the element whose visible text matches exactly. Matching is
624 | * case-sensitive.
625 | * @return true if successful, false otherwise
626 | */
627 | fun swipeRight(textOrResId: String): Boolean = swipeRight { textOrResId(textOrResId) }
628 |
629 | /**
630 | * Performs the swipe right action on the UiObject. The swipe gesture can be performed over any
631 | * surface. The targeted UI element does not need to be scrollable.
632 | *
633 | * @return true if successful, false otherwise
634 | */
635 | fun swipeRight(type: Class<*>): Boolean = swipeRight { className(type) }
636 |
637 | /**
638 | * Performs the swipe right action on the UiObject. The swipe gesture can be performed over any
639 | * surface. The targeted UI element does not need to be scrollable.
640 | *
641 | * @return true if successful, false otherwise
642 | */
643 | fun swipeRight(select: RelaxSelector.() -> Unit): Boolean = intercept {
644 | findObject(select, false) {
645 | it.swipeRight(config.swipeSteps).also { result ->
646 | if (!result) error(UnsupportedOperationException("swipeRight ${it.selector}"))
647 | }
648 | }
649 | }
650 |
651 | /**
652 | * Performs the swipe up action on the UiObject. The swipe gesture can be performed over any
653 | * surface. The targeted UI element does not need to be scrollable.
654 | *
655 | * @param textOrResId If the string contains ":id/" it will be treated as a resource ID,
656 | * otherwise searches for the element whose visible text matches exactly. Matching is
657 | * case-sensitive.
658 | * @return true if successful, false otherwise
659 | */
660 | fun swipeUp(textOrResId: String): Boolean = swipeUp { textOrResId(textOrResId) }
661 |
662 | /**
663 | * Performs the swipe up action on the UiObject. The swipe gesture can be performed over any
664 | * surface. The targeted UI element does not need to be scrollable.
665 | *
666 | * @return true if successful, false otherwise
667 | */
668 | fun swipeUp(type: Class<*>): Boolean = swipeUp { className(type) }
669 |
670 | /**
671 | * Performs the swipe up action on the UiObject. The swipe gesture can be performed over any
672 | * surface. The targeted UI element does not need to be scrollable.
673 | *
674 | * @return true if successful, false otherwise
675 | */
676 | fun swipeUp(select: RelaxSelector.() -> Unit): Boolean = intercept {
677 | findObject(select, false) {
678 | it.swipeUp(config.swipeSteps).also { result ->
679 | if (!result) error(UnsupportedOperationException("swipeUp ${it.selector}"))
680 | }
681 | }
682 | }
683 |
684 | fun assertExists(textOrResId: String) = assertExists { textOrResId(textOrResId) }
685 |
686 | fun assertExists(type: Class<*>) = assertExists { className(type) }
687 |
688 | fun assertExists(select: RelaxSelector.() -> Unit) = intercept {
689 | Assert.assertTrue(findObject(select).exists())
690 | }
691 |
692 | fun assertNotExists(textOrResId: String) = assertNotExists { textOrResId(textOrResId) }
693 |
694 | fun assertNotExists(type: Class<*>) = assertNotExists { className(type) }
695 |
696 | fun assertNotExists(select: RelaxSelector.() -> Unit) = intercept {
697 | Assert.assertFalse(findObject(select).exists())
698 | }
699 |
700 | private fun intercept(call: () -> T): T {
701 | val caller = Thread.currentThread().stackTrace
702 | .firstOrNull {
703 | it.className == Flow::class.java.canonicalName &&
704 | it.methodName != "intercept"
705 | }
706 | ?.methodName
707 | ?: "unknown"
708 |
709 | return interceptors.fold(call) { acc, interceptor ->
710 | { interceptor.intercept(caller, acc) }
711 | }.invoke()
712 | }
713 |
714 | private fun waitForlaunch(packageName: String = this.packageName) {
715 | device.wait(
716 | Until.hasObject(By.pkg(packageName).depth(0)),
717 | config.launchTimeout
718 | )
719 | ?: error(TimeoutException("Launch of $packageName timed out after ${config.launchTimeout}ms"))
720 | }
721 |
722 | private fun error(e: Throwable) {
723 | config.errorHandler.onError(e)
724 | }
725 | }
726 |
--------------------------------------------------------------------------------