Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make IsBlank matcher consistent with String.isBlank #326

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions hamcrest/src/main/java/org/hamcrest/text/IsBlankString.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import java.util.regex.Pattern;

import static org.hamcrest.core.AnyOf.anyOf;
import static org.hamcrest.core.IsNull.nullValue;

Expand All @@ -18,13 +16,20 @@ public final class IsBlankString extends TypeSafeMatcher<String> {
@SuppressWarnings("unchecked")
private static final Matcher<String> NULL_OR_BLANK_INSTANCE = anyOf(nullValue(), BLANK_INSTANCE);

private static final Pattern REGEX_WHITESPACE = Pattern.compile("\\s*");

private IsBlankString() { }

@Override
public boolean matchesSafely(String item) {
return REGEX_WHITESPACE.matcher(item).matches();
final int length = item.length();
int offset = 0;
while (offset < length) {
final int codePoint = item.codePointAt(offset);
if (!Character.isWhitespace(codePoint)) {
return false;
}
offset += Character.charCount(codePoint);
}
return true;
}

@Override
Expand Down
22 changes: 22 additions & 0 deletions hamcrest/src/test/java/org/hamcrest/text/IsBlankStringTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ public final class IsBlankStringTest {
assertMatches(blankString(), " \t");
assertMatches(blankOrNullString(), " \t");
}

@Test public void
matchesAllCharactersConsideredWhitespaceByJavaLangCharacter() {
// See Javadocs for Character.isWhitespace
String[] consideredBlankByJavaLangCharacter = new String[] {
"\t",
"\n",
"\u000B",
"\f",
"\r",
"\u001C",
"\u001D",
"\u001E",
"\u001F"
};

for(String string : consideredBlankByJavaLangCharacter) {
assertMatches(blankString(), string);
assertMatches(blankOrNullString(), string);
}
}

@Test public void
doesNotMatchFilledString() {
Expand All @@ -52,4 +73,5 @@ public final class IsBlankStringTest {
assertMismatchDescription("was \"a\"", blankString(), "a");
assertMismatchDescription("was \"a\"", blankOrNullString(), "a");
}

}