def _write_content(self, suffix): try: fn = tempfile.mkstemp(suffix)[1] with tools.open_archive(fn, 'wb') as f: f.write(self.original_content) with tools.open_archive(fn, 'rb') as f: self.assertEqual(f.read(), self.original_content) with open(fn, 'rb') as f: return f.read() finally: os.remove(fn)
def _write_content(self, suffix): try: fh, fn = tempfile.mkstemp(suffix) with tools.open_archive(fn, "wb") as f: f.write(self.original_content) with tools.open_archive(fn, "rb") as f: self.assertEqual(f.read(), self.original_content) with open(fn, "rb") as f: return f.read() finally: os.close(fh) os.remove(fn)
def test_invalid_modes(self): """Test various invalid mode configurations.""" with self.assertRaisesRegex(ValueError, 'Invalid mode: "ra"'): tools.open_archive('/dev/null', 'ra') # two modes besides with self.assertRaisesRegex(ValueError, 'Invalid mode: "rt"'): tools.open_archive('/dev/null', 'rt') # text mode with self.assertRaisesRegex(ValueError, 'Invalid mode: "br"'): tools.open_archive('/dev/null', 'br') # binary at front with self.assertRaisesRegex( ValueError, 'Magic number detection only when reading'): tools.open_archive( '/dev/null', # writing without extension 'wb', False)
def parse(self): """Generator using ElementTree iterparse function.""" with open_archive(self.filename) as source: context = iterparse(source, events=('start', 'end', 'start-ns')) self.root = None for event, elem in context: if event == 'start-ns' and elem[0] == '': self.uri = elem[1] continue if event == 'start' and self.root is None: self.root = elem continue yield from self._parse(event, elem)
def parse(self): """Generator using cElementTree iterparse function.""" with open_archive(self.filename) as source: # iterparse's event must be a str but they are unicode with # unicode_literals in Python 2 context = iterparse(source, events=(str('start'), str('end'), str('start-ns'))) self.root = None for event, elem in context: if event == "start-ns" and elem[0] == "": self.uri = elem[1] continue if event == "start" and self.root is None: self.root = elem continue for rev in self._parse(event, elem): yield rev
def _get_content(self, *args, **kwargs): """Use open_archive and return content using a with-statement.""" with tools.open_archive(*args, **kwargs) as f: return f.read().replace(b'\r\n', b'\n')
def test_write_archive_7z(self): """Test writing an archive as a 7z archive.""" with self.assertRaisesRegex(NotImplementedError, 'It is not possible to write a 7z file.'): tools.open_archive('/dev/null.7z', mode='wb')
def test_binary_mode(self): """Test that it uses binary mode.""" with tools.open_archive(self.base_file, 'r') as f: self.assertEqual(f.mode, 'rb') self.assertIsInstance(f.read(), bytes)
def _get_content(self, *args, **kwargs): """Use open_archive and return content using a with-statement.""" with tools.open_archive(*args, **kwargs) as f: return f.read()