Skip to content

Instantly share code, notes, and snippets.

@fwcd
Created August 10, 2021 12:57
Show Gist options
  • Save fwcd/a88ae2e5eb6e9602dd655e749b49ddc2 to your computer and use it in GitHub Desktop.
Save fwcd/a88ae2e5eb6e9602dd655e749b49ddc2 to your computer and use it in GitHub Desktop.
Automatic color diffs for XCTest output
#!/usr/bin/env python3
# A small script that parses the output of `swift test`
# and emits colored diffs for failed XCTAssertEquals.
import difflib
import fileinput
import re
import subprocess
# ANSI colors
BROWN = '\033[33m'
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
CLEAR = '\033[0m'
for line in fileinput.input():
match = re.search(r'^(.+XCTAssertEqual failed:)\s+\("(.+)"\)\s+is not equal to\s+\("(.+)"\)', line)
if match:
[msg, a, b] = [match[1], match[2], match[3]]
differ = difflib.SequenceMatcher(None, a, b)
diff = ''
for op, i1, i2, j1, j2 in differ.get_opcodes():
if op == 'replace':
diff += f'{YELLOW}{{{differ.a[i1:i2]} -> {differ.b[j1:j2]}}}{CLEAR}'
elif op == 'equal':
diff += differ.a[i1:i2]
elif op == 'insert':
diff += f'{GREEN}{{+ {differ.b[j1:j2]}}}{CLEAR}'
elif op == 'delete':
diff += f'{RED}{{- {differ.a[i1:i2]}}}{CLEAR}'
print('\n'.join([
f'{BROWN}{msg}{CLEAR}',
diff,
''
]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment