def test_gt(self): """ verify that instances of UnknownTextSource are not ordered """ other_src = UnknownTextSource() self.assertFalse(self.src < other_src) self.assertFalse(other_src < self.src)
def test_eq(self): """ verify instances of UnknownTextSource are all equal to each other but not equal to any other object """ other_src = UnknownTextSource() self.assertTrue(self.src == other_src) self.assertFalse(self.src == "???")
def test_just_file(self): """ verify how Origin.just_file() works as expected """ origin1 = Origin(UnknownTextSource(), 1, 2) origin2 = origin1.just_file() self.assertEqual(origin2.line_start, None) self.assertEqual(origin2.line_end, None) self.assertIs(origin2.source, origin1.source)
def test_with_offset(self): """ verify how Origin.with_offset() works as expected """ origin1 = Origin(UnknownTextSource(), 1, 2) origin2 = origin1.with_offset(10) self.assertEqual(origin2.line_start, 11) self.assertEqual(origin2.line_end, 12) self.assertIs(origin2.source, origin1.source)
def test_from_string(self): """ verify that WhiteList.from_string() works """ whitelist = WhiteList.from_string("\n".join(self._content)) # verify that the patterns are okay self.assertEqual(repr(whitelist.qualifier_list[0]), "RegExpJobQualifier('^foo$', inclusive=True)") # verify that whitelist name is the empty default self.assertEqual(whitelist.name, None) # verify that the origin got set to the default constructed value self.assertEqual(whitelist.origin, Origin(UnknownTextSource(), 1, 3))
def test_origin_from_stream_is_Unknown(self): """ verify that gen_rfc822_records() uses origin instances with source equal to UnknownTextSource, when no explicit source is provided and the stream has no name to infer a FileTextSource() from. """ expected_origin = Origin(UnknownTextSource(), 1, 1) with StringIO("key:value") as stream: records = type(self).loader(stream) self.assertEqual(len(records), 1) self.assertEqual(records[0].data, {'key': 'value'}) self.assertEqual(records[0].origin, expected_origin)
def test_relative_to(self): """ verify how Origin.relative_to() works in various situations """ # if the source does not have relative_to method, nothing is changed origin = Origin(UnknownTextSource(), 1, 2) self.assertIs(origin.relative_to("/some/path"), origin) # otherwise the source is replaced and a new origin is returned self.assertEqual( Origin( FileTextSource("/some/path/file.txt"), 1, 2 ).relative_to("/some/path"), Origin(FileTextSource("file.txt"), 1, 2))
def from_string(cls, text, *, filename=None, name=None, origin=None, implicit_namespace=None): """ Load and initialize the WhiteList object from the specified string. :param text: full text of the whitelist :param filename: (optional, keyword-only) filename from which text was read from. This simulates a call to :meth:`from_file()` which properly computes the name and origin of the whitelist. :param name: (optional) name of the whitelist, only used if filename is not specified. :param origin: (optional) origin of the whitelist, only used if a filename is not specified. If omitted a default origin value will be constructed out of UnknownTextSource instance :param implicit_namespace: (optional) implicit namespace for jobs that are using partial identifiers (all jobs) :returns: a fresh WhiteList object The optional filename or a pair of name and origin arguments may be provided in order to have additional meta-data. This is typically needed when the :meth:`from_file()` method cannot be used as the caller already has the full text of the intended file available. """ _logger.debug("Loaded whitelist from %r", filename) pattern_list, max_lineno = cls._parse_patterns(text) # generate name and origin if filename is provided if filename is not None: name = WhiteList.name_from_filename(filename) origin = Origin(FileTextSource(filename), 1, max_lineno) else: # otherwise generate origin if it's not specified if origin is None: origin = Origin(UnknownTextSource(), 1, max_lineno) return cls(pattern_list, name, origin, implicit_namespace)
def gen_rfc822_records(stream, data_cls=dict, source=None): """ Load a sequence of rfc822-like records from a text stream. :param stream: A file-like object from which to load the rfc822 data :param data_cls: The class of the dictionary-like type to hold the results. This is mainly there so that callers may pass collections.OrderedDict. :param source: A :class:`plainbox.abc.ITextSource` subclass instance that describes where stream data is coming from. If None, it will be inferred from the stream (if possible). Specialized callers should provider a custom source object to allow developers to accurately keep track of where (possibly problematic) RFC822 data is coming from. If this is None and inferring fails then all of the loaded records will have a None origin. Each record consists of any number of key-value pairs. Subsequent records are separated by one blank line. A record key may have a multi-line value if the line starts with whitespace character. Returns a list of subsequent values as instances RFC822Record class. If the optional data_cls argument is collections.OrderedDict then the values retain their original ordering. """ record = None key = None value_list = None origin = None field_offset_map = None # If the source was not provided then try constructing a FileTextSource # from the name of the stream. If that fails, keep using None. if source is None: try: source = FileTextSource(stream.name) except AttributeError: source = UnknownTextSource() def _syntax_error(msg): """ Report a syntax error in the current line """ try: filename = stream.name except AttributeError: filename = None return RFC822SyntaxError(filename, lineno, msg) def _new_record(): """ Reset local state to track new record """ nonlocal key nonlocal value_list nonlocal record nonlocal origin nonlocal field_offset_map key = None value_list = None if source is not None: origin = Origin(source, None, None) field_offset_map = {} record = RFC822Record(data_cls(), origin, data_cls(), field_offset_map) def _commit_key_value_if_needed(): """ Finalize the most recently seen key: value pair """ nonlocal key if key is not None: raw_value = ''.join(value_list) normalized_value = normalize_rfc822_value(raw_value) record.raw_data[key] = raw_value record.data[key] = normalized_value logger.debug(_("Committed key/value %r=%r"), key, normalized_value) key = None def _set_start_lineno_if_needed(): """ Remember the line number of the record start unless already set """ if origin and record.origin.line_start is None: record.origin.line_start = lineno def _update_end_lineno(): """ Update the line number of the record tail """ if origin: record.origin.line_end = lineno # Start with an empty record _new_record() # Support simple text strings if isinstance(stream, str): # keepends=True (python3.2 has no keyword for this) stream = iter(stream.splitlines(True)) # Iterate over subsequent lines of the stream for lineno, line in enumerate(stream, start=1): logger.debug(_("Looking at line %d:%r"), lineno, line) # Treat # as comments if line.startswith("#"): pass # Treat empty lines as record separators elif line.strip() == "": # Commit the current record so that the multi-line value of the # last key, if any, is saved as a string _commit_key_value_if_needed() # If data is non-empty, yield the record, this allows us to safely # use newlines for formatting if record.data: logger.debug(_("yielding record: %r"), record) yield record # Reset local state so that we can build a new record _new_record() # Treat lines staring with whitespace as multi-line continuation of the # most recently seen key-value elif line.startswith(" "): if key is None: # If we have not seen any keys yet then this is a syntax error raise _syntax_error(_("Unexpected multi-line value")) # Strip the initial space. This matches the behavior of xgettext # scanning our job definitions with multi-line values. line = line[1:] # Append the current line to the list of values of the most recent # key. This prevents quadratic complexity of string concatenation value_list.append(line) # Update the end line location of this record _update_end_lineno() # Treat lines with a colon as new key-value pairs elif ":" in line: # Since this is actual data let's try to remember where it came # from. This may be a no-operation if there were any preceding # key-value pairs. _set_start_lineno_if_needed() # Since we have a new, key-value pair we need to commit any # previous key that we may have (regardless of multi-line or # single-line values). _commit_key_value_if_needed() # Parse the line by splitting on the colon, getting rid of # all surrounding whitespace from the key and getting rid of the # leading whitespace from the value. key, value = line.split(":", 1) key = key.strip() value = value.lstrip() # Check if the key already exist in this message if key in record.data: raise _syntax_error( _("Job has a duplicate key {!r} " "with old value {!r} and new value {!r}").format( key, record.raw_data[key], value)) if value.strip() != "": # Construct initial value list out of the (only) value that we # have so far. Additional multi-line values will just append to # value_list value_list = [value] # Store the offset of the filed in the offset map field_offset_map[key] = lineno - origin.line_start else: # The initial line may be empty, in that case the spaces and # newlines there are discarded value_list = [] # Store the offset of the filed in the offset map # The +1 is for the fact that value is empty (or just # whitespace) and that is stripped away in the normalized data # part of the RFC822 record. To keep line tracking accurate # we just assume that the field actually starts on # the following line. field_offset_map[key] = lineno - origin.line_start + 1 # Update the end-line location _update_end_lineno() # Treat all other lines as syntax errors else: raise _syntax_error( _("Unexpected non-empty line: {!r}").format(line)) # Make sure to commit the last key from the record _commit_key_value_if_needed() # Once we've seen the whole file return the last record, if any if record.data: logger.debug(_("yielding record: %r"), record) yield record
def setUp(self): self.src = UnknownTextSource()