absl.testing.flagsaver module
Decorator and context manager for saving and restoring flag values.
There are many ways to save and restore. Always use the most convenient method for a given use case.
Here are examples of each method. They all call do_stuff() while FLAGS.someflag is temporarily set to ‘foo’.
from absl.testing import flagsaver
# Use a decorator which can optionally override flags via arguments. @flagsaver.flagsaver(someflag=’foo’) def some_func():
do_stuff()
# Use a decorator which can optionally override flags with flagholders. @flagsaver.flagsaver((module.FOO_FLAG, ‘foo’), (other_mod.BAR_FLAG, 23)) def some_func():
do_stuff()
# Use a decorator which does not override flags itself. @flagsaver.flagsaver def some_func():
FLAGS.someflag = ‘foo’ do_stuff()
# Use a context manager which can optionally override flags via arguments. with flagsaver.flagsaver(someflag=’foo’):
do_stuff()
# Save and restore the flag values yourself. saved_flag_values = flagsaver.save_flag_values() try:
FLAGS.someflag = ‘foo’ do_stuff()
- finally:
flagsaver.restore_flag_values(saved_flag_values)
We save and restore a shallow copy of each Flag object’s __dict__ attribute. This preserves all attributes of the flag, such as whether or not it was overridden from its default value.
WARNING: Currently a flag that is saved and then deleted cannot be restored. An exception will be raised. However if you add a flag after saving flag values, and then restore flag values, the added flag will be deleted with no errors.
- absl.testing.flagsaver.flagsaver(*args, **kwargs)[source]
The main flagsaver interface. See module doc for usage.
- absl.testing.flagsaver.restore_flag_values(saved_flag_values, flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
Restores flag values based on the dictionary of flag values.
- Parameters
saved_flag_values – {‘flag_name’: value_dict, …}
flag_values – FlagValues, the FlagValues instance from which the flag will be restored. This should almost never need to be overridden.
- absl.testing.flagsaver.save_flag_values(flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
Returns copy of flag values as a dict.
- Parameters
flag_values – FlagValues, the FlagValues instance with which the flag will be saved. This should almost never need to be overridden.
- Returns
Dictionary mapping keys to values. Keys are flag names, values are corresponding __dict__ members. E.g. {‘key’: value_dict, …}.