desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the list of names of key flags for a module. Auxiliary for the testKeyFlags* methods. Args: module: A module object or a string module name. flag_values: A FlagValues object. Returns: A list of strings.'
def _GetNamesOfKeyFlags(self, module, flag_values):
return [f.name for f in flag_values._GetKeyFlagsForModule(module)]
'Set a flag to a given value and make sure we get expected message.'
def _CheckErrorMessage(self, flag_name, flag_value, expected_message_suffix):
try: self.flag_values.__setattr__(flag_name, flag_value) raise AssertionError('Bounds exception not raised!') except gflags.IllegalFlagValue as e: expected = ('flag --%(name)s=%(value)s: %(value)s is not %(suffix)s' % {'name': flag_name, 'value': flag_value, 'suff...
'Asserts that, when sorted, list1 and list2 are identical.'
def assertListEqual(self, list1, list2):
if hasattr(unittest.TestCase, 'assertListEqual'): unittest.TestCase.assertListEqual(self, Sorted(list1), Sorted(list2)) else: self.assertEqual(Sorted(list1), Sorted(list2))
'Constructor to create all validators. Args: checker: function to verify the constraint. Input of this method varies, see SimpleValidator and DictionaryValidator for a detailed description. message: string, error message to be shown to the user'
def __init__(self, checker, message):
self.checker = checker self.message = message Validator.validators_count += 1 self.insertion_index = Validator.validators_count
'Verify that constraint is satisfied. flags library calls this method to verify Validator\'s constraint. Args: flag_values: gflags.FlagValues, containing all flags Raises: Error: if constraint is not satisfied.'
def Verify(self, flag_values):
param = self._GetInputToCheckerFunction(flag_values) if (not self.checker(param)): raise Error(self.message)
'Return the names of the flags checked by this validator. Returns: [string], names of the flags'
def GetFlagsNames(self):
raise NotImplementedError('This method should be overloaded')
'Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues, containing all flags. Returns: Return type depends on the specific validator.'
def _GetInputToCheckerFunction(self, flag_values):
raise NotImplementedError('This method should be overloaded')
'Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. mess...
def __init__(self, flag_name, checker, message):
super(SimpleValidator, self).__init__(checker, message) self.flag_name = flag_name
'Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: value of the corresponding flag.'
def _GetInputToCheckerFunction(self, flag_values):
return flag_values[self.flag_name].value
'Constructor. Args: flag_names: [string], containing names of the flags used by checker. checker: function to verify the validator. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator ...
def __init__(self, flag_names, checker, message):
super(DictionaryValidator, self).__init__(checker, message) self.flag_names = flag_names
'Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: dictionary, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc).'
def _GetInputToCheckerFunction(self, flag_values):
return dict(([key, flag_values[key].value] for key in self.flag_names))
'Create the flag object. Args: flag_desc The command line forms this could take. (string) help The help text (string)'
def __init__(self, flag_desc, help):
self.desc = flag_desc self.help = help self.default = '' self.tips = ''
'Create object with executable. Args: executable Program to execute (string)'
def __init__(self, executable):
self.long_name = executable self.name = os.path.basename(executable) (self.short_name, self.ext) = os.path.splitext(self.name) self.executable = GetRealPath(executable) self.output = [] self.desc = [] self.modules = {} self.module_list = [] self.date = time.localtime(time.time())
'Run it and collect output. Returns: 1 (true) If everything went well. 0 (false) If there were problems.'
def Run(self):
if (not self.executable): logging.error(('Could not locate "%s"' % self.long_name)) return 0 finfo = os.stat(self.executable) self.date = time.localtime(finfo[stat.ST_MTIME]) logging.info(('Running: %s %s </dev/null 2>&1' % (self.executable, FLAGS.help_flag))) (c...
'Parse program output.'
def Parse(self):
(start_line, lang) = self.ParseDesc() if (start_line < 0): return if ('python' == lang): self.ParsePythonFlags(start_line) elif ('c' == lang): self.ParseCFlags(start_line) elif ('java' == lang): self.ParseJavaFlags(start_line)
'Parse the initial description. This could be Python or C++. Returns: (start_line, lang_type) start_line Line to start parsing flags on (int) lang_type Either \'python\' or \'c\' (-1, \'\') if the flags start could not be found'
def ParseDesc(self, start_line=0):
exec_mod_start = (self.executable + ':') after_blank = 0 start_line = 0 for start_line in range(start_line, len(self.output)): line = self.output[start_line].rstrip() if (('flags:' == line) and (len(self.output) > (start_line + 1)) and ('' == self.output[(start_line + 1)].rstrip())): ...
'Parse python/swig style flags.'
def ParsePythonFlags(self, start_line=0):
modname = None modlist = [] flag = None for line_num in range(start_line, len(self.output)): line = self.output[line_num].rstrip() if (not line): continue mobj = self.module_py_re.match(line) if mobj: modname = mobj.group(1) logging.deb...
'Parse C style flags.'
def ParseCFlags(self, start_line=0):
modname = None modlist = [] flag = None for line_num in range(start_line, len(self.output)): line = self.output[line_num].rstrip() if (not line): if flag: modlist.append(flag) flag = None continue mobj = self.module_c_re.mat...
'Parse Java style flags (com.google.common.flags).'
def ParseJavaFlags(self, start_line=0):
modname = 'Standard flags' self.module_list.append(modname) self.modules.setdefault(modname, []) modlist = self.modules[modname] flag = None for line_num in range(start_line, len(self.output)): line = self.output[line_num].rstrip() logging.vlog(2, ('Line: "%s"' % line)) ...
'Filter parsed data to create derived fields.'
def Filter(self):
if (not self.desc): self.short_desc = '' return for i in range(len(self.desc)): if (self.desc[i].find(self.executable) >= 0): self.desc[i] = self.desc[i].replace(self.executable, self.name) self.short_desc = self.desc[0] word_list = self.short_desc.split(' ') a...
'Create base object. Args: proginfo A ProgramInfo object directory Directory to write output into'
def __init__(self, proginfo, directory='.'):
self.info = proginfo self.dirname = directory
'Output all sections of the page.'
def Output(self):
self.Open() self.Header() self.Body() self.Footer()
'Create base object. Args: proginfo A ProgramInfo object directory Directory to write output into'
def __init__(self, proginfo, directory='.'):
GenerateDoc.__init__(self, proginfo, directory)
'Create a DuplicateFlagError. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we...
def __init__(self, flagname, flag_values, other_flag_values=None):
self.flagname = flagname first_module = flag_values.FindModuleDefiningFlag(flagname, default='<unknown>') if (other_flag_values is None): second_module = _GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag(flagname, default='<unknown>') msg = ("The f...
'Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning.'
def UseGnuGetOpt(self, use_gnu_getopt=True):
self.__dict__['__use_gnu_getopt'] = use_gnu_getopt
'Returns the dictionary of module_name -> list of defined flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects.'
def FlagsByModuleDict(self):
return self.__dict__['__flags_by_module']
'Returns the dictionary of module_id -> list of defined flags. Returns: A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects.'
def FlagsByModuleIdDict(self):
return self.__dict__['__flags_by_module_id']
'Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects.'
def KeyFlagsByModuleDict(self):
return self.__dict__['__key_flags_by_module']
'Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module.'
def _RegisterFlagByModule(self, module_name, flag):
flags_by_module = self.FlagsByModuleDict() flags_by_module.setdefault(module_name, []).append(flag)
'Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module.'
def _RegisterFlagByModuleId(self, module_id, flag):
flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag)
'Specifies that a flag is a key flag for a module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module.'
def _RegisterKeyFlagForModule(self, module_name, flag):
key_flags_by_module = self.KeyFlagsByModuleDict() key_flags = key_flags_by_module.setdefault(module_name, []) if (flag not in key_flags): key_flags.append(flag)
'Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object.'
def _GetFlagsDefinedByModule(self, module):
if (not isinstance(module, str)): module = module.__name__ return list(self.FlagsByModuleDict().get(module, []))
'Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object.'
def _GetKeyFlagsForModule(self, module):
if (not isinstance(module, str)): module = module.__name__ key_flags = self._GetFlagsDefinedByModule(module) for flag in self.KeyFlagsByModuleDict().get(module, []): if (flag not in key_flags): key_flags.append(flag) return key_flags
'Return the name of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we re...
def FindModuleDefiningFlag(self, flagname, default=None):
for (module, flags) in self.FlagsByModuleDict().iteritems(): for flag in flags: if ((flag.name == flagname) or (flag.short_name == flagname)): return module return default
'Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return...
def FindModuleIdDefiningFlag(self, flagname, default=None):
for (module_id, flags) in self.FlagsByModuleIdDict().iteritems(): for flag in flags: if ((flag.name == flagname) or (flag.short_name == flagname)): return module_id return default
'Appends flags registered in another FlagValues instance. Args: flag_values: registry to copy from'
def AppendFlagValues(self, flag_values):
for (flag_name, flag) in flag_values.FlagDict().iteritems(): if (flag_name == flag.name): try: self[flag_name] = flag except DuplicateFlagError: raise DuplicateFlagError(flag_name, self, other_flag_values=flag_values)
'Remove flags that were previously appended from another FlagValues. Args: flag_values: registry containing flags to remove.'
def RemoveFlagValues(self, flag_values):
for flag_name in flag_values.FlagDict(): self.__delattr__(flag_name)
'Registers a new flag variable.'
def __setitem__(self, name, flag):
fl = self.FlagDict() if (not isinstance(flag, Flag)): raise IllegalFlagValue(flag) if (not isinstance(name, type(''))): raise FlagsError('Flag name must be a string') if (len(name) == 0): raise FlagsError('Flag name cannot be empty') if ((name in fl...
'Retrieves the Flag object for the flag --name.'
def __getitem__(self, name):
return self.FlagDict()[name]
'Retrieves the \'value\' attribute of the flag --name.'
def __getattr__(self, name):
fl = self.FlagDict() if (name not in fl): raise AttributeError(name) return fl[name].value
'Sets the \'value\' attribute of the flag --name.'
def __setattr__(self, name, value):
fl = self.FlagDict() fl[name].value = value self._AssertValidators(fl[name].validators) return value
'Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator...
def _AssertValidators(self, validators):
for validator in sorted(validators, key=(lambda validator: validator.insertion_index)): try: validator.Verify(self) except gflags_validators.Error as e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue(('%s: %s' % (message, str(e))))
'Checks whether a Flag object is registered under some name. Note: this is non trivial: in addition to its normal name, a flag may have a short name too. In self.FlagDict(), both the normal and the short name are mapped to the same flag object. E.g., calling only "del FLAGS.short_name" is not unregistering the corres...
def _FlagIsRegistered(self, flag_obj):
flag_dict = self.FlagDict() name = flag_obj.name if (flag_dict.get(name, None) == flag_obj): return True short_name = flag_obj.short_name if ((short_name is not None) and (flag_dict.get(short_name, None) == flag_obj)): return True return False
'Deletes a previously-defined flag from a flag object. This method makes sure we can delete a flag by using del flag_values_object.<flag_name> E.g., gflags.DEFINE_integer(\'foo\', 1, \'Integer flag.\') del gflags.FLAGS.foo Args: flag_name: A string, the name of the flag to be deleted. Raises: AttributeError: When there...
def __delattr__(self, flag_name):
fl = self.FlagDict() if (flag_name not in fl): raise AttributeError(flag_name) flag_obj = fl[flag_name] del fl[flag_name] if (not self._FlagIsRegistered(flag_obj)): self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.Fl...
'Removes a flag object from a module -> list of flags dictionary. Args: flags_by_module_dict: A dictionary that maps module names to lists of flags. flag_obj: A flag object.'
def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj):
for (unused_module, flags_in_module) in flags_by_module_dict.iteritems(): while (flag_obj in flags_in_module): flags_in_module.remove(flag_obj)
'Changes the default value of the named flag object.'
def SetDefault(self, name, value):
fl = self.FlagDict() if (name not in fl): raise AttributeError(name) fl[name].SetDefault(value) self._AssertValidators(fl[name].validators)
'Returns True if name is a value (flag) in the dict.'
def __contains__(self, name):
return (name in self.FlagDict())
'Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Flags are parsed using the GNU Program Argument Syntax Conventions, using getopt: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt Args: argv: argument list. Can be of any type that may be c...
def __call__(self, argv):
argv = list(argv) shortopts = '' longopts = [] fl = self.FlagDict() argv = (argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False)) original_argv = list(argv) shortest_matches = None for (name, flag) in fl.items(): if (not flag.boolean): continue if (sh...
'Resets the values to the point before FLAGS(argv) was called.'
def Reset(self):
for f in self.FlagDict().values(): f.Unparse()
'Returns: a list of the names and short names of all registered flags.'
def RegisteredFlags(self):
return list(self.FlagDict())
'Returns: a dictionary that maps flag names to flag values.'
def FlagValuesDict(self):
flag_values = {} for flag_name in self.RegisteredFlags(): flag = self.FlagDict()[flag_name] flag_values[flag_name] = flag.value return flag_values
'Generates a help string for all known flags.'
def __str__(self):
return self.GetHelp()
'Generates a help string for all known flags.'
def GetHelp(self, prefix=''):
helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) main_module = _GetMainModule() if (main_module in modules): modules.remove(main_module) modules = ([main_module] + modules) for module in mod...
'Generates a help string for a given module.'
def __RenderModuleFlags(self, module, flags, output_lines, prefix=''):
if (not isinstance(module, str)): module = module.__name__ output_lines.append(('\n%s%s:' % (prefix, module))) self.__RenderFlagList(flags, output_lines, (prefix + ' '))
'Generates a help string for a given module.'
def __RenderOurModuleFlags(self, module, output_lines, prefix=''):
flags = self._GetFlagsDefinedByModule(module) if flags: self.__RenderModuleFlags(module, flags, output_lines, prefix)
'Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line.'
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=''):
key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
'Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module.'
def ModuleHelp(self, module):
helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist)
'Describe the key flags of the main module. Returns: string describing the key flags of a module.'
def MainModuleHelp(self):
return self.ModuleHelp(_GetMainModule())
'Returns the value of a flag (if not None) or a default value. Args: name: A string, the name of a flag. default: Default value to use if the flag value is None.'
def get(self, name, default):
value = self.__getattr__(name) if (value is not None): return value else: return default
'Returns: dictionary; maps flag names to their shortest unique prefix.'
def ShortestUniquePrefixes(self, fl):
sorted_flags = [] for (name, flag) in fl.items(): sorted_flags.append(name) if flag.boolean: sorted_flags.append(('no%s' % name)) sorted_flags.sort() shortest_matches = {} prev_idx = 0 for flag_idx in range(len(sorted_flags)): curr = sorted_flags[flag_idx] ...
'Checks whether flag_string contain a --flagfile=<foo> directive.'
def __IsFlagFileDirective(self, flag_string):
if isinstance(flag_string, type('')): if flag_string.startswith('--flagfile='): return 1 elif (flag_string == '--flagfile'): return 1 elif flag_string.startswith('-flagfile='): return 1 elif (flag_string == '-flagfile'): return 1 ...
'Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn\'t be hitting this function, as they are dealt with in the level above this function.'
def ExtractFilename(self, flagfile_str):
if flagfile_str.startswith('--flagfile='): return os.path.expanduser(flagfile_str[len('--flagfile='):].strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser(flagfile_str[len('-flagfile='):].strip()) else: raise FlagsError(('Hit illegal --flagfile typ...
'Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --f...
def __GetFlagFileLines(self, filename, parsed_file_list):
line_list = [] flag_line_list = [] try: file_obj = open(filename, 'r') except IOError as e_msg: raise CantOpenFlagFileError(('ERROR:: Unable to open flagfile: %s' % e_msg)) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) ...
'Processes command line args, but also allow args to be read from file. Args: argv: A list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu: If False, --flagfile parsing o...
def ReadFlagsFromFiles(self, argv, force_gnu=True):
parsed_file_list = [] rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): if ((current_arg == '--flagfile') or (current_arg == '-flagfile')): if...
'Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags'
def FlagsIntoString(self):
s = '' for flag in self.FlagDict().values(): if (flag.value is not None): s += (flag.Serialize() + '\n') return s
'Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags'
def AppendFlagsIntoFile(self, filename):
out_file = open(filename, 'a') out_file.write(self.FlagsIntoString()) out_file.close()
'Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from http://code.google.com/p/google-gflags We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. ...
def WriteHelpInXMLFormat(self, outfile=None):
outfile = (outfile or sys.stdout) outfile.write('<?xml version="1.0"?>\n') outfile.write('<AllFlags>\n') indent = ' ' _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), indent) usage_doc = sys.modules['__main__'].__doc__ if (not usage_doc): usage_doc ...
'Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag.'
def AddValidator(self, validator):
for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator)
'Changes the default value (and current value too) for this Flag.'
def SetDefault(self, value):
if ((value is None) and self.allow_override): raise DuplicateFlagCannotPropagateNoneToSwig(self.name) self.default = value self.Unparse() self.default_as_str = self.__GetParsedValueAsString(self.value)
'Returns: a string that describes the type of this Flag.'
def Type(self):
return self.parser.Type()
'Writes common info about this flag, in XML format. This is information that is relevant to all flags (e.g., name, meaning, etc.). If you defined a flag that has some other pieces of info, then please override _WriteCustomInfoInXMLFormat. Please do NOT override this method. Args: outfile: File object we write to. modu...
def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''):
outfile.write((indent + '<flag>\n')) inner_indent = (indent + ' ') if is_key: _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) if self.sho...
'Writes extra info about this flag, in XML format. "Extra" means "not already printed by WriteInfoInXMLFormat above." Args: outfile: File object we write to. indent: A string that is prepended to each generated line.'
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
self.parser.WriteCustomInfoInXMLFormat(outfile, indent)
'Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or t...
def __call__(mcs, *args, **kwargs):
if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = ((mcs,) + tuple(args)) try: return instances[key] except KeyError: return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: ...
'Default implementation: always returns its argument unmodified.'
def Parse(self, argument):
return argument
'Converts the argument to a boolean; raise ValueError on errors.'
def Convert(self, argument):
if (type(argument) == str): if (argument.lower() in ['true', 't', '1']): return True elif (argument.lower() in ['false', 'f', '0']): return False bool_argument = bool(argument) if (argument == bool_argument): return bool_argument raise ValueError('Non-bool...
'Default implementation: always returns its argument unmodified.'
def Convert(self, argument):
return argument
'Converts argument to a float; raises ValueError on errors.'
def Convert(self, argument):
return float(argument)
'Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item.'
def Parse(self, arguments):
if (not isinstance(arguments, list)): arguments = [arguments] if self.present: values = self.value else: values = [] for item in arguments: Flag.Parse(self, item) values.append(self.value) self.value = values
'Overriding a method on a super class and then calling that method on the super class should not trigger infinite recursion. See #17011.'
def test_max_recursion_error(self):
try: super(ClassDecoratedTestCase, self).test_max_recursion_error() except RuntimeError as e: self.fail()
'ALLOWED_INCLUDE_ROOTS is not allowed to be incorrectly set to a string rather than a tuple.'
def test_allowed_include_roots_string(self):
self.assertRaises(ValueError, setattr, settings, 'ALLOWED_INCLUDE_ROOTS', '/var/www/ssi/')
'If blank, no DeprecationWarning error will be raised, even though it doesn\'t end in a slash.'
def test_blank(self):
self.settings_module.MEDIA_URL = '' self.assertEqual('', self.settings_module.MEDIA_URL)
'MEDIA_URL works if you end in a slash.'
def test_end_slash(self):
self.settings_module.MEDIA_URL = '/foo/' self.assertEqual('/foo/', self.settings_module.MEDIA_URL) self.settings_module.MEDIA_URL = 'http://media.foo.com/' self.assertEqual('http://media.foo.com/', self.settings_module.MEDIA_URL)
'MEDIA_URL raises an DeprecationWarning error if it doesn\'t end in a slash.'
def test_no_end_slash(self):
import warnings warnings.filterwarnings('error', 'If set, MEDIA_URL must end with a slash', DeprecationWarning) def setattr_settings(settings_module, attr, value): setattr(settings_module, attr, value) self.assertRaises(DeprecationWarning, setattr_settings, self.settings_mod...
'If a MEDIA_URL ends in more than one slash, presume they know what they\'re doing.'
def test_double_slash(self):
self.settings_module.MEDIA_URL = '/stupid//' self.assertEqual('/stupid//', self.settings_module.MEDIA_URL) self.settings_module.MEDIA_URL = 'http://media.foo.com/stupid//' self.assertEqual('http://media.foo.com/stupid//', self.settings_module.MEDIA_URL)
'If the environment variable is set, do not ignore it. However, the kwarg original_settings_path takes precedence. This tests both plus the default (neither set).'
def test_env_var_used(self):
from django.core.management import setup_environ original_module = os.environ.get('DJANGO_SETTINGS_MODULE', 'the default') user_override = 'custom.settings' orig_path = 'original.path' setup_environ(global_settings) self.assertEqual(os.environ.get('DJANGO_SETTINGS_MODULE'), original_module) ...
'Cookie will expire when an near expiration time is provided'
def test_near_expiration(self):
response = HttpResponse() expires = (datetime.utcnow() + timedelta(seconds=10)) time.sleep(0.001) response.set_cookie('datetime', expires=expires) datetime_cookie = response.cookies['datetime'] self.assertEqual(datetime_cookie['max-age'], 10)
'Cookie accepts an aware datetime as expiration time'
def test_aware_expiration(self):
response = HttpResponse() expires = (datetime.utcnow() + timedelta(seconds=10)).replace(tzinfo=utc) time.sleep(0.001) response.set_cookie('datetime', expires=expires) datetime_cookie = response.cookies['datetime'] self.assertEqual(datetime_cookie['max-age'], 10)
'Cookie will expire when an distant expiration time is provided'
def test_far_expiration(self):
response = HttpResponse() response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6)) datetime_cookie = response.cookies['datetime'] self.assertEqual(datetime_cookie['expires'], 'Sat, 01-Jan-2028 04:05:06 GMT')
'Cookie will expire if max_age is provided'
def test_max_age_expiration(self):
response = HttpResponse() response.set_cookie('max_age', max_age=10) max_age_cookie = response.cookies['max_age'] self.assertEqual(max_age_cookie['max-age'], 10) self.assertEqual(max_age_cookie['expires'], cookie_date((time.time() + 10)))
'Reading from request is allowed after accessing request contents as POST or body.'
def test_read_after_value(self):
payload = 'name=value' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)}) self.assertEqual(request.POST, {u'name': [u'value']}) self.assertEqual(request.body, 'name=value') self.assertEqual(request.read(), 'name=value')
'Construction of POST or body is not allowed after reading from request.'
def test_value_after_read(self):
payload = 'name=value' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)}) self.assertEqual(request.read(2), 'na') self.assertRaises(Exception, (lambda : request.body)) self.assertEqual(request.POST, {})
'Reading body after parsing multipart is not allowed'
def test_body_after_POST_multipart(self):
payload = '\r\n'.join(['--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--']) request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)}) self.assertE...
'Multipart POST requests with Content-Length >= 0 are valid and need to be handled.'
def test_POST_multipart_with_content_length_zero(self):
payload = '\r\n'.join(['--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--']) request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': 0, 'wsgi.input': StringIO(payload)}) self.assertEqual(reques...
'POST should be populated even if body is read first'
def test_POST_after_body_read(self):
payload = 'name=value' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)}) raw_data = request.body self.assertEqual(request.POST, {u'name': [u'value']})
'POST should be populated even if body is read first, and then the stream is read second.'
def test_POST_after_body_read_and_stream_read(self):
payload = 'name=value' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)}) raw_data = request.body self.assertEqual(request.read(1), u'n') self.assertEqual(request.POST, {u'name': [u'value']})
'POST should be populated even if body is read first, and then the stream is read second. Using multipart/form-data instead of urlencoded.'
def test_POST_after_body_read_and_stream_read_multipart(self):
payload = '\r\n'.join(['--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--']) request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)}) raw_data = r...
'HttpRequest.raw_post_body should be the same as HttpRequest.body'
def test_raw_post_data_returns_body(self):
payload = 'Hello There!' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'wsgi.input': StringIO(payload)}) warnings_state = get_warnings_state() warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.http') try: self.assertEqual(requ...
'If wsgi.input.read() raises an exception while trying to read() the POST, the exception should be identifiable (not a generic IOError).'
def test_POST_connection_error(self):
class ExplodingStringIO(StringIO, ): def read(self, len=0): raise IOError('kaboom!') payload = 'name=value' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'wsgi.input': ExplodingStringIO(payload)}) with self.assertRaises(UnreadablePostError): ...
'signature() method should generate a signature'
def test_signature(self):
signer = signing.Signer('predictable-secret') signer2 = signing.Signer('predictable-secret2') for s in ('hello', '3098247:529:087:', u'\u2019'.encode('utf-8')): self.assertEqual(signer.signature(s), signing.base64_hmac((signer.salt + 'signer'), s, 'predictable-secret')) self.assertNotEqual(s...
'signature(value, salt=...) should work'
def test_signature_with_salt(self):
signer = signing.Signer('predictable-secret', salt='extra-salt') self.assertEqual(signer.signature('hello'), signing.base64_hmac(('extra-salt' + 'signer'), 'hello', 'predictable-secret')) self.assertNotEqual(signing.Signer('predictable-secret', salt='one').signature('hello'), signing.Signer('predictable-sec...