1 package junit.framework; 2 3 public class ComparisonCompactor { 4 5 private static final String ELLIPSIS = "..."; 6 private static final String DELTA_END = "]"; 7 private static final String DELTA_START = "["; 8 9 private int fContextLength; 10 private String fExpected; 11 private String fActual; 12 private int fPrefix; 13 private int fSuffix; 14 ComparisonCompactor(int contextLength, String expected, String actual)15 public ComparisonCompactor(int contextLength, String expected, String actual) { 16 fContextLength = contextLength; 17 fExpected = expected; 18 fActual = actual; 19 } 20 21 @SuppressWarnings("deprecation") compact(String message)22 public String compact(String message) { 23 if (fExpected == null || fActual == null || areStringsEqual()) { 24 return Assert.format(message, fExpected, fActual); 25 } 26 27 findCommonPrefix(); 28 findCommonSuffix(); 29 String expected = compactString(fExpected); 30 String actual = compactString(fActual); 31 return Assert.format(message, expected, actual); 32 } 33 compactString(String source)34 private String compactString(String source) { 35 String result = DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; 36 if (fPrefix > 0) { 37 result = computeCommonPrefix() + result; 38 } 39 if (fSuffix > 0) { 40 result = result + computeCommonSuffix(); 41 } 42 return result; 43 } 44 findCommonPrefix()45 private void findCommonPrefix() { 46 fPrefix = 0; 47 int end = Math.min(fExpected.length(), fActual.length()); 48 for (; fPrefix < end; fPrefix++) { 49 if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) { 50 break; 51 } 52 } 53 } 54 findCommonSuffix()55 private void findCommonSuffix() { 56 int expectedSuffix = fExpected.length() - 1; 57 int actualSuffix = fActual.length() - 1; 58 for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { 59 if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) { 60 break; 61 } 62 } 63 fSuffix = fExpected.length() - expectedSuffix; 64 } 65 computeCommonPrefix()66 private String computeCommonPrefix() { 67 return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); 68 } 69 computeCommonSuffix()70 private String computeCommonSuffix() { 71 int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); 72 return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : ""); 73 } 74 areStringsEqual()75 private boolean areStringsEqual() { 76 return fExpected.equals(fActual); 77 } 78 } 79