Java

Форк
0
257 строк · 7.5 Кб
1
/*
2
 * Copyright (C) 2007 The Guava Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 * http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package com.google.common.collect.testing;
18

19
import com.google.common.annotations.GwtCompatible;
20
import java.util.Collection;
21
import java.util.Iterator;
22
import java.util.List;
23
import java.util.ListIterator;
24
import java.util.Map;
25
import java.util.Map.Entry;
26
import org.checkerframework.checker.nullness.qual.Nullable;
27
import org.junit.Ignore;
28

29
/**
30
 * Base class for map testers.
31
 *
32
 * <p>TODO: see how much of this is actually needed once Map testers are written. (It was cloned
33
 * from AbstractCollectionTester.)
34
 *
35
 * @param <K> the key type of the map to be tested.
36
 * @param <V> the value type of the map to be tested.
37
 * @author George van den Driessche
38
 */
39
@GwtCompatible
40
@Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
41
@SuppressWarnings("JUnit4ClassUsedInJUnit3")
42
@ElementTypesAreNonnullByDefault
43
public abstract class AbstractMapTester<K extends @Nullable Object, V extends @Nullable Object>
44
    extends AbstractContainerTester<Map<K, V>, Entry<K, V>> {
45
  protected Map<K, V> getMap() {
46
    return container;
47
  }
48

49
  @Override
50
  protected Collection<Entry<K, V>> actualContents() {
51
    return getMap().entrySet();
52
  }
53

54
  /** @see AbstractContainerTester#resetContainer() */
55
  protected final void resetMap() {
56
    resetContainer();
57
  }
58

59
  protected void resetMap(Entry<K, V>[] entries) {
60
    resetContainer(getSubjectGenerator().create((Object[]) entries));
61
  }
62

63
  protected void expectMissingKeys(K... elements) {
64
    for (K element : elements) {
65
      assertFalse("Should not contain key " + element, getMap().containsKey(element));
66
    }
67
  }
68

69
  protected void expectMissingValues(V... elements) {
70
    for (V element : elements) {
71
      assertFalse("Should not contain value " + element, getMap().containsValue(element));
72
    }
73
  }
74

75
  /** @return an array of the proper size with {@code null} as the key of the middle element. */
76
  protected Entry<K, V>[] createArrayWithNullKey() {
77
    Entry<K, V>[] array = createSamplesArray();
78
    int nullKeyLocation = getNullLocation();
79
    Entry<K, V> oldEntry = array[nullKeyLocation];
80
    array[nullKeyLocation] = entry(null, oldEntry.getValue());
81
    return array;
82
  }
83

84
  protected V getValueForNullKey() {
85
    return getEntryNullReplaces().getValue();
86
  }
87

88
  protected K getKeyForNullValue() {
89
    return getEntryNullReplaces().getKey();
90
  }
91

92
  private Entry<K, V> getEntryNullReplaces() {
93
    Iterator<Entry<K, V>> entries = getSampleElements().iterator();
94
    for (int i = 0; i < getNullLocation(); i++) {
95
      entries.next();
96
    }
97
    return entries.next();
98
  }
99

100
  /** @return an array of the proper size with {@code null} as the value of the middle element. */
101
  protected Entry<K, V>[] createArrayWithNullValue() {
102
    Entry<K, V>[] array = createSamplesArray();
103
    int nullValueLocation = getNullLocation();
104
    Entry<K, V> oldEntry = array[nullValueLocation];
105
    array[nullValueLocation] = entry(oldEntry.getKey(), null);
106
    return array;
107
  }
108

109
  protected void initMapWithNullKey() {
110
    resetMap(createArrayWithNullKey());
111
  }
112

113
  protected void initMapWithNullValue() {
114
    resetMap(createArrayWithNullValue());
115
  }
116

117
  /**
118
   * Equivalent to {@link #expectMissingKeys(Object[]) expectMissingKeys} {@code (null)} except that
119
   * the call to {@code contains(null)} is permitted to throw a {@code NullPointerException}.
120
   *
121
   * @param message message to use upon assertion failure
122
   */
123
  protected void expectNullKeyMissingWhenNullKeysUnsupported(String message) {
124
    try {
125
      assertFalse(message, getMap().containsKey(null));
126
    } catch (NullPointerException tolerated) {
127
      // Tolerated
128
    }
129
  }
130

131
  /**
132
   * Equivalent to {@link #expectMissingValues(Object[]) expectMissingValues} {@code (null)} except
133
   * that the call to {@code contains(null)} is permitted to throw a {@code NullPointerException}.
134
   *
135
   * @param message message to use upon assertion failure
136
   */
137
  protected void expectNullValueMissingWhenNullValuesUnsupported(String message) {
138
    try {
139
      assertFalse(message, getMap().containsValue(null));
140
    } catch (NullPointerException tolerated) {
141
      // Tolerated
142
    }
143
  }
144

145
  @Override
146
  protected MinimalCollection<Entry<K, V>> createDisjointCollection() {
147
    return MinimalCollection.of(e3(), e4());
148
  }
149

150
  protected int getNumEntries() {
151
    return getNumElements();
152
  }
153

154
  protected Collection<Entry<K, V>> getSampleEntries(int howMany) {
155
    return getSampleElements(howMany);
156
  }
157

158
  protected Collection<Entry<K, V>> getSampleEntries() {
159
    return getSampleElements();
160
  }
161

162
  @Override
163
  protected void expectMissing(Entry<K, V>... entries) {
164
    for (Entry<K, V> entry : entries) {
165
      assertFalse("Should not contain entry " + entry, actualContents().contains(entry));
166
      assertFalse(
167
          "Should not contain key " + entry.getKey() + " mapped to value " + entry.getValue(),
168
          equal(getMap().get(entry.getKey()), entry.getValue()));
169
    }
170
  }
171

172
  private static boolean equal(@Nullable Object a, @Nullable Object b) {
173
    return a == b || (a != null && a.equals(b));
174
  }
175

176
  // This one-liner saves us from some ugly casts
177
  protected Entry<K, V> entry(K key, V value) {
178
    return Helpers.mapEntry(key, value);
179
  }
180

181
  @Override
182
  protected void expectContents(Collection<Entry<K, V>> expected) {
183
    // TODO: move this to invariant checks once the appropriate hook exists?
184
    super.expectContents(expected);
185
    for (Entry<K, V> entry : expected) {
186
      assertEquals(
187
          "Wrong value for key " + entry.getKey(), entry.getValue(), getMap().get(entry.getKey()));
188
    }
189
  }
190

191
  protected final void expectReplacement(Entry<K, V> newEntry) {
192
    List<Entry<K, V>> expected = Helpers.copyToList(getSampleElements());
193
    replaceValue(expected, newEntry);
194
    expectContents(expected);
195
  }
196

197
  private void replaceValue(List<Entry<K, V>> expected, Entry<K, V> newEntry) {
198
    for (ListIterator<Entry<K, V>> i = expected.listIterator(); i.hasNext(); ) {
199
      if (Helpers.equal(i.next().getKey(), newEntry.getKey())) {
200
        i.set(newEntry);
201
        return;
202
      }
203
    }
204

205
    throw new IllegalArgumentException(
206
        Platform.format("key %s not found in entries %s", newEntry.getKey(), expected));
207
  }
208

209
  /**
210
   * Wrapper for {@link Map#get(Object)} that forces the caller to pass in a key of the same type as
211
   * the map. Besides being slightly shorter than code that uses {@link #getMap()}, it also ensures
212
   * that callers don't pass an {@link Entry} by mistake.
213
   */
214
  protected V get(K key) {
215
    return getMap().get(key);
216
  }
217

218
  protected final K k0() {
219
    return e0().getKey();
220
  }
221

222
  protected final V v0() {
223
    return e0().getValue();
224
  }
225

226
  protected final K k1() {
227
    return e1().getKey();
228
  }
229

230
  protected final V v1() {
231
    return e1().getValue();
232
  }
233

234
  protected final K k2() {
235
    return e2().getKey();
236
  }
237

238
  protected final V v2() {
239
    return e2().getValue();
240
  }
241

242
  protected final K k3() {
243
    return e3().getKey();
244
  }
245

246
  protected final V v3() {
247
    return e3().getValue();
248
  }
249

250
  protected final K k4() {
251
    return e4().getKey();
252
  }
253

254
  protected final V v4() {
255
    return e4().getValue();
256
  }
257
}
258

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.