OLD | NEW |
(Empty) | |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 """A utility function to do text diffs of expected and actual layout test result
s.""" |
| 6 |
| 7 import difflib |
| 8 |
| 9 |
| 10 def unified_diff(expected_text, actual_text, expected_filename, actual_filename)
: |
| 11 """Returns a string containing the diff of the two text strings |
| 12 in 'unified diff' format. |
| 13 """ |
| 14 # The filenames show up in the diff output, make sure they're |
| 15 # raw bytes and not unicode, so that they don't trigger join() |
| 16 # trying to decode the input. |
| 17 expected_filename = _to_raw_bytes(expected_filename) |
| 18 actual_filename = _to_raw_bytes(actual_filename) |
| 19 |
| 20 diff = difflib.unified_diff( |
| 21 expected_text.splitlines(True), |
| 22 actual_text.splitlines(True), |
| 23 expected_filename, |
| 24 actual_filename) |
| 25 |
| 26 return ''.join(_diff_fixup(diff)) |
| 27 |
| 28 |
| 29 def _to_raw_bytes(string_value): |
| 30 if isinstance(string_value, unicode): |
| 31 return string_value.encode('utf-8') |
| 32 return string_value |
| 33 |
| 34 |
| 35 def _diff_fixup(diff): |
| 36 # The diff generated by the difflib is incorrect if one of the files |
| 37 # does not have a newline at the end of the file and it is present in |
| 38 # the diff. Relevant Python issue: http://bugs.python.org/issue2142 |
| 39 for line in diff: |
| 40 yield line |
| 41 if not line.endswith('\n'): |
| 42 yield '\n\\ No newline at end of file\n' |
OLD | NEW |