Skip to content

Commit f90af55

Browse files
committed
Merge pull request #31 from mogproject/topic-unittest-#30
add withBytesOutput method to TestCase closes #30
2 parents a37bd2f + e65dc87 commit f90af55

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/mog_commons/unittest.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,15 +113,15 @@ def assertRaisesMessage(self, expected_exception, expected_message, callable_obj
113113
self.assertEqual(msg, expected_message)
114114

115115
@contextmanager
116-
def withOutput(self):
116+
def withOutput(self, buffer_type=StringBuffer):
117117
"""
118118
Capture and suppress stdout and stderr.
119119
example:
120120
with self.withOutput() as (out, err):
121121
(do main logic)
122122
(verify out.getvalue() or err.getvalue())
123123
"""
124-
new_out, new_err = StringBuffer(), StringBuffer()
124+
new_out, new_err = buffer_type(), buffer_type()
125125
old_out, old_err = sys.stdout, sys.stderr
126126

127127
try:
@@ -130,6 +130,18 @@ def withOutput(self):
130130
finally:
131131
sys.stdout, sys.stderr = old_out, old_err
132132

133+
@contextmanager
134+
def withBytesOutput(self):
135+
"""
136+
Capture and suppress stdout and stderr. The value is represented as bytes.
137+
example:
138+
with self.withBytesOutput() as (out, err):
139+
(do main logic)
140+
(verify out.getvalue() or err.getvalue())
141+
"""
142+
with self.withOutput(six.BytesIO) as (out, err):
143+
yield out, err
144+
133145
@contextmanager
134146
def withAssertOutput(self, expected_stdout, expected_stderr, encoding='utf-8'):
135147
with self.withOutput() as (out, err):

tests/mog_commons/test_unittest.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@ def test_assert_system_exit(self):
3030
self.assertSystemExit(123, lambda: sys.exit(123))
3131
self.assertSystemExit(234, lambda x: sys.exit(x), 234)
3232

33+
def test_with_bytes_output(self):
34+
with self.withBytesOutput() as (out, err):
35+
out.write(b'\xff\xfe')
36+
out.write('あいうえお'.encode('utf-8'))
37+
err.write(b'\xfd\xfc')
38+
self.assertEqual(out.getvalue(), b'\xff\xfe' + 'あいうえお'.encode('utf-8'))
39+
self.assertEqual(err.getvalue(), b'\xfd\xfc')
40+
3341
def test_with_assert_output_file(self):
3442
def f(text):
3543
with self.withAssertOutputFile(os.path.join('tests', 'resources', 'utf8_ja.txt')) as out:

0 commit comments

Comments
 (0)