Skip to content

Instantly share code, notes, and snippets.

@4xes
Created January 17, 2019 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4xes/1c8d6eb4c7123e64499061569f6bec38 to your computer and use it in GitHub Desktop.
Save 4xes/1c8d6eb4c7123e64499061569f6bec38 to your computer and use it in GitHub Desktop.
package editor.video.motion.fast.slow.core.utils
import android.os.SystemClock
import android.support.test.espresso.*
import android.view.View
import org.hamcrest.Matcher
import java.lang.Exception
import java.util.concurrent.TimeoutException
object TimeoutEspresso {
fun onViewTimeout(viewMatcher: Matcher<View>, defaultTime: Long = DEFAULT_TIMEOUT_IN_MILLIS): ViewInteraction {
return interaction(defaultTime, {
Espresso.onView(viewMatcher)
}, {
TimeoutException("Timeout occurred when trying to find: $viewMatcher")
})
}
}
fun ViewInteraction.performTimeout(vararg viewActions: ViewAction, defaultTime: Long = DEFAULT_TIMEOUT_IN_MILLIS): ViewInteraction {
return interaction(defaultTime, {
perform(*viewActions)
}, {
TimeoutException("Timeout occurred when trying to perform view actions: $viewActions")
})
}
fun ViewInteraction.checkTimeout(viewAssert: ViewAssertion, defaultTime: Long = DEFAULT_TIMEOUT_IN_MILLIS): ViewInteraction {
return interaction(defaultTime, {
check(viewAssert)
}, {
TimeoutException("Timeout occurred when trying to check: $viewAssert")
})
}
fun interaction(timeoutInMillis: Long, interactionCallback: () -> ViewInteraction, errorCallback: () -> Exception): ViewInteraction {
val startTime = System.currentTimeMillis()
val endTime = startTime + timeoutInMillis
do {
try {
return interactionCallback.invoke()
} catch (ex: RuntimeException) {
//ignore
}
SystemClock.sleep(SLEEP_IN_A_LOOP_TIME)
} while (System.currentTimeMillis() < endTime)
// timeout happens
throw PerformException.Builder()
.withCause(errorCallback.invoke())
.build()
}
private const val SLEEP_IN_A_LOOP_TIME = 50L
private const val DEFAULT_TIMEOUT_IN_MILLIS = 10L * 1000L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment