aconfig: add java codegen test mode
Add java codegen test mode. The test mode will generate Flags.java and
FeatureFlagsImpl.java differently.
* Flags.java will have getter and setter function to switch the
FeatureFlagsImpl. Flags.java will not initialize the instance
of FeatureFlagsImpl during initialization, thus it will force the
user to set up the flag values for the tests.
* FeatureFlagsImpl removes the dependency on DeviceConfig, and
allows the caller to set the values of flags.
Command changes
This change adds a new parameter `mode` to `create-java-lib` subcommand.
The default value of `mode` is production, which will generate files for
production usage, and keeps the same behavior as before.
The new `mode` test is added to trigger the test mode. The command is
aconfig create-java-lib --cache=<path_to_cache> --out=<out_path>
--mode=test
Test: atest aconfig.test
Bug: 288632682
Change-Id: I7566464eb762f3107142fe787f56b17f5be631b7
diff --git a/tools/aconfig/templates/FeatureFlagsImpl.java.template b/tools/aconfig/templates/FeatureFlagsImpl.java.template
index 2b031f1..dafd99e 100644
--- a/tools/aconfig/templates/FeatureFlagsImpl.java.template
+++ b/tools/aconfig/templates/FeatureFlagsImpl.java.template
@@ -1,20 +1,61 @@
package {package_name};
-{{ if is_read_write }}
+{{ -if is_test_mode }}
+import static java.util.stream.Collectors.toMap;
+
+import java.util.stream.Stream;
+import java.util.HashMap;
+{{ else}}
+{{ if is_read_write- }}
import android.provider.DeviceConfig;
+{{ -endif- }}
{{ endif }}
public final class FeatureFlagsImpl implements FeatureFlags \{
{{ for item in class_elements}}
@Override
public boolean {item.method_name}() \{
- {{ if item.is_read_write- }}
+ {{ -if not is_test_mode- }}
+ {{ if item.is_read_write }}
return DeviceConfig.getBoolean(
"{item.device_config_namespace}",
"{item.device_config_flag}",
{item.default_value}
);
- {{ -else- }}
+ {{ else }}
return {item.default_value};
+ {{ -endif- }}
+ {{ else }}
+ return getFlag(Flags.FLAG_{item.flag_name_constant_suffix});
{{ -endif }}
}
{{ endfor }}
-}
\ No newline at end of file
+
+ {{ if is_test_mode- }}
+ public void setFlag(String flagName, boolean value) \{
+ if (!this.mFlagMap.containsKey(flagName)) \{
+ throw new IllegalArgumentException("no such flag" + flagName);
+ }
+ this.mFlagMap.put(flagName, value);
+ }
+
+ private boolean getFlag(String flagName) \{
+ Boolean value = this.mFlagMap.get(flagName);
+ if (value == null) \{
+ throw new IllegalArgumentException(flagName + " is not set");
+ }
+ return value;
+ }
+
+ private HashMap<String, Boolean> mFlagMap = Stream.of(
+ {{-for item in class_elements}}
+ Flags.FLAG_{item.flag_name_constant_suffix}{{ if not @last }},{{ endif }}
+ {{ -endfor }}
+ )
+ .collect(
+ HashMap::new,
+ (map, elem) -> map.put(elem, null),
+ HashMap::putAll
+ );
+ {{ -endif }}
+}
+
+