1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.testutils
18 
19 import com.android.tradefed.invoker.TestInformation
20 import com.android.tradefed.targetprep.BaseTargetPreparer
21 
22 /**
23  * A target preparer that disables DeviceConfig sync while running a test.
24  *
25  * Without this preparer, tests that rely on stable values of DeviceConfig flags, for example to
26  * test behavior when setting the flag and resetting it afterwards, may flake as the flags may
27  * be synced with remote servers during the test.
28  */
29 class DisableConfigSyncTargetPreparer : BaseTargetPreparer() {
30     private var syncDisabledOriginalValue = "none"
31 
setUpnull32     override fun setUp(testInfo: TestInformation) {
33         if (isDisabled) return
34         syncDisabledOriginalValue = readSyncDisabledOriginalValue(testInfo)
35 
36         // The setter is the same in current and legacy S versions
37         testInfo.exec("cmd device_config set_sync_disabled_for_tests until_reboot")
38     }
39 
tearDownnull40     override fun tearDown(testInfo: TestInformation, e: Throwable?) {
41         if (isTearDownDisabled) return
42         // May fail harmlessly if called before S
43         testInfo.exec("cmd device_config set_sync_disabled_for_tests $syncDisabledOriginalValue")
44     }
45 
readSyncDisabledOriginalValuenull46     private fun readSyncDisabledOriginalValue(testInfo: TestInformation): String {
47         return when (val reply = testInfo.exec("cmd device_config get_sync_disabled_for_tests")) {
48             "until_reboot", "persistent", "none" -> reply
49             // Reply does not match known modes, try legacy commands used on S and some T builds
50             else -> when (testInfo.exec("cmd device_config is_sync_disabled_for_tests")) {
51                 // The legacy command just said "true" for "until_reboot" or "persistent". There is
52                 // no way to know which one was used, so just reset to "until_reboot" to be
53                 // conservative.
54                 "true" -> "until_reboot"
55                 else -> "none"
56             }
57         }
58     }
59 }
60 
TestInformationnull61 fun TestInformation.exec(cmd: String) = this.device.executeShellCommand(cmd)
62