Move InputStream matcher to Matchers.
[Sone.git] / src / test / java / net / pterodactylus / sone / Matchers.java
index c08ffb1..8873278 100644 (file)
@@ -20,6 +20,8 @@ package net.pterodactylus.sone;
 import static java.util.Arrays.asList;
 import static java.util.regex.Pattern.compile;
 
+import java.io.IOException;
+import java.io.InputStream;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
@@ -112,4 +114,42 @@ public class Matchers {
                };
        }
 
+       public static Matcher<InputStream> delivers(final byte[] data) {
+               return new TypeSafeMatcher<InputStream>() {
+                       byte[] readData = new byte[data.length];
+
+                       @Override
+                       protected boolean matchesSafely(InputStream inputStream) {
+                               int offset = 0;
+                               try {
+                                       while (true) {
+                                               int r = inputStream.read();
+                                               if (r == -1) {
+                                                       return offset == data.length;
+                                               }
+                                               if (offset == data.length) {
+                                                       return false;
+                                               }
+                                               if (data[offset] != (readData[offset] = (byte) r)) {
+                                                       return false;
+                                               }
+                                               offset++;
+                                       }
+                               } catch (IOException ioe1) {
+                                       return false;
+                               }
+                       }
+
+                       @Override
+                       public void describeTo(Description description) {
+                               description.appendValue(data);
+                       }
+
+                       @Override
+                       protected void describeMismatchSafely(InputStream item, Description mismatchDescription) {
+                               mismatchDescription.appendValue(readData);
+                       }
+               };
+       }
+
 }