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