001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect.testing;
018
019import static com.google.common.collect.testing.Helpers.copyToList;
020import static com.google.common.collect.testing.Helpers.mapEntry;
021
022import com.google.common.annotations.GwtCompatible;
023import java.util.Collection;
024import java.util.Iterator;
025import java.util.List;
026import java.util.ListIterator;
027import java.util.Map;
028import java.util.Map.Entry;
029import org.jspecify.annotations.NullMarked;
030import org.checkerframework.checker.nullness.qual.Nullable;
031import org.junit.Ignore;
032
033/**
034 * Base class for map testers.
035 *
036 * <p>TODO: see how much of this is actually needed once Map testers are written. (It was cloned
037 * from AbstractCollectionTester.)
038 *
039 * @param <K> the key type of the map to be tested.
040 * @param <V> the value type of the map to be tested.
041 * @author George van den Driessche
042 */
043@GwtCompatible
044@Ignore("test runners must not instantiate and run this directly, only via suites we build")
045// @Ignore affects the Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
046@SuppressWarnings("JUnit4ClassUsedInJUnit3")
047@NullMarked
048public abstract class AbstractMapTester<K extends @Nullable Object, V extends @Nullable Object>
049    extends AbstractContainerTester<Map<K, V>, Entry<K, V>> {
050  protected Map<K, V> getMap() {
051    return container;
052  }
053
054  @Override
055  protected Collection<Entry<K, V>> actualContents() {
056    return getMap().entrySet();
057  }
058
059  /** @see AbstractContainerTester#resetContainer() */
060  protected final void resetMap() {
061    resetContainer();
062  }
063
064  protected void resetMap(Entry<K, V>[] entries) {
065    resetContainer(getSubjectGenerator().create((Object[]) entries));
066  }
067
068  protected void expectMissingKeys(K... elements) {
069    for (K element : elements) {
070      assertFalse("Should not contain key " + element, getMap().containsKey(element));
071    }
072  }
073
074  protected void expectMissingValues(V... elements) {
075    for (V element : elements) {
076      assertFalse("Should not contain value " + element, getMap().containsValue(element));
077    }
078  }
079
080  /** @return an array of the proper size with {@code null} as the key of the middle element. */
081  protected Entry<K, V>[] createArrayWithNullKey() {
082    Entry<K, V>[] array = createSamplesArray();
083    int nullKeyLocation = getNullLocation();
084    Entry<K, V> oldEntry = array[nullKeyLocation];
085    array[nullKeyLocation] = entry(null, oldEntry.getValue());
086    return array;
087  }
088
089  protected V getValueForNullKey() {
090    return getEntryNullReplaces().getValue();
091  }
092
093  protected K getKeyForNullValue() {
094    return getEntryNullReplaces().getKey();
095  }
096
097  private Entry<K, V> getEntryNullReplaces() {
098    Iterator<Entry<K, V>> entries = getSampleElements().iterator();
099    for (int i = 0; i < getNullLocation(); i++) {
100      entries.next();
101    }
102    return entries.next();
103  }
104
105  /** @return an array of the proper size with {@code null} as the value of the middle element. */
106  protected Entry<K, V>[] createArrayWithNullValue() {
107    Entry<K, V>[] array = createSamplesArray();
108    int nullValueLocation = getNullLocation();
109    Entry<K, V> oldEntry = array[nullValueLocation];
110    array[nullValueLocation] = entry(oldEntry.getKey(), null);
111    return array;
112  }
113
114  protected void initMapWithNullKey() {
115    resetMap(createArrayWithNullKey());
116  }
117
118  protected void initMapWithNullValue() {
119    resetMap(createArrayWithNullValue());
120  }
121
122  /**
123   * Equivalent to {@link #expectMissingKeys(Object[]) expectMissingKeys} {@code (null)} except that
124   * the call to {@code contains(null)} is permitted to throw a {@code NullPointerException}.
125   *
126   * @param message message to use upon assertion failure
127   */
128  protected void expectNullKeyMissingWhenNullKeysUnsupported(String message) {
129    try {
130      assertFalse(message, getMap().containsKey(null));
131    } catch (NullPointerException tolerated) {
132      // Tolerated
133    }
134  }
135
136  /**
137   * Equivalent to {@link #expectMissingValues(Object[]) expectMissingValues} {@code (null)} except
138   * that the call to {@code contains(null)} is permitted to throw a {@code NullPointerException}.
139   *
140   * @param message message to use upon assertion failure
141   */
142  protected void expectNullValueMissingWhenNullValuesUnsupported(String message) {
143    try {
144      assertFalse(message, getMap().containsValue(null));
145    } catch (NullPointerException tolerated) {
146      // Tolerated
147    }
148  }
149
150  @Override
151  protected MinimalCollection<Entry<K, V>> createDisjointCollection() {
152    return MinimalCollection.of(e3(), e4());
153  }
154
155  protected int getNumEntries() {
156    return getNumElements();
157  }
158
159  protected Collection<Entry<K, V>> getSampleEntries(int howMany) {
160    return getSampleElements(howMany);
161  }
162
163  protected Collection<Entry<K, V>> getSampleEntries() {
164    return getSampleElements();
165  }
166
167  @Override
168  protected void expectMissing(Entry<K, V>... entries) {
169    for (Entry<K, V> entry : entries) {
170      assertFalse("Should not contain entry " + entry, actualContents().contains(entry));
171      assertFalse(
172          "Should not contain key " + entry.getKey() + " mapped to value " + entry.getValue(),
173          equal(getMap().get(entry.getKey()), entry.getValue()));
174    }
175  }
176
177  private static boolean equal(@Nullable Object a, @Nullable Object b) {
178    return a == b || (a != null && a.equals(b));
179  }
180
181  // This one-liner saves us from some ugly casts
182  protected Entry<K, V> entry(K key, V value) {
183    return mapEntry(key, value);
184  }
185
186  @Override
187  protected void expectContents(Collection<Entry<K, V>> expected) {
188    // TODO: move this to invariant checks once the appropriate hook exists?
189    super.expectContents(expected);
190    for (Entry<K, V> entry : expected) {
191      assertEquals(
192          "Wrong value for key " + entry.getKey(), entry.getValue(), getMap().get(entry.getKey()));
193    }
194  }
195
196  protected final void expectReplacement(Entry<K, V> newEntry) {
197    List<Entry<K, V>> expected = copyToList(getSampleElements());
198    replaceValue(expected, newEntry);
199    expectContents(expected);
200  }
201
202  private void replaceValue(List<Entry<K, V>> expected, Entry<K, V> newEntry) {
203    for (ListIterator<Entry<K, V>> i = expected.listIterator(); i.hasNext(); ) {
204      if (Helpers.equal(i.next().getKey(), newEntry.getKey())) {
205        i.set(newEntry);
206        return;
207      }
208    }
209
210    throw new IllegalArgumentException(
211        Platform.format("key %s not found in entries %s", newEntry.getKey(), expected));
212  }
213
214  /**
215   * Wrapper for {@link Map#get(Object)} that forces the caller to pass in a key of the same type as
216   * the map. Besides being slightly shorter than code that uses {@link #getMap()}, it also ensures
217   * that callers don't pass an {@link Entry} by mistake.
218   */
219  protected V get(K key) {
220    return getMap().get(key);
221  }
222
223  protected final K k0() {
224    return e0().getKey();
225  }
226
227  protected final V v0() {
228    return e0().getValue();
229  }
230
231  protected final K k1() {
232    return e1().getKey();
233  }
234
235  protected final V v1() {
236    return e1().getValue();
237  }
238
239  protected final K k2() {
240    return e2().getKey();
241  }
242
243  protected final V v2() {
244    return e2().getValue();
245  }
246
247  protected final K k3() {
248    return e3().getKey();
249  }
250
251  protected final V v3() {
252    return e3().getValue();
253  }
254
255  protected final K k4() {
256    return e4().getKey();
257  }
258
259  protected final V v4() {
260    return e4().getValue();
261  }
262}