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