1 package android.platform.test.rule
2 
3 import android.platform.test.rule.Orientation.LANDSCAPE
4 import android.platform.test.rule.Orientation.PORTRAIT
5 import org.junit.AssumptionViolatedException
6 import org.junit.rules.TestRule
7 import org.junit.runner.Description
8 import org.junit.runners.model.Statement
9 
10 /**
11  * Makes each test of the class that uses this rule execute twice, in [Orientation.LANDSCAPE] and
12  * [Orientation.PORTRAIT] orientation.
13  */
14 class PortraitLandscapeRule(
15     private val portraitDeviceFilter: List<DeviceTypeFilter> = listOf(DeviceTypeFilter.ANY),
16     private val landscapeDeviceFilter: List<DeviceTypeFilter> = listOf(DeviceTypeFilter.ANY)
17 ) : TestRule {
18 
applynull19     override fun apply(base: Statement, description: Description): Statement =
20         object : Statement() {
21             override fun evaluate() {
22                 try {
23                     if (portraitDeviceFilter.any { it.match() }) {
24                         base.runInOrientation(PORTRAIT)
25                     }
26                     if (landscapeDeviceFilter.any { it.match() }) {
27                         base.runInOrientation(LANDSCAPE)
28                     }
29                 } finally {
30                     RotationUtils.clearOrientationOverride()
31                 }
32             }
33         }
34 
Statementnull35     private fun Statement.runInOrientation(orientation: Orientation) {
36         RotationUtils.setOrientationOverride(orientation)
37         try {
38             evaluate()
39         } catch (e: AssumptionViolatedException) {
40             /**
41              * Pass [AssumptionViolatedException] through so that testing infra can properly ignore
42              * the failure. See b/330200243
43              */
44             throw e
45         } catch (e: Throwable) {
46             throw Exception("Test failed while in $orientation", e)
47         }
48     }
49 }
50