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

Issue 172: optimize map hasKey() and hasEntry() #292

Open
wants to merge 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,39 @@ public static <K,V> Matcher<Map<? extends K,? extends V>> hasEntry(Matcher<? sup
* the value that, in combination with the key, must be describe at least one entry
*/
public static <K,V> Matcher<Map<? extends K,? extends V>> hasEntry(K key, V value) {
return new IsMapContaining<>(equalTo(key), equalTo(value));
return new IsMapContainingEntry<>(key, value);
}


/**
* Provides a type-safe optimization over the O(n) linear search in {@link IsMapContaining#matchesSafely(Map)},
* by leveraging the speed of the map's own {@link Map#containsKey(Object)} check.
* <p>
* It preserves the same descriptors.
*/
private static class IsMapContainingEntry<K, V> extends IsMapContaining<K, V>
{
private final K key;

public IsMapContainingEntry(K key, V value)
{
super(equalTo(key), equalTo(value));
this.key = key;
}

@Override
public boolean matchesSafely(Map<? extends K, ? extends V> map)
{
try{
return map.containsKey(key) && super.valueMatcher.matches(map.get(key));
} catch (NullPointerException e){
// some maps (like Hashtable) don't want to let you check for a null key.
// to be consistent with previous behavior checking each entry,
// we squash any error coming from that to indicate simply that there's no entry with that key.
return false;
}
}
}

/**
* Creates a matcher for {@link java.util.Map}s matching when the examined {@link java.util.Map} contains
* at least one key that satisfies the specified matcher.
Expand All @@ -98,7 +128,51 @@ public static <K,V> Matcher<Map<? extends K,? extends V>> hasEntry(K key, V valu
* the key that satisfying maps must contain
*/
public static <K> Matcher<Map<? extends K, ?>> hasKey(K key) {
return new IsMapContaining<>(equalTo(key), anything());
return new IsMapContainingKey<>(key);
}

/**
* Provides a type-safe optimization over the O(n) linear search in {@link IsMapContaining#matchesSafely(Map)},
* by leveraging the speed of the map's own {@link Map#containsKey(Object)} check.
* <p>
* It preserves the same descriptors.
*/
private static class IsMapContainingKey<K, V> extends IsMapContaining<K, V>
{
private final K key;

public IsMapContainingKey(K key)
{
super(equalTo(key), anything());
this.key = key;
}

@Override
public boolean matchesSafely(Map<? extends K, ? extends V> map)
{
try
{
return map.containsKey(key);
} catch (NullPointerException e){
// some maps (like Hashtable) don't want to let you check for a null key.
// to be consistent with previous behavior checking each entry,
// we squash any error coming from that to indicate simply that there's no entry with that key.
return false;
}
}

@Override
public void describeMismatchSafely(Map<? extends K, ? extends V> map, Description mismatchDescription)
{
mismatchDescription.appendText("map keys were ").appendValueList("[", ", ", "]", map.keySet());
}

@Override
public void describeTo(Description description)
{
description.appendText("map containing key ")
.appendDescriptionOf(super.keyMatcher);
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.hamcrest.Matcher;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;

Expand Down Expand Up @@ -62,15 +63,33 @@ public void testMatchesMapContainingKeyWithNumberKeys() throws Exception {
assertThat(map, hasKey((Number)1));

// TODO: work out the correct sprinkling of wildcards to get this to work!
// assertThat(map, hasKey(1));
// assertThat(map, hasKey(1));
}

public void test_mapContainingNullKey_returnsFalse_forMapsWithNonnullKeys() throws Exception {
Map<Number, String> map = new Hashtable<>(); // Hashtables cannot store null keys
map.put(1, "A");
map.put(2, "B");

assertDoesNotMatch(hasKey((Number)null), map);
}


public void test_mapContainingNullKey_returnsTrue_forMapWithNullKey() throws Exception {
Map<Number, String> map = new HashMap<>(); // HashMap can store null keys
map.put(1, "A");
map.put(2, "B");
map.put(null, "C");

assertMatches(hasKey((Number)null), map);
}

public void testHasReadableDescription() {
assertDescription("map containing [\"a\"->ANYTHING]", hasKey("a"));
assertDescription("map containing key \"a\"", hasKey("a"));
}

public void testDoesNotMatchEmptyMap() {
assertMismatchDescription("map was []", hasKey("Foo"), new HashMap<String,Integer>());
assertMismatchDescription("map keys were []", hasKey("Foo"), new HashMap<String,Integer>());
}

public void testDoesNotMatchMapMissingKey() {
Expand All @@ -79,6 +98,6 @@ public void testDoesNotMatchMapMissingKey() {
map.put("b", 2);
map.put("c", 3);

assertMismatchDescription("map was [<a=1>, <b=2>, <c=3>]", hasKey("d"), map);
assertMismatchDescription("map keys were [\"a\", \"b\", \"c\"]", hasKey("d"), map);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.hamcrest.Matcher;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;

Expand Down Expand Up @@ -46,4 +47,29 @@ public void testDoesNotMatchNull() {
public void testHasReadableDescription() {
assertDescription("map containing [\"a\"-><2>]", hasEntry(equalTo("a"), (equalTo(2))));
}

public void test_mapContainsEntryWithNullKey_returnsFalseForMapsWithoutNullKeys(){
Map<String, Integer> map = new Hashtable<>(); // throws exception if given null key, or if map.containsKey(null) is called
map.put("a", 1);
map.put("b", 2);

assertDoesNotMatch(hasEntry(null, 2), map);
}

public void test_mapContainsEntryWithNullKey_returnsTrueForMapWithNullKeyAndMatchingValue(){
Map<String, Integer> map = new HashMap<>(); // throws exception if given null key, or if map.containsKey(null) is called
map.put("a", 1);
map.put("b", 2);
map.put(null, 3);

assertMatches(hasEntry(null, 3), map);
}

public void test_mapContainsEntryWithNullKey_returnsFalseForMapWithNullKeyAndNoMatchingValue(){
Map<String, Integer> map = new HashMap<>(); // throws exception if given null key, or if map.containsKey(null) is called
map.put("a", 1);
map.put("b", 2);

assertDoesNotMatch(hasEntry(null, 3), map);
}
}