Skip to content

Commit a09059a

Browse files
Merge pull request #96 from bridadan/fix_test_encode_failure
Fix test encode failure
2 parents 7dd7eed + 549c1d0 commit a09059a

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/mbed_os_tools/test/mbed_test_api.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def run_htrun(cmd, verbose):
125125
htrun_failure_line = re.compile('\[RXD\] (:\d+::FAIL: .*)')
126126

127127
for line in iter(p.stdout.readline, b''):
128-
decoded_line = line.decode('utf-8', 'ignore')
128+
decoded_line = line.decode("utf-8", "replace")
129129
htrun_output += decoded_line
130130
# When dumping output to file both \r and \n will be a new line
131131
# To avoid this "extra new-line" we only use \n at the end
@@ -135,7 +135,20 @@ def run_htrun(cmd, verbose):
135135
gt_logger.gt_log_err(test_error.group(1))
136136

137137
if verbose:
138-
sys.stdout.write(decoded_line.rstrip() + '\n')
138+
output = decoded_line.rstrip() + '\n'
139+
try:
140+
# Try to output decoded unicode. Should be fine in most Python 3
141+
# environments.
142+
sys.stdout.write(output)
143+
except UnicodeEncodeError:
144+
try:
145+
# Try to encode to unicode bytes and let the terminal handle
146+
# the decoding. Some Python 2 and OS combinations handle this
147+
# gracefully.
148+
sys.stdout.write(output.encode("utf-8"))
149+
except TypeError:
150+
# Fallback to printing just ascii characters
151+
sys.stdout.write(output.encode("ascii", "replace").decode("ascii"))
139152
sys.stdout.flush()
140153

141154
# Check if process was terminated by signal

test/test/mbed_gt_test_api.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
import unittest
1717
from mbed_os_tools.test import mbed_test_api
18-
18+
from mock import patch, MagicMock
1919

2020

2121
class GreenteaTestAPI(unittest.TestCase):
@@ -589,5 +589,15 @@ def test_get_testcase_result_start_tag_missing(self):
589589
result = mbed_test_api.get_testcase_result(self.OUTPUT_STARTTAG_MISSING)
590590
self.assertEqual(result['DNS query']['utest_log'], "__testcase_start tag not found.")
591591

592+
def test_run_htrun_unicode(self):
593+
with patch("mbed_os_tools.test.mbed_test_api.run_command") as _run_command:
594+
read_line_mock = MagicMock()
595+
read_line_mock.decode = MagicMock(return_value=u"\u036b")
596+
p_mock = MagicMock()
597+
p_mock.wait = MagicMock(return_value=1337)
598+
p_mock.stdout.readline = MagicMock(side_effect=[read_line_mock])
599+
_run_command.return_value = p_mock
600+
returncode, htrun_output = mbed_test_api.run_htrun("dummy", True)
601+
592602
if __name__ == '__main__':
593603
unittest.main()

0 commit comments

Comments
 (0)