aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/java/com/google/common/truth/SubjectUtils.java
blob: ae55c06687c25867ff6cb614a20b8f7d90dff195 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*
 * Copyright (c) 2011 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.common.truth;

import static com.google.common.base.Strings.lenientFormat;
import static com.google.common.collect.Iterables.isEmpty;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Multisets.immutableEntry;

import com.google.common.base.Equivalence;
import com.google.common.base.Equivalence.Wrapper;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultiset;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Utility methods used in {@code Subject} implementors.
 *
 * @author Christian Gruber
 * @author Jens Nyman
 */
final class SubjectUtils {
  private SubjectUtils() {}

  static final String HUMAN_UNDERSTANDABLE_EMPTY_STRING = "\"\" (empty String)";

  static <T extends @Nullable Object> List<T> accumulate(T first, T second, T @Nullable ... rest) {
    // rest should never be deliberately null, so assume that the caller passed null
    // in the third position but intended it to be the third element in the array of values.
    // Javac makes the opposite inference, so handle that here.
    List<T> items = new ArrayList<>(2 + ((rest == null) ? 1 : rest.length));
    items.add(first);
    items.add(second);
    if (rest == null) {
      items.add((T) null);
    } else {
      items.addAll(Arrays.asList(rest));
    }
    return items;
  }

  static <T> int countOf(T t, Iterable<T> items) {
    int count = 0;
    for (T item : items) {
      if (t == null ? (item == null) : t.equals(item)) {
        count++;
      }
    }
    return count;
  }

  static String countDuplicates(Iterable<?> items) {
    /*
     * TODO(cpovirk): Remove brackets after migrating all callers to the new message format. But
     * will that look OK when we put the result next to a homogeneous type name? If not, maybe move
     * the homogeneous type name to a separate Fact?
     */
    return countDuplicatesToMultiset(items).toStringWithBrackets();
  }

  static String entryString(Multiset.Entry<?> entry) {
    int count = entry.getCount();
    String item = String.valueOf(entry.getElement());
    return (count > 1) ? item + " [" + count + " copies]" : item;
  }

  private static <T extends @Nullable Object> NonHashingMultiset<T> countDuplicatesToMultiset(
      Iterable<T> items) {
    // We use avoid hashing in case the elements don't have a proper
    // .hashCode() method (e.g., MessageSet from old versions of protobuf).
    NonHashingMultiset<T> multiset = new NonHashingMultiset<>();
    for (T item : items) {
      multiset.add(item);
    }
    return multiset;
  }

  /**
   * Makes a String representation of {@code items} with collapsed duplicates and additional class
   * info.
   *
   * <p>Example: {@code countDuplicatesAndAddTypeInfo([1, 2, 2, 3]) == "[1, 2 [3 copies]]
   * (java.lang.Integer)"} and {@code countDuplicatesAndAddTypeInfo([1, 2L]) == "[1
   * (java.lang.Integer), 2 (java.lang.Long)]"}.
   */
  static String countDuplicatesAndAddTypeInfo(Iterable<?> itemsIterable) {
    Collection<?> items = iterableToCollection(itemsIterable);
    Optional<String> homogeneousTypeName = getHomogeneousTypeName(items);

    return homogeneousTypeName.isPresent()
        ? lenientFormat("%s (%s)", countDuplicates(items), homogeneousTypeName.get())
        : countDuplicates(addTypeInfoToEveryItem(items));
  }

  /**
   * Similar to {@link #countDuplicatesAndAddTypeInfo} and {@link #countDuplicates} but (a) only
   * adds type info if requested and (b) returns a richer object containing the data.
   */
  static DuplicateGroupedAndTyped countDuplicatesAndMaybeAddTypeInfoReturnObject(
      Iterable<?> itemsIterable, boolean addTypeInfo) {
    if (addTypeInfo) {
      Collection<?> items = iterableToCollection(itemsIterable);
      Optional<String> homogeneousTypeName = getHomogeneousTypeName(items);

      NonHashingMultiset<?> valuesWithCountsAndMaybeTypes =
          homogeneousTypeName.isPresent()
              ? countDuplicatesToMultiset(items)
              : countDuplicatesToMultiset(addTypeInfoToEveryItem(items));
      return new DuplicateGroupedAndTyped(valuesWithCountsAndMaybeTypes, homogeneousTypeName);
    } else {
      return new DuplicateGroupedAndTyped(
          countDuplicatesToMultiset(itemsIterable),
          /* homogeneousTypeToDisplay= */ Optional.<String>absent());
    }
  }

  private static final class NonHashingMultiset<E extends @Nullable Object> {
    /*
     * This ought to be static, but the generics are easier when I can refer to <E>. We still want
     * an Entry<?> so that entrySet() can return Iterable<Entry<?>> instead of Iterable<Entry<E>>.
     * That way, it can be returned directly from DuplicateGroupedAndTyped.entrySet() without our
     * having to generalize *its* return type to Iterable<? extends Entry<?>>.
     */
    private Multiset.Entry<?> unwrapKey(Multiset.Entry<Wrapper<E>> input) {
      return immutableEntry(input.getElement().get(), input.getCount());
    }

    private final Multiset<Wrapper<E>> contents = LinkedHashMultiset.create();

    void add(E element) {
      contents.add(EQUALITY_WITHOUT_USING_HASH_CODE.wrap(element));
    }

    int totalCopies() {
      return contents.size();
    }

    boolean isEmpty() {
      return contents.isEmpty();
    }

    Iterable<Multiset.Entry<?>> entrySet() {
      return transform(contents.entrySet(), this::unwrapKey);
    }

    String toStringWithBrackets() {
      List<String> parts = new ArrayList<>();
      for (Multiset.Entry<?> entry : entrySet()) {
        parts.add(entryString(entry));
      }
      return parts.toString();
    }

    @Override
    public String toString() {
      String withBrackets = toStringWithBrackets();
      return withBrackets.substring(1, withBrackets.length() - 1);
    }

    private static final Equivalence<Object> EQUALITY_WITHOUT_USING_HASH_CODE =
        new Equivalence<Object>() {
          @Override
          protected boolean doEquivalent(Object a, Object b) {
            return Objects.equal(a, b);
          }

          @Override
          protected int doHash(Object o) {
            return 0; // slow but hopefully not much worse than what we get with a flat list
          }
        };
  }

  /**
   * Missing or unexpected values from a collection assertion, with equal objects grouped together
   * and, in some cases, type information added. If the type information is present, it is either
   * present in {@code homogeneousTypeToDisplay} (if all objects have the same type) or appended to
   * each individual element (if some elements have different types).
   *
   * <p>This allows collection assertions to the type information on a separate line from the
   * elements and even to output different elements on different lines.
   */
  static final class DuplicateGroupedAndTyped {
    final NonHashingMultiset<?> valuesAndMaybeTypes;
    final Optional<String> homogeneousTypeToDisplay;

    DuplicateGroupedAndTyped(
        NonHashingMultiset<?> valuesAndMaybeTypes, Optional<String> homogeneousTypeToDisplay) {
      this.valuesAndMaybeTypes = valuesAndMaybeTypes;
      this.homogeneousTypeToDisplay = homogeneousTypeToDisplay;
    }

    int totalCopies() {
      return valuesAndMaybeTypes.totalCopies();
    }

    boolean isEmpty() {
      return valuesAndMaybeTypes.isEmpty();
    }

    Iterable<Multiset.Entry<?>> entrySet() {
      return valuesAndMaybeTypes.entrySet();
    }

    @Override
    public String toString() {
      return homogeneousTypeToDisplay.isPresent()
          ? valuesAndMaybeTypes + " (" + homogeneousTypeToDisplay.get() + ")"
          : valuesAndMaybeTypes.toString();
    }
  }

  /**
   * Makes a String representation of {@code items} with additional class info.
   *
   * <p>Example: {@code iterableToStringWithTypeInfo([1, 2]) == "[1, 2] (java.lang.Integer)"} and
   * {@code iterableToStringWithTypeInfo([1, 2L]) == "[1 (java.lang.Integer), 2 (java.lang.Long)]"}.
   */
  static String iterableToStringWithTypeInfo(Iterable<?> itemsIterable) {
    Collection<?> items = iterableToCollection(itemsIterable);
    Optional<String> homogeneousTypeName = getHomogeneousTypeName(items);

    if (homogeneousTypeName.isPresent()) {
      return lenientFormat("%s (%s)", items, homogeneousTypeName.get());
    } else {
      return addTypeInfoToEveryItem(items).toString();
    }
  }

  /**
   * Returns a new collection containing all elements in {@code items} for which there exists at
   * least one element in {@code itemsToCheck} that has the same {@code toString()} value without
   * being equal.
   *
   * <p>Example: {@code retainMatchingToString([1L, 2L, 2L], [2, 3]) == [2L, 2L]}
   */
  static List<@Nullable Object> retainMatchingToString(
      Iterable<?> items, Iterable<?> itemsToCheck) {
    ListMultimap<String, @Nullable Object> stringValueToItemsToCheck = ArrayListMultimap.create();
    for (Object itemToCheck : itemsToCheck) {
      stringValueToItemsToCheck.put(String.valueOf(itemToCheck), itemToCheck);
    }

    List<@Nullable Object> result = Lists.newArrayList();
    for (Object item : items) {
      for (Object itemToCheck : stringValueToItemsToCheck.get(String.valueOf(item))) {
        if (!Objects.equal(itemToCheck, item)) {
          result.add(item);
          break;
        }
      }
    }
    return result;
  }

  /**
   * Returns true if there is a pair of an item from {@code items1} and one in {@code items2} that
   * has the same {@code toString()} value without being equal.
   *
   * <p>Example: {@code hasMatchingToStringPair([1L, 2L], [1]) == true}
   */
  static boolean hasMatchingToStringPair(Iterable<?> items1, Iterable<?> items2) {
    if (isEmpty(items1) || isEmpty(items2)) {
      return false; // Bail early to avoid calling hashCode() on the elements unnecessarily.
    }
    return !retainMatchingToString(items1, items2).isEmpty();
  }

  static String objectToTypeName(@Nullable Object item) {
    // TODO(cpovirk): Merge this with the code in Subject.failEqualityCheck().
    if (item == null) {
      // The name "null type" comes from the interface javax.lang.model.type.NullType.
      return "null type";
    } else if (item instanceof Map.Entry) {
      Map.Entry<?, ?> entry = (Map.Entry<?, ?>) item;
      // Fix for interesting bug when entry.getValue() returns itself b/170390717
      String valueTypeName =
          entry.getValue() == entry ? "Map.Entry" : objectToTypeName(entry.getValue());

      return lenientFormat("Map.Entry<%s, %s>", objectToTypeName(entry.getKey()), valueTypeName);
    } else {
      return item.getClass().getName();
    }
  }

  /**
   * Returns the name of the single type of all given items or {@link Optional#absent()} if no such
   * type exists.
   */
  private static Optional<String> getHomogeneousTypeName(Iterable<?> items) {
    Optional<String> homogeneousTypeName = Optional.absent();
    for (Object item : items) {
      if (item == null) {
        /*
         * TODO(cpovirk): Why? We could have multiple nulls, which would be homogeneous. More
         * likely, we could have exactly one null, which is still homogeneous. Arguably it's weird
         * to call a single element "homogeneous" at all, but that's not specific to null.
         */
        return Optional.absent();
      } else if (!homogeneousTypeName.isPresent()) {
        // This is the first item
        homogeneousTypeName = Optional.of(objectToTypeName(item));
      } else if (!objectToTypeName(item).equals(homogeneousTypeName.get())) {
        // items is a heterogeneous collection
        return Optional.absent();
      }
    }
    return homogeneousTypeName;
  }

  private static List<String> addTypeInfoToEveryItem(Iterable<?> items) {
    List<String> itemsWithTypeInfo = Lists.newArrayList();
    for (Object item : items) {
      itemsWithTypeInfo.add(lenientFormat("%s (%s)", item, objectToTypeName(item)));
    }
    return itemsWithTypeInfo;
  }

  static <T extends @Nullable Object> Collection<T> iterableToCollection(Iterable<T> iterable) {
    if (iterable instanceof Collection) {
      // Should be safe to assume that any Iterable implementing Collection isn't a one-shot
      // iterable, right? I sure hope so.
      return (Collection<T>) iterable;
    } else {
      return Lists.newArrayList(iterable);
    }
  }

  static <T extends @Nullable Object> List<T> iterableToList(Iterable<T> iterable) {
    if (iterable instanceof List) {
      return (List<T>) iterable;
    } else {
      return Lists.newArrayList(iterable);
    }
  }

  /**
   * Returns an iterable with all empty strings replaced by a non-empty human understandable
   * indicator for an empty string.
   *
   * <p>Returns the given iterable if it contains no empty strings.
   */
  static <T extends @Nullable Object> Iterable<T> annotateEmptyStrings(Iterable<T> items) {
    if (Iterables.contains(items, "")) {
      List<T> annotatedItems = Lists.newArrayList();
      for (T item : items) {
        if (Objects.equal(item, "")) {
          // This is a safe cast because know that at least one instance of T (this item) is a
          // String.
          @SuppressWarnings("unchecked")
          T newItem = (T) HUMAN_UNDERSTANDABLE_EMPTY_STRING;
          annotatedItems.add(newItem);
        } else {
          annotatedItems.add(item);
        }
      }
      return annotatedItems;
    } else {
      return items;
    }
  }

  @SafeVarargs
  static <E> ImmutableList<E> concat(Iterable<? extends E>... inputs) {
    return ImmutableList.copyOf(Iterables.concat(inputs));
  }

  static <E> ImmutableList<E> append(E[] array, E object) {
    return new ImmutableList.Builder<E>().add(array).add(object).build();
  }

  static <E> ImmutableList<E> append(ImmutableList<? extends E> list, E object) {
    return new ImmutableList.Builder<E>().addAll(list).add(object).build();
  }

  static <E> ImmutableList<E> sandwich(E first, E[] array, E last) {
    return new ImmutableList.Builder<E>().add(first).add(array).add(last).build();
  }
}