1 package android.platform.test.rule
2 
3 import android.platform.uiautomator_helpers.WaitUtils.ensureThat
4 import android.provider.Settings
5 import org.junit.rules.ExternalResource
6 
7 private val supportedTypes =
8     listOf(Boolean::class, Int::class, Long::class, Float::class, String::class)
9 
10 /** Base rule to set values in [Settings]. The value is then reset at the end of the test. */
11 abstract class SettingRule<T>(
12     private val initialValue: T? = null,
13 ) : ExternalResource() {
14 
15     private var originalValueAsString: String? = null
16 
beforenull17     override fun before() {
18         originalValueAsString = getSettingValueAsString()
19         if (initialValue != null) {
20             setSettingValue(initialValue)
21         }
22     }
23 
afternull24     override fun after() {
25         setSettingValueAsString(originalValueAsString)
26     }
27 
clearValuenull28     fun clearValue() {
29         setSettingValueAsString(null)
30     }
31 
getSettingValuenull32     inline fun <reified T> getSettingValue(): T? {
33         val valueAsString = getSettingValueAsString() ?: return null
34         val actualValue =
35             when (T::class) {
36                 Boolean::class -> valueAsString.toInt() == 1
37                 Int::class -> valueAsString.toInt()
38                 Long::class -> valueAsString.toLong()
39                 Float::class -> valueAsString.toFloat()
40                 String::class -> valueAsString
41                 else -> throw IllegalArgumentException("Type not supported: ${T::class}")
42             }
43         return actualValue as T
44     }
45 
setSettingValuenull46     fun setSettingValue(value: T?) {
47         val valueAsString =
48             when {
49                 value == null -> null
50                 value is Boolean -> if (value) "1" else "0"
51                 value!!::class in supportedTypes -> value.toString()
52                 else -> throw IllegalArgumentException("Unsupported type: ${value!!::class}")
53             }
54         setSettingValueAsString(valueAsString)
55         ensureThat("New setting value set") { getSettingValueAsString() == valueAsString }
56     }
57 
getSettingValueAsStringnull58     abstract fun getSettingValueAsString(): String?
59 
60     abstract fun setSettingValueAsString(value: String?)
61 }
62