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 #include <string>
18 #include <utility>
19 #include <functional>
20 #include <vector>
21 
22 #include <flag_checker.h>
23 #include <gtest/gtest.h>
24 #include <android-base/strings.h>
25 #include <android-base/stringprintf.h>
26 #include <android-base/properties.h>
27 
28 #define SYSTEM_PROPERTY_PREFIX "persist.device_config."
29 
30 namespace android::test::flag {
31 
GetFlagsNotMetRequirements(const std::vector<std::pair<bool,std::vector<p_flag>>> flag_conditions)32 std::vector<std::pair<bool, std::string>> GetFlagsNotMetRequirements(
33   const std::vector<std::pair<bool, std::vector<p_flag>>> flag_conditions) {
34   std::vector<std::pair<bool, std::string>> unsatisfied_flags;
35   for (const std::pair<bool, std::vector<p_flag>> flag_condition : flag_conditions) {
36     bool expected_condition = flag_condition.first;
37     for (const p_flag feature_flag : flag_condition.second) {
38       if (!CheckFlagCondition(expected_condition, feature_flag)) {
39         // Records the feature flag if it doesn't meet the expected condition.
40         unsatisfied_flags.push_back({expected_condition, feature_flag.second});
41       }
42     }
43   }
44   return unsatisfied_flags;
45 }
46 
CheckFlagCondition(bool expected_condition,const p_flag feature_flag)47 bool CheckFlagCondition(bool expected_condition, const p_flag feature_flag) {
48   // Checks the aconfig flag.
49   if (feature_flag.first) {
50     return feature_flag.first() == expected_condition;
51   }
52   // Checks the legacy flag.
53   std::vector<std::string> flag_args = android::base::Split(feature_flag.second, ",");
54   if (flag_args.size() != 3) {
55     return false;
56   }
57   std::string package_name = android::base::StringReplace(flag_args[1], "::", ".", true);
58   std::string full_flag_name = android::base::StringPrintf(
59     "%s.%s.%s",
60     android::base::Trim(flag_args[0]).c_str(),
61     android::base::Trim(package_name).c_str(),
62     android::base::Trim(flag_args[2]).c_str()
63   );
64   return android::base::GetProperty(SYSTEM_PROPERTY_PREFIX + full_flag_name, "") ==
65     (expected_condition ? "true":"false");
66 }
67 
68 }  // namespace android::test::flag