Merge branch 'mdsal-trace' from controller
[mdsal.git] / binding / mdsal-binding-test-utils / src / main / java / org / opendaylight / mdsal / binding / testutils / DiffUtil.java
1 /*
2  * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.testutils;
9
10 import com.google.common.base.Joiner;
11 import com.google.common.base.Splitter;
12 import difflib.DiffUtils;
13 import difflib.Patch;
14 import java.util.List;
15
16 /**
17  * Utility to create diff of text.
18  *
19  * @author Michael Vorburger
20  */
21 // package-local: no need to expose this, consider it an implementation detail; public API is the AssertDataObjects
22 final class DiffUtil {
23
24     // Configuration which we could tune as we use this more
25     private static final int MAX_DIFFS = 1;
26     private static final int CONTEXT_LINES = 3; // number of lines of context output around each difference
27
28     private static final Splitter SPLITTER = Splitter.on(System.getProperty("line.separator"));
29     private static final Joiner JOINER = Joiner.on(System.getProperty("line.separator"));
30
31     public static String diff(String expectedText, String actualText) {
32         List<String> originalLines = SPLITTER.splitToList(expectedText);
33         List<String> revisedLines = SPLITTER.splitToList(actualText);
34         Patch<String> patch = DiffUtils.diff(originalLines, revisedLines);
35         List<String> diff = DiffUtils.generateUnifiedDiff("expected", "actual", originalLines, patch, CONTEXT_LINES);
36
37         String header = "";
38         int deltas = patch.getDeltas().size();
39         if (deltas > MAX_DIFFS) {
40             header = String.format("(Too many differences (%d); only showing first %d)%n", deltas, MAX_DIFFS);
41             diff = diff.subList(0, MAX_DIFFS);
42         }
43         return header + JOINER.join(diff);
44     }
45
46     private DiffUtil() { }
47
48 }