1717package androidx.test.espresso.device.action
1818
1919import android.util.Log
20+ import androidx.test.espresso.device.common.executeShellCommand
21+ import androidx.test.espresso.device.common.getMapOfDeviceStateNamesToIdentifiers
2022import androidx.test.espresso.device.common.getResumedActivityOrNull
2123import androidx.test.espresso.device.common.isRobolectricTest
2224import androidx.test.espresso.device.context.ActionContext
@@ -28,6 +30,7 @@ import androidx.window.layout.WindowInfoTracker
2830import androidx.window.layout.WindowLayoutInfo
2931import java.util.concurrent.CountDownLatch
3032import java.util.concurrent.Executor
33+ import java.util.concurrent.TimeUnit
3134import kotlinx.coroutines.CoroutineScope
3235import kotlinx.coroutines.asCoroutineDispatcher
3336import kotlinx.coroutines.flow.collect
@@ -95,6 +98,30 @@ internal open class BaseSingleFoldDeviceAction(
9598 }
9699
97100 deviceController.setDeviceMode(deviceMode.mode)
98- latch.await()
101+ latch.await(5 , TimeUnit .SECONDS )
102+
103+ if (latch.getCount() != 0L ) {
104+ // If WindowLayoutInfo is not updated to the requested state within five seconds, check device
105+ // state and throw DeviceControllerOperationException if the device is not in the requested
106+ // state.
107+ val finalDeviceStateIdentifier = executeShellCommand(" cmd device_state print-state" ).trim()
108+ val mapOfDeviceStateNamesToIdentifiers = getMapOfDeviceStateNamesToIdentifiers()
109+ val expectedDeviceState =
110+ when (foldingFeatureState) {
111+ FoldingFeature .State .FLAT -> " OPENED"
112+ FoldingFeature .State .HALF_OPENED -> " HALF_OPENED"
113+ else -> " CLOSED"
114+ }
115+ val currentDeviceState =
116+ mapOfDeviceStateNamesToIdentifiers
117+ .filterValues { finalDeviceStateIdentifier.trim().toString() == it }
118+ .keys
119+ .first()
120+ if (expectedDeviceState != currentDeviceState) {
121+ throw DeviceControllerOperationException (
122+ " Device could not be set to ${deviceMode} mode. Expected device state is ${expectedDeviceState} , actual state is ${currentDeviceState} ."
123+ )
124+ }
125+ }
99126 }
100127}
0 commit comments