1 /*
2  * Copyright (C) 2023 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 android.platform.test.flag.junit;
18 
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.function.Predicate;
22 
23 /** @hide */
24 public class FakeFeatureFlagsImpl extends CustomFeatureFlags {
25     private final Map<String, Boolean> mFlagMap = new HashMap<>();
26     private final FeatureFlags mDefaults;
27 
FakeFeatureFlagsImpl()28     public FakeFeatureFlagsImpl() {
29         this(null);
30     }
31 
FakeFeatureFlagsImpl(FeatureFlags defaults)32     public FakeFeatureFlagsImpl(FeatureFlags defaults) {
33         super(null);
34         mDefaults = defaults;
35         // Initialize the map with null values
36         for (String flagName : getFlagNames()) {
37             mFlagMap.put(flagName, null);
38         }
39     }
40 
41     @Override
getValue(String flagName, Predicate<FeatureFlags> getter)42     protected boolean getValue(String flagName, Predicate<FeatureFlags> getter) {
43         Boolean value = this.mFlagMap.get(flagName);
44         if (value != null) {
45             return value;
46         }
47         if (mDefaults != null) {
48             return getter.test(mDefaults);
49         }
50         throw new IllegalArgumentException(flagName + " is not set");
51     }
52 
setFlag(String flagName, boolean value)53     public void setFlag(String flagName, boolean value) {
54         if (!this.mFlagMap.containsKey(flagName)) {
55             throw new IllegalArgumentException("no such flag " + flagName);
56         }
57         this.mFlagMap.put(flagName, value);
58     }
59 
resetAll()60     public void resetAll() {
61         for (Map.Entry entry : mFlagMap.entrySet()) {
62             entry.setValue(null);
63         }
64     }
65 }
66