1 /*
2  * Copyright (C) 2019 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 package com.android.cts.net.hostside;
17 
18 import static com.android.cts.net.hostside.NetworkPolicyTestUtils.resetMeteredNetwork;
19 import static com.android.cts.net.hostside.NetworkPolicyTestUtils.setupMeteredNetwork;
20 import static com.android.cts.net.hostside.Property.METERED_NETWORK;
21 import static com.android.cts.net.hostside.Property.NON_METERED_NETWORK;
22 
23 import android.util.ArraySet;
24 import android.util.Pair;
25 
26 import com.android.compatibility.common.util.BeforeAfterRule;
27 
28 import org.junit.runner.Description;
29 import org.junit.runners.model.Statement;
30 
31 public class MeterednessConfigurationRule extends BeforeAfterRule {
32     private Pair<String, Boolean> mSsidAndInitialMeteredness;
33 
34     @Override
onBefore(Statement base, Description description)35     public void onBefore(Statement base, Description description) throws Throwable {
36         final ArraySet<Property> requiredProperties
37                 = RequiredPropertiesRule.getRequiredProperties();
38         if (requiredProperties.contains(METERED_NETWORK)) {
39             configureNetworkMeteredness(true);
40         } else if (requiredProperties.contains(NON_METERED_NETWORK)) {
41             configureNetworkMeteredness(false);
42         }
43     }
44 
45     @Override
onAfter(Statement base, Description description)46     public void onAfter(Statement base, Description description) throws Throwable {
47         resetNetworkMeteredness();
48     }
49 
configureNetworkMeteredness(boolean metered)50     public void configureNetworkMeteredness(boolean metered) throws Exception {
51         mSsidAndInitialMeteredness = setupMeteredNetwork(metered);
52     }
53 
resetNetworkMeteredness()54     public void resetNetworkMeteredness() throws Exception {
55         if (mSsidAndInitialMeteredness != null) {
56             resetMeteredNetwork(mSsidAndInitialMeteredness.first,
57                     mSsidAndInitialMeteredness.second);
58         }
59     }
60 }
61