Reusable assertions for InputStream s. @author Matthieu Baechler
| 30 | * @author Matthieu Baechler |
| 31 | */ |
| 32 | public class InputStreams { |
| 33 | |
| 34 | private static final InputStreams INSTANCE = new InputStreams(); |
| 35 | |
| 36 | /** |
| 37 | * Returns the singleton instance of this class. |
| 38 | * @return the singleton instance of this class. |
| 39 | */ |
| 40 | public static InputStreams instance() { |
| 41 | return INSTANCE; |
| 42 | } |
| 43 | |
| 44 | @VisibleForTesting |
| 45 | Diff diff = new Diff(); |
| 46 | @VisibleForTesting |
| 47 | Failures failures = Failures.instance(); |
| 48 | |
| 49 | @VisibleForTesting |
| 50 | InputStreams() {} |
| 51 | |
| 52 | /** |
| 53 | * Asserts that the given InputStreams have equal content. |
| 54 | * |
| 55 | * @param info contains information about the assertion. |
| 56 | * @param actual the "actual" InputStream. |
| 57 | * @param expected the "expected" InputStream. |
| 58 | * @throws NullPointerException if {@code expected} is {@code null}. |
| 59 | * @throws AssertionError if {@code actual} is {@code null}. |
| 60 | * @throws AssertionError if the given InputStreams do not have equal content. |
| 61 | * @throws InputStreamsException if an I/O error occurs. |
| 62 | */ |
| 63 | public void assertEqualContent(AssertionInfo info, InputStream actual, InputStream expected) { |
| 64 | if (expected == null) throw new NullPointerException("The InputStream to compare to should not be null"); |
| 65 | assertNotNull(info, actual); |
| 66 | try { |
| 67 | List<String> diffs = diff.diff(actual, expected); |
| 68 | if (diffs.isEmpty()) return; |
| 69 | throw failures.failure(info, shouldHaveEqualContent(actual, expected, diffs)); |
| 70 | } catch (IOException e) { |
| 71 | String msg = format("Unable to compare contents of InputStreams:\n <%s>\nand:\n <%s>", actual, expected); |
| 72 | throw new InputStreamsException(msg, e); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | private static void assertNotNull(AssertionInfo info, InputStream stream) { |
| 77 | Objects.instance().assertNotNull(info, stream); |
| 78 | } |
| 79 | } |