Bug 1257516 - Add a file-like class that sends writes to a callback. r=ted

This commit is contained in:
Mike Hommey 2016-03-25 12:13:37 +09:00
Родитель cf67fa8b15
Коммит e22a5082f7
2 изменённых файлов: 78 добавлений и 0 удалений

Просмотреть файл

@ -96,3 +96,36 @@ class ConfigureOutputHandler(logging.Handler):
raise raise
except: except:
self.handleError(record) self.handleError(record)
class LineIO(object):
'''File-like class that sends each line of the written data to a callback
(without carriage returns).
'''
def __init__(self, callback):
self._callback = callback
self._buf = ''
def write(self, buf):
lines = buf.splitlines()
if not lines:
return
if self._buf:
lines[0] = self._buf + lines[0]
self._buf = ''
if not buf.endswith('\n'):
self._buf = lines.pop()
for line in lines:
self._callback(line)
def close(self):
if self._buf:
self._callback(self._buf)
self._buf = ''
def __enter__(self):
return self
def __exit__(self, *args):
self.close()

Просмотреть файл

@ -16,6 +16,7 @@ from mozunit import main
from mozbuild.configure.util import ( from mozbuild.configure.util import (
ConfigureOutputHandler, ConfigureOutputHandler,
LineIO,
Version, Version,
) )
@ -176,6 +177,50 @@ class TestConfigureOutputHandler(unittest.TestCase):
os.remove(path) os.remove(path)
class TestLineIO(unittest.TestCase):
def test_lineio(self):
lines = []
l = LineIO(lambda l: lines.append(l))
l.write('a')
self.assertEqual(lines, [])
l.write('b')
self.assertEqual(lines, [])
l.write('\n')
self.assertEqual(lines, ['ab'])
l.write('cdef')
self.assertEqual(lines, ['ab'])
l.write('\n')
self.assertEqual(lines, ['ab', 'cdef'])
l.write('ghi\njklm')
self.assertEqual(lines, ['ab', 'cdef', 'ghi'])
l.write('nop\nqrst\nuv\n')
self.assertEqual(lines, ['ab', 'cdef', 'ghi', 'jklmnop', 'qrst', 'uv'])
l.write('wx\nyz')
self.assertEqual(lines, ['ab', 'cdef', 'ghi', 'jklmnop', 'qrst', 'uv',
'wx'])
l.close()
self.assertEqual(lines, ['ab', 'cdef', 'ghi', 'jklmnop', 'qrst', 'uv',
'wx', 'yz'])
def test_lineio_contextmanager(self):
lines = []
with LineIO(lambda l: lines.append(l)) as l:
l.write('a\nb\nc')
self.assertEqual(lines, ['a', 'b'])
self.assertEqual(lines, ['a', 'b', 'c'])
class TestVersion(unittest.TestCase): class TestVersion(unittest.TestCase):
def test_version_simple(self): def test_version_simple(self):
v = Version('1') v = Version('1')