code
stringlengths
25
201k
docstring
stringlengths
19
96.2k
func_name
stringlengths
0
235
language
stringclasses
1 value
repo
stringlengths
8
51
path
stringlengths
11
314
url
stringlengths
62
377
license
stringclasses
7 values
private boolean correspondInOrderAllIn( Iterator<? extends A> actual, Iterator<? extends E> expected) { // We take a greedy approach here, iterating through the expected elements and pairing each // with the first applicable actual element. This is fine for the in-order test, since there's // no way that paring an expected element with a later actual element permits a solution which // couldn't be achieved by pairing it with the first. (For the any-order test, we may want to // pair an expected element with a later actual element so that we can pair the earlier actual // element with a later expected element, but that doesn't apply here.) Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); while (expected.hasNext()) { E expectedElement = expected.next(); // Return false if we couldn't find the expected exception, or if the correspondence threw // an exception. We'll fall back on the any-order assertion in this case. if (!findCorresponding(actual, expectedElement, exceptions) || exceptions.hasCompareException()) { return false; } } return true; }
Returns whether all the elements of the expected iterator and any subset of the elements of the actual iterator can be paired up in order, such that every pair of actual and expected elements satisfies the correspondence. Returns false if any comparison threw an exception.
correspondInOrderAllIn
java
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
Apache-2.0
private boolean findCorresponding( Iterator<? extends A> actual, E expectedElement, Correspondence.ExceptionStore exceptions) { while (actual.hasNext()) { A actualElement = actual.next(); if (correspondence.safeCompare(actualElement, expectedElement, exceptions)) { return true; } } return false; }
Advances the actual iterator looking for an element which corresponds to the expected element. Returns whether or not it finds one.
findCorresponding
java
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
Apache-2.0
private boolean failIfCandidateMappingHasMissing( List<? extends A> actual, List<? extends E> expected, ImmutableSetMultimap<Integer, Integer> mapping, Correspondence.ExceptionStore exceptions) { List<? extends E> missing = findNotIndexed(expected, mapping.inverse().keySet()); if (!missing.isEmpty()) { List<? extends A> extra = findNotIndexed(actual, mapping.keySet()); subject.failWithoutActual( ImmutableList.<Fact>builder() .addAll(describeMissing(missing, extra, exceptions)) .add(fact("expected to contain at least", expected)) .addAll(correspondence.describeForIterable()) .add(subject.butWas()) .addAll(exceptions.describeAsAdditionalInfo()) .build()); return true; } return false; }
Given a list of actual elements, a list of expected elements, and a many:many mapping between actual and expected elements specified as a multimap of indexes into the actual list to indexes into the expected list, checks that every expected element maps to at least one actual element, and fails if this is not the case. Actual elements which do not map to any expected elements are ignored.
failIfCandidateMappingHasMissing
java
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
Apache-2.0
private boolean failIfOneToOneMappingHasMissing( List<? extends A> actual, List<? extends E> expected, BiMap<Integer, Integer> mapping, Correspondence.ExceptionStore exceptions) { List<? extends E> missing = findNotIndexed(expected, mapping.values()); if (!missing.isEmpty()) { List<? extends A> extra = findNotIndexed(actual, mapping.keySet()); subject.failWithoutActual( ImmutableList.<Fact>builder() .add( simpleFact( "in an assertion requiring a 1:1 mapping between the expected and a subset" + " of the actual elements, each actual element matches as least one" + " expected element, and vice versa, but there was no 1:1 mapping")) .add( simpleFact( "using the most complete 1:1 mapping (or one such mapping, if there is a" + " tie)")) .addAll(describeMissing(missing, extra, exceptions)) .add(fact("expected to contain at least", expected)) .addAll(correspondence.describeForIterable()) .add(subject.butWas()) .addAll(exceptions.describeAsAdditionalInfo()) .build()); return true; } return false; }
Given a list of expected elements, and a 1:1 mapping between actual and expected elements specified as a bimap of indexes into the actual list to indexes into the expected list, checks that every expected element maps to an actual element. Actual elements which do not map to any expected elements are ignored.
failIfOneToOneMappingHasMissing
java
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
Apache-2.0
@Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<LongStreamSubject, LongStream> longStreams() { return LongStreamSubject::new; }
Obsolete factory instance. This factory was previously necessary for assertions like {@code assertWithMessage(...).about(longStreams()).that(stream)....}. Now, you can perform assertions like that without the {@code about(...)} call. @deprecated Instead of {@code about(longStreams()).that(...)}, use just {@code that(...)}. Similarly, instead of {@code assertAbout(longStreams()).that(...)}, use just {@code assertThat(...)}.
longStreams
java
google/truth
core/src/main/java/com/google/common/truth/LongStreamSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/LongStreamSubject.java
Apache-2.0
@Deprecated @Override public boolean equals(@Nullable Object o) { throw new UnsupportedOperationException( "If you meant to compare longs, use .of(long) instead."); }
@throws UnsupportedOperationException always @deprecated {@link Object#equals(Object)} is not supported on TolerantLongComparison. If you meant to compare longs, use {@link #of(long)} instead.
equals
java
google/truth
core/src/main/java/com/google/common/truth/LongSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/LongSubject.java
Apache-2.0
@Override @Deprecated public final void isEquivalentAccordingToCompareTo(@Nullable Long other) { super.isEquivalentAccordingToCompareTo(other); }
@deprecated Use {@link #isEqualTo} instead. Long comparison is consistent with equality.
isEquivalentAccordingToCompareTo
java
google/truth
core/src/main/java/com/google/common/truth/LongSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/LongSubject.java
Apache-2.0
public final void isNotEmpty() { if (checkNotNull(actual).isEmpty()) { failWithoutActual(simpleFact("expected not to be empty")); } }
Checks that the actual map is not empty.
isNotEmpty
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
public final void hasSize(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize (%s) must be >= 0", expectedSize); check("size()").that(checkNotNull(actual).size()).isEqualTo(expectedSize); }
Checks that the actual map has the given size.
hasSize
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
public final void containsEntry(@Nullable Object key, @Nullable Object value) { Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value); checkNotNull(actual); if (!actual.entrySet().contains(entry)) { List<@Nullable Object> keyList = singletonList(key); List<@Nullable Object> valueList = singletonList(value); if (actual.containsKey(key)) { Object actualValue = actual.get(key); if (Objects.equals(actualValue, value)) { /* * `contains(entry(key, value))` returned `false`, but `get(key)` returned a result equal * to `value`. We're probably looking at an `IdentityHashMap`, which compares values (not * just keys!) using `==`. * * `IdentityHashMap` isn't following the contract for `Map`, so we're within our rights to * do whatever we want. But it's probably simplest for us and best for users if we just * make the assertion pass: While users probably *do* want us to follow the * `IdentityHashMap` behavior of comparing *keys* with `==`, they probably *don't* want us * to follow the same behavior for *values*. */ return; } /* * In the case of a null expected or actual map, clarify that the key *is* present and * *is* expected to be present. That is, get() isn't returning null to indicate that the key * is missing, and the user isn't making an assertion that the key is missing. */ StandardSubjectBuilder check = check("get(%s)", key); if (value == null || actualValue == null) { check = check.withMessage("key is present but with a different value"); } // See the comment on IterableSubject's use of failEqualityCheckForEqualsWithoutDescription. check.that(actualValue).failEqualityCheckForEqualsWithoutDescription(value); } else if (hasMatchingToStringPair(actual.keySet(), keyList)) { failWithoutActual( fact("expected to contain entry", entry), fact("an instance of", objectToTypeName(entry)), simpleFact("but did not"), fact( "though it did contain keys", countDuplicatesAndAddTypeInfo( retainMatchingToString(actual.keySet(), /* itemsToCheck= */ keyList))), fact("full contents", actualCustomStringRepresentationForPackageMembersToCall())); } else if (actual.containsValue(value)) { Set<@Nullable Object> keys = new LinkedHashSet<>(); for (Map.Entry<?, ?> actualEntry : actual.entrySet()) { if (Objects.equals(actualEntry.getValue(), value)) { keys.add(actualEntry.getKey()); } } failWithoutActual( fact("expected to contain entry", entry), simpleFact("but did not"), fact("though it did contain keys with that value", keys), fact("full contents", actualCustomStringRepresentationForPackageMembersToCall())); } else if (hasMatchingToStringPair(actual.values(), valueList)) { failWithoutActual( fact("expected to contain entry", entry), fact("an instance of", objectToTypeName(entry)), simpleFact("but did not"), fact( "though it did contain values", countDuplicatesAndAddTypeInfo( retainMatchingToString(actual.values(), /* itemsToCheck= */ valueList))), fact("full contents", actualCustomStringRepresentationForPackageMembersToCall())); } else { failWithActual("expected to contain entry", entry); } } }
Checks that the actual map contains the given entry.
containsEntry
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
public final void doesNotContainEntry(@Nullable Object key, @Nullable Object value) { checkNoNeedToDisplayBothValues("entrySet()") .that(checkNotNull(actual).entrySet()) .doesNotContain(immutableEntry(key, value)); }
Checks that the actual map does not contain the given entry.
doesNotContainEntry
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
@CanIgnoreReturnValue public final Ordered containsExactlyEntriesIn(Map<?, ?> expectedMap) { if (expectedMap.isEmpty()) { if (checkNotNull(actual).isEmpty()) { return IN_ORDER; } else { isEmpty(); // fails return ALREADY_FAILED; } } boolean containsAnyOrder = containsEntriesInAnyOrder(expectedMap, /* allowUnexpected= */ false); if (containsAnyOrder) { return MapInOrder.create( this, expectedMap, /* allowUnexpected= */ false, /* correspondence= */ null); } else { return ALREADY_FAILED; } }
Checks that the actual map contains exactly the given set of entries in the given map.
containsExactlyEntriesIn
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
public final <A extends @Nullable Object, E extends @Nullable Object> UsingCorrespondence<A, E> comparingValuesUsing( Correspondence<? super A, ? super E> correspondence) { return UsingCorrespondence.create(this, correspondence); }
Starts a method chain for a check in which the actual values (i.e. the values of the {@link Map} under test) are compared to expected values using the given {@link Correspondence}. The actual values must be of type {@code A}, the expected values must be of type {@code E}. The check is actually executed by continuing the method chain. For example: <pre>{@code assertThat(actualMap) .comparingValuesUsing(correspondence) .containsEntry(expectedKey, expectedValue); }</pre> where {@code actualMap} is a {@code Map<?, A>} (or, more generally, a {@code Map<?, ? extends A>}), {@code correspondence} is a {@code Correspondence<A, E>}, and {@code expectedValue} is an {@code E}. <p>Note that keys will always be compared with regular object equality ({@link Object#equals}). <p>Any of the methods on the returned object may throw {@link ClassCastException} if they encounter an actual map that is not of type {@code A} or an expected value that is not of type {@code E}.
comparingValuesUsing
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
public final <V extends @Nullable Object> UsingCorrespondence<V, V> formattingDiffsUsing( DiffFormatter<? super V, ? super V> formatter) { return comparingValuesUsing(Correspondence.<V>equality().formattingDiffsUsing(formatter)); }
Starts a method chain for a check in which failure messages may use the given {@link DiffFormatter} to describe the difference between an actual map (i.e. a value in the {@link Map} under test) and the value it is expected to be equal to, but isn't. The actual and expected values must be of type {@code V}. The check is actually executed by continuing the method chain. For example: <pre>{@code assertThat(actualMap) .formattingDiffsUsing(FooTestHelper::formatDiff) .containsExactly(key1, foo1, key2, foo2, key3, foo3); }</pre> where {@code actualMap} is a {@code Map<?, Foo>} (or, more generally, a {@code Map<?, ? extends Foo>}), {@code FooTestHelper.formatDiff} is a static method taking two {@code Foo} arguments and returning a {@link String}, and {@code foo1}, {@code foo2}, and {@code foo3} are {@code Foo} instances. <p>Unlike when using {@link #comparingValuesUsing}, the values are still compared using object equality, so this method does not affect whether a test passes or fails. <p>Any of the methods on the returned object may throw {@link ClassCastException} if they encounter a value that is not of type {@code V}. @since 1.1
formattingDiffsUsing
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
@SuppressWarnings("UnnecessaryCast") // needed by nullness checker public void containsEntry(@Nullable Object expectedKey, E expectedValue) { if (checkNotNull(actual).containsKey(expectedKey)) { // Found matching key. A actualValue = getCastSubject().get(expectedKey); Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues(); if (correspondence.safeCompare((A) actualValue, expectedValue, exceptions)) { // The expected key had the expected value. There's no need to check exceptions here, // because if Correspondence.compare() threw then safeCompare() would return false. return; } // Found matching key with non-matching value. String diff = correspondence.safeFormatDiff((A) actualValue, expectedValue, exceptions); if (diff != null) { failWithoutActual( ImmutableList.<Fact>builder() .add(fact("for key", expectedKey)) .add(fact("expected value", expectedValue)) .addAll(correspondence.describeForMapValues()) .add(fact("but got value", actualValue)) .add(fact("diff", diff)) .add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } else { failWithoutActual( ImmutableList.<Fact>builder() .add(fact("for key", expectedKey)) .add(fact("expected value", expectedValue)) .addAll(correspondence.describeForMapValues()) .add(fact("but got value", actualValue)) .add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } } else { // Did not find matching key. Look for the matching value with a different key. Set<@Nullable Object> keys = new LinkedHashSet<>(); Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues(); for (Map.Entry<?, A> actualEntry : getCastSubject().entrySet()) { if (correspondence.safeCompare(actualEntry.getValue(), expectedValue, exceptions)) { keys.add(actualEntry.getKey()); } } if (!keys.isEmpty()) { // Found matching values with non-matching keys. failWithoutActual( ImmutableList.<Fact>builder() .add(fact("for key", expectedKey)) .add(fact("expected value", expectedValue)) .addAll(correspondence.describeForMapValues()) .add(simpleFact("but was missing")) .add(fact("other keys with matching values", keys)) .add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } else { // Did not find matching key or value. failWithoutActual( ImmutableList.<Fact>builder() .add(fact("for key", expectedKey)) .add(fact("expected value", expectedValue)) .addAll(correspondence.describeForMapValues()) .add(simpleFact("but was missing")) .add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } } }
Checks that the actual map contains an entry with the given key and a value that corresponds to the given value.
containsEntry
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
@SuppressWarnings("UnnecessaryCast") // needed by nullness checker public void doesNotContainEntry(@Nullable Object excludedKey, E excludedValue) { if (checkNotNull(actual).containsKey(excludedKey)) { // Found matching key. Fail if the value matches, too. A actualValue = getCastSubject().get(excludedKey); Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues(); if (correspondence.safeCompare((A) actualValue, excludedValue, exceptions)) { // The matching key had a matching value. There's no need to check exceptions here, // because if Correspondence.compare() threw then safeCompare() would return false. failWithoutActual( ImmutableList.<Fact>builder() .add(fact("expected not to contain", immutableEntry(excludedKey, excludedValue))) .addAll(correspondence.describeForMapValues()) .add( fact( "but contained", Maps.<@Nullable Object, @Nullable A>immutableEntry( excludedKey, actualValue))) .add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } // The value didn't match, but we still need to fail if we hit an exception along the way. if (exceptions.hasCompareException()) { failWithoutActual( ImmutableList.<Fact>builder() .addAll(exceptions.describeAsMainCause()) .add(fact("expected not to contain", immutableEntry(excludedKey, excludedValue))) .addAll(correspondence.describeForMapValues()) .add(simpleFact("found no match (but failing because of exception)")) .add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall())) .build()); } } }
Checks that the actual map does not contain an entry with the given key and a value that corresponds to the given value.
doesNotContainEntry
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
@CanIgnoreReturnValue public Ordered containsExactly(@Nullable Object k0, @Nullable E v0, @Nullable Object... rest) { @SuppressWarnings("unchecked") // throwing ClassCastException is the correct behaviour Map<Object, E> expectedMap = (Map<Object, E>) accumulateMap("containsExactly", k0, v0, rest); return containsExactlyEntriesIn(expectedMap); }
Checks that the actual map contains exactly the given set of keys mapping to values that correspond to the given values. <p>The values must all be of type {@code E}, and a {@link ClassCastException} will be thrown if any other type is encountered. <p><b>Warning:</b> the use of varargs means that we cannot guarantee an equal number of key/value pairs at compile time. Please make sure you provide varargs in key/value pairs!
containsExactly
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
@CanIgnoreReturnValue public Ordered containsAtLeast(@Nullable Object k0, @Nullable E v0, @Nullable Object... rest) { @SuppressWarnings("unchecked") // throwing ClassCastException is the correct behaviour Map<Object, E> expectedMap = (Map<Object, E>) accumulateMap("containsAtLeast", k0, v0, rest); return containsAtLeastEntriesIn(expectedMap); }
Checks that the actual map contains at least the given set of keys mapping to values that correspond to the given values. <p>The values must all be of type {@code E}, and a {@link ClassCastException} will be thrown if any other type is encountered. <p><b>Warning:</b> the use of varargs means that we cannot guarantee an equal number of key/value pairs at compile time. Please make sure you provide varargs in key/value pairs!
containsAtLeast
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
@CanIgnoreReturnValue public Ordered containsExactlyEntriesIn(Map<?, ? extends E> expectedMap) { if (expectedMap.isEmpty()) { if (checkNotNull(actual).isEmpty()) { return IN_ORDER; } else { subject.isEmpty(); // fails return ALREADY_FAILED; } } return internalContainsEntriesIn(expectedMap, /* allowUnexpected= */ false); }
Checks that the actual map contains exactly the keys in the given map, mapping to values that correspond to the values of the given map.
containsExactlyEntriesIn
java
google/truth
core/src/main/java/com/google/common/truth/MapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MapSubject.java
Apache-2.0
static void checkTolerance(double tolerance) { checkArgument(!Double.isNaN(tolerance), "tolerance cannot be NaN"); checkArgument( Double.compare(tolerance, 0.0) >= 0, "tolerance (%s) cannot be negative", tolerance); checkArgument(tolerance != Double.POSITIVE_INFINITY, "tolerance cannot be POSITIVE_INFINITY"); }
Ensures that the given tolerance is a non-negative finite value, i.e. not {@code Double.NaN}, {@code Double.POSITIVE_INFINITY}, or negative, including {@code -0.0}.
checkTolerance
java
google/truth
core/src/main/java/com/google/common/truth/MathUtil.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MathUtil.java
Apache-2.0
public final void hasSize(int expectedSize) { checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize); check("size()").that(checkNotNull(actual).size()).isEqualTo(expectedSize); }
Checks that the actual multimap has the given size.
hasSize
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
public final void containsEntry(@Nullable Object key, @Nullable Object value) { // TODO(kak): Can we share any of this logic w/ MapSubject.containsEntry()? checkNotNull(actual); if (!actual.containsEntry(key, value)) { Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value); ImmutableList<Map.Entry<@Nullable Object, @Nullable Object>> entryList = ImmutableList.of(entry); // TODO(cpovirk): If the key is present but not with the right value, we could fail using // something like valuesForKey(key).contains(value). Consider whether this is worthwhile. if (hasMatchingToStringPair(actual.entries(), entryList)) { failWithoutActual( fact("expected to contain entry", entry), fact("an instance of", objectToTypeName(entry)), simpleFact("but did not"), fact( "though it did contain", countDuplicatesAndAddTypeInfo( retainMatchingToString(actual.entries(), /* itemsToCheck= */ entryList))), fact("full contents", actualCustomStringRepresentationForPackageMembersToCall())); } else if (actual.containsKey(key)) { failWithoutActual( fact("expected to contain entry", entry), simpleFact("but did not"), fact("though it did contain values with that key", actual.asMap().get(key)), fact("full contents", actualCustomStringRepresentationForPackageMembersToCall())); } else if (actual.containsValue(value)) { Set<@Nullable Object> keys = new LinkedHashSet<>(); for (Map.Entry<?, ?> actualEntry : actual.entries()) { if (Objects.equals(actualEntry.getValue(), value)) { keys.add(actualEntry.getKey()); } } failWithoutActual( fact("expected to contain entry", entry), simpleFact("but did not"), fact("though it did contain keys with that value", keys), fact("full contents", actualCustomStringRepresentationForPackageMembersToCall())); } else { failWithActual("expected to contain entry", immutableEntry(key, value)); } } }
Checks that the actual multimap contains the given entry.
containsEntry
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
public final void doesNotContainEntry(@Nullable Object key, @Nullable Object value) { checkNoNeedToDisplayBothValues("entries()") .that(checkNotNull(actual).entries()) .doesNotContain(immutableEntry(key, value)); }
Checks that the actual multimap does not contain the given entry.
doesNotContainEntry
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
@CanIgnoreReturnValue public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); ListMultimap<?, ?> extra = difference(actual, expectedMultimap); // TODO(kak): Possible enhancement: Include "[1 copy]" if the element does appear in // the actual multimap but not enough times. Similarly for unexpected extra items. if (!missing.isEmpty()) { if (!extra.isEmpty()) { boolean addTypeInfo = hasMatchingToStringPair(missing.entries(), extra.entries()); // Note: The usage of countDuplicatesAndAddTypeInfo() below causes entries no longer to be // grouped by key in the 'missing' and 'unexpected items' parts of the message (we still // show the actual and expected multimaps in the standard format). String missingDisplay = addTypeInfo ? countDuplicatesAndAddTypeInfo(annotateEmptyStringsMultimap(missing).entries()) : countDuplicatesMultimap(annotateEmptyStringsMultimap(missing)); String extraDisplay = addTypeInfo ? countDuplicatesAndAddTypeInfo(annotateEmptyStringsMultimap(extra).entries()) : countDuplicatesMultimap(annotateEmptyStringsMultimap(extra)); failWithActual( fact("missing", missingDisplay), fact("unexpected", extraDisplay), simpleFact("---"), fact("expected", annotateEmptyStringsMultimap(expectedMultimap))); return ALREADY_FAILED; } else { failWithActual( fact("missing", countDuplicatesMultimap(annotateEmptyStringsMultimap(missing))), simpleFact("---"), fact("expected", annotateEmptyStringsMultimap(expectedMultimap))); return ALREADY_FAILED; } } else if (!extra.isEmpty()) { failWithActual( fact("unexpected", countDuplicatesMultimap(annotateEmptyStringsMultimap(extra))), simpleFact("---"), fact("expected", annotateEmptyStringsMultimap(expectedMultimap))); return ALREADY_FAILED; } return MultimapInOrder.create(this, /* allowUnexpected= */ false, expectedMultimap); }
Checks that the actual multimap contains precisely the same entries as the argument {@link Multimap}. <p>A subsequent call to {@link Ordered#inOrder} may be made if the caller wishes to verify that the two multimaps iterate fully in the same order. That is, their key sets iterate in the same order, and the value collections for each key iterate in the same order.
containsExactlyEntriesIn
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
@CanIgnoreReturnValue public final Ordered containsAtLeastEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); // TODO(kak): Possible enhancement: Include "[1 copy]" if the element does appear in // the actual multimap but not enough times. Similarly for unexpected extra items. if (!missing.isEmpty()) { failWithActual( fact("missing", countDuplicatesMultimap(annotateEmptyStringsMultimap(missing))), simpleFact("---"), fact("expected to contain at least", annotateEmptyStringsMultimap(expectedMultimap))); return ALREADY_FAILED; } return MultimapInOrder.create(this, /* allowUnexpected= */ true, expectedMultimap); }
Checks that the actual multimap contains at least the entries in the argument {@link Multimap}. <p>A subsequent call to {@link Ordered#inOrder} may be made if the caller wishes to verify that the entries are present in the same order as given. That is, the keys are present in the given order in the key set, and the values for each key are present in the given order order in the value collections.
containsAtLeastEntriesIn
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
private static Multimap<?, ?> annotateEmptyStringsMultimap(Multimap<?, ?> multimap) { if (multimap.containsKey("") || multimap.containsValue("")) { ListMultimap<@Nullable Object, @Nullable Object> annotatedMultimap = LinkedListMultimap.create(); for (Map.Entry<?, ?> entry : multimap.entries()) { Object key = Objects.equals(entry.getKey(), "") ? HUMAN_UNDERSTANDABLE_EMPTY_STRING : entry.getKey(); Object value = Objects.equals(entry.getValue(), "") ? HUMAN_UNDERSTANDABLE_EMPTY_STRING : entry.getValue(); annotatedMultimap.put(key, value); } return annotatedMultimap; } else { return multimap; } }
Returns a multimap with all empty strings (as keys or values) replaced by a non-empty human understandable indicator for an empty string. <p>Returns the given multimap if it contains no empty strings.
annotateEmptyStringsMultimap
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
public <A extends @Nullable Object, E extends @Nullable Object> UsingCorrespondence<A, E> comparingValuesUsing( Correspondence<? super A, ? super E> correspondence) { return UsingCorrespondence.create(this, correspondence); }
Starts a method chain for a check in which the actual values (i.e. the values of the {@link Multimap} under test) are compared to expected values using the given {@link Correspondence}. The actual values must be of type {@code A}, and the expected values must be of type {@code E}. The check is actually executed by continuing the method chain. For example: <pre>{@code assertThat(actualMultimap) .comparingValuesUsing(correspondence) .containsEntry(expectedKey, expectedValue); }</pre> where {@code actualMultimap} is a {@code Multimap<?, A>} (or, more generally, a {@code Multimap<?, ? extends A>}), {@code correspondence} is a {@code Correspondence<A, E>}, and {@code expectedValue} is an {@code E}. <p>Note that keys will always be compared with regular object equality ({@link Object#equals}). <p>Any of the methods on the returned object may throw {@link ClassCastException} if they encounter an actual multimap that is not of type {@code A}.
comparingValuesUsing
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
@SuppressWarnings("nullness") // TODO: b/423853632 - Remove after checker is fixed. public void containsEntry(@Nullable Object expectedKey, E expectedValue) { if (checkNotNull(actual).containsKey(expectedKey)) { // Found matching key. Collection<A> actualValues = checkNotNull(getCastActual().asMap().get(expectedKey)); Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues(); for (A actualValue : actualValues) { if (correspondence.safeCompare(actualValue, expectedValue, exceptions)) { // Found matching key and value, but we still need to fail if we hit an exception along // the way. if (exceptions.hasCompareException()) { failWithoutActual( ImmutableList.<Fact>builder() .addAll(exceptions.describeAsMainCause()) .add( fact( "expected to contain entry", immutableEntry(expectedKey, expectedValue))) .addAll(correspondence.describeForMapValues()) .add( fact( "found match (but failing because of exception)", immutableEntry(expectedKey, actualValue))) .add( fact( "full contents", actualCustomStringRepresentationForPackageMembersToCall())) .build()); } return; } } // Found matching key with non-matching values. failWithoutActual( ImmutableList.<Fact>builder() .add(fact("expected to contain entry", immutableEntry(expectedKey, expectedValue))) .addAll(correspondence.describeForMapValues()) .add(simpleFact("but did not")) .add(fact("though it did contain values for that key", actualValues)) .add( fact( "full contents", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } else { // Did not find matching key. Set<Map.Entry<?, ?>> entries = new LinkedHashSet<>(); Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues(); for (Map.Entry<?, A> actualEntry : getCastActual().entries()) { if (correspondence.safeCompare(actualEntry.getValue(), expectedValue, exceptions)) { entries.add(actualEntry); } } if (!entries.isEmpty()) { // Found matching values with non-matching keys. failWithoutActual( ImmutableList.<Fact>builder() .add( fact("expected to contain entry", immutableEntry(expectedKey, expectedValue))) .addAll(correspondence.describeForMapValues()) .add(simpleFact("but did not")) // The corresponding failure in the non-Correspondence case reports the keys // mapping to the expected value. Here, we show the full entries, because for some // Correspondences it may not be obvious which of the actual values it was that // corresponded to the expected value. .add(fact("though it did contain entries with matching values", entries)) .add( fact( "full contents", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } else { // Did not find matching key or value. failWithoutActual( ImmutableList.<Fact>builder() .add( fact("expected to contain entry", immutableEntry(expectedKey, expectedValue))) .addAll(correspondence.describeForMapValues()) .add(simpleFact("but did not")) .add( fact( "full contents", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } } }
Checks that the actual multimap contains an entry with the given key and a value that corresponds to the given value.
containsEntry
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
public void doesNotContainEntry(@Nullable Object excludedKey, E excludedValue) { if (checkNotNull(actual).containsKey(excludedKey)) { Collection<A> actualValues = checkNotNull(getCastActual().asMap().get(excludedKey)); List<A> matchingValues = new ArrayList<>(); Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues(); for (A actualValue : actualValues) { if (correspondence.safeCompare(actualValue, excludedValue, exceptions)) { matchingValues.add(actualValue); } } // Fail if we found a matching value for the key. if (!matchingValues.isEmpty()) { failWithoutActual( ImmutableList.<Fact>builder() .add( fact( "expected not to contain entry", immutableEntry(excludedKey, excludedValue))) .addAll(correspondence.describeForMapValues()) .add(fact("but contained that key with matching values", matchingValues)) .add( fact( "full contents", actualCustomStringRepresentationForPackageMembersToCall())) .addAll(exceptions.describeAsAdditionalInfo()) .build()); } else { // No value matched, but we still need to fail if we hit an exception along the way. if (exceptions.hasCompareException()) { failWithoutActual( ImmutableList.<Fact>builder() .addAll(exceptions.describeAsMainCause()) .add( fact( "expected not to contain entry", immutableEntry(excludedKey, excludedValue))) .addAll(correspondence.describeForMapValues()) .add(simpleFact("found no match (but failing because of exception)")) .add( fact( "full contents", actualCustomStringRepresentationForPackageMembersToCall())) .build()); } } } }
Checks that the actual multimap does not contain an entry with the given key and a value that corresponds to the given value.
doesNotContainEntry
java
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/MultimapSubject.java
Apache-2.0
@SuppressWarnings("nullness") static <T extends @Nullable Object> T uncheckedCastNullableTToT(@Nullable T t) { return t; }
Accepts a {@code @Nullable T} and returns a plain {@code T}, without performing any check that that conversion is safe. <p>This method is intended to help with usages of type parameters that have parametric nullness. If a type parameter instead ranges over only non-null types (or if the type is a non-variable type, like {@code String}), then code should almost never use this method, preferring instead to call {@code requireNonNull} so as to benefit from its runtime check. <p>An example use case for this method is in implementing an {@code Iterator<T>} whose {@code next} field is lazily initialized. The type of that field would be {@code @Nullable T}, and the code would be responsible for populating a "real" {@code T} (which might still be the value {@code null}!) before returning it to callers. Depending on how the code is structured, a nullness analysis might not understand that the field has been populated. To avoid that problem without having to add {@code @SuppressWarnings}, the code can call this method. <p>Why <i>not</i> just add {@code SuppressWarnings}? The problem is that this method is typically useful for {@code return} statements. That leaves the code with two options: Either add the suppression to the whole method (which turns off checking for a large section of code), or extract a variable, and put the suppression on that. However, a local variable typically doesn't work: Because nullness analyses typically infer the nullness of local variables, there's no way to assign a {@code @Nullable T} to a field {@code T foo;} and instruct the analysis that that means "plain {@code T}" rather than the inferred type {@code @Nullable T}. (Even if supported added {@code @NonNull}, that would not help, since the problem case addressed by this method is the case in which {@code T} has parametric nullness -- and thus its value may be legitimately {@code null}.)
uncheckedCastNullableTToT
java
google/truth
core/src/main/java/com/google/common/truth/NullnessCasts.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/NullnessCasts.java
Apache-2.0
public IterableSubject asList() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(ImmutableList.of()); } return checkNoNeedToDisplayBothValues("asList()").that(Arrays.asList(actual)); }
A subject for {@code Object[]} and more generically {@code T[]}. @author Christian Gruber
asList
java
google/truth
core/src/main/java/com/google/common/truth/ObjectArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ObjectArraySubject.java
Apache-2.0
public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } }
Checks that the actual {@link OptionalDouble} contains a value.
isPresent
java
google/truth
core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java
Apache-2.0
public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", doubleToString(actual.getAsDouble()))); } }
Checks that the actual {@link OptionalDouble} does not contain a value.
isEmpty
java
google/truth
core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java
Apache-2.0
@Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalDoubleSubject, OptionalDouble> optionalDoubles() { return OptionalDoubleSubject::new; }
Obsolete factory instance. This factory was previously necessary for assertions like {@code assertWithMessage(...).about(optionalDoubles()).that(optional)....}. Now, you can perform assertions like that without the {@code about(...)} call. @deprecated Instead of {@code about(optionalDoubles()).that(...)}, use just {@code that(...)}. Similarly, instead of {@code assertAbout(optionalDoubles()).that(...)}, use just {@code assertThat(...)}.
optionalDoubles
java
google/truth
core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalDoubleSubject.java
Apache-2.0
public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.getAsInt())); } }
Checks that the actual {@link OptionalInt} does not contain a value.
isEmpty
java
google/truth
core/src/main/java/com/google/common/truth/OptionalIntSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalIntSubject.java
Apache-2.0
@Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalIntSubject, OptionalInt> optionalInts() { return OptionalIntSubject::new; }
Obsolete factory instance. This factory was previously necessary for assertions like {@code assertWithMessage(...).about(optionalInts()).that(optional)....}. Now, you can perform assertions like that without the {@code about(...)} call. @deprecated Instead of {@code about(optionalInts()).that(...)}, use just {@code that(...)}. Similarly, instead of {@code assertAbout(optionalInts()).that(...)}, use just {@code assertThat(...)}.
optionalInts
java
google/truth
core/src/main/java/com/google/common/truth/OptionalIntSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalIntSubject.java
Apache-2.0
public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.getAsLong())); } }
Checks that the actual {@link OptionalLong} does not contain a value.
isEmpty
java
google/truth
core/src/main/java/com/google/common/truth/OptionalLongSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalLongSubject.java
Apache-2.0
@Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalLongSubject, OptionalLong> optionalLongs() { return OptionalLongSubject::new; }
Obsolete factory instance. This factory was previously necessary for assertions like {@code assertWithMessage(...).about(optionalLongs()).that(optional)....}. Now, you can perform assertions like that without the {@code about(...)} call. @deprecated Instead of {@code about(optionalLongs()).that(...)}, use just {@code that(...)}. Similarly, instead of {@code assertAbout(optionalLongs()).that(...)}, use just {@code assertThat(...)}.
optionalLongs
java
google/truth
core/src/main/java/com/google/common/truth/OptionalLongSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalLongSubject.java
Apache-2.0
@Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalSubject, Optional<?>> optionals() { return OptionalSubject::new; }
Obsolete factory instance. This factory was previously necessary for assertions like {@code assertWithMessage(...).about(paths()).that(path)....}. Now, you can perform assertions like that without the {@code about(...)} call. @deprecated Instead of {@code about(optionals()).that(...)}, use just {@code that(...)}. Similarly, instead of {@code assertAbout(optionals()).that(...)}, use just {@code assertThat(...)}.
optionals
java
google/truth
core/src/main/java/com/google/common/truth/OptionalSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/OptionalSubject.java
Apache-2.0
@Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<PathSubject, Path> paths() { return PathSubject::new; }
Obsolete factory instance. This factory was previously necessary for assertions like {@code assertWithMessage(...).about(paths()).that(path)....}. Now, you can perform assertions like that without the {@code about(...)} call. @deprecated Instead of {@code about(paths()).that(...)}, use just {@code that(...)}. Similarly, instead of {@code assertAbout(paths()).that(...)}, use just {@code assertThat(...)}.
paths
java
google/truth
core/src/main/java/com/google/common/truth/PathSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PathSubject.java
Apache-2.0
static boolean isAndroid() { return checkNotNull(System.getProperty("java.runtime.name", "")).contains("Android"); }
Tests if current platform is Android.
isAndroid
java
google/truth
core/src/main/java/com/google/common/truth/Platform.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Platform.java
Apache-2.0
public IterableSubject asList() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(ImmutableList.of()); } return checkNoNeedToDisplayBothValues("asList()").that(Booleans.asList(actual)); }
A subject for {@code boolean[]}. @author Christian Gruber ([email protected])
asList
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveBooleanArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveBooleanArraySubject.java
Apache-2.0
public IterableSubject asList() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(emptyList()); } return checkNoNeedToDisplayBothValues("asList()").that(Bytes.asList(actual)); }
A subject for {@code byte[]}. @author Kurt Alfred Kluever
asList
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveByteArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveByteArraySubject.java
Apache-2.0
public IterableSubject asList() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(emptyList()); } return checkNoNeedToDisplayBothValues("asList()").that(Chars.asList(actual)); }
A subject for {@code char[]}. @author Christian Gruber ([email protected])
asList
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveCharArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveCharArraySubject.java
Apache-2.0
public DoubleArrayAsIterable usingExactEquality() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(new double[0]).usingExactEquality(); } return DoubleArrayAsIterable.create(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject(actual)); }
Starts a method chain for a check in which the actual values (i.e. the elements of the array under test) are compared to expected elements using a {@link Correspondence} which considers values to correspond if they are exactly equal, with equality defined by {@link Double#equals}. This method is <i>not</i> recommended when the code under test is doing any kind of arithmetic: use {@link #usingTolerance} with a suitable tolerance in that case. (Remember that the exact result of floating point arithmetic is sensitive to apparently trivial changes such as replacing {@code (a + b) + c} with {@code a + (b + c)}, and that unless {@code strictfp} is in force even the result of {@code (a + b) + c} is sensitive to the JVM's choice of precision for the intermediate result.) This method is recommended when the code under test is specified as either copying a value without modification from its input or returning a well-defined literal or constant value. The check is actually executed by continuing the method chain. For example: <pre>{@code assertThat(actualDoubleArray).usingExactEquality().contains(3.14159); }</pre> <p>For convenience, some subsequent methods accept expected values as {@link Number} instances. These numbers must be either of type {@link Double}, {@link Float}, {@link Integer}, or {@link Long}, and if they are {@link Long} then their absolute values must not exceed 2^53 which is just over 9e15. (This restriction ensures that the expected values have exact {@link Double} representations: using exact equality makes no sense if they do not.) <ul> <li>It considers {@link Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, and {@link Double#NaN} to be equal to themselves (contrast with {@code usingTolerance(0.0)} which does not). <li>It does <i>not</i> consider {@code -0.0} to be equal to {@code 0.0} (contrast with {@code usingTolerance(0.0)} which does). <li>The subsequent methods in the chain may throw a {@link NullPointerException} if any expected {@link Double} instance is null. </ul>
usingExactEquality
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveDoubleArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveDoubleArraySubject.java
Apache-2.0
public FloatArrayAsIterable usingExactEquality() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(new float[0]).usingExactEquality(); } return FloatArrayAsIterable.create(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject(actual)); }
Starts a method chain for a check in which the actual values (i.e. the elements of the array under test) are compared to expected elements using a {@link Correspondence} which considers values to correspond if they are exactly equal, with equality defined by {@link Float#equals}. This method is <i>not</i> recommended when the code under test is doing any kind of arithmetic: use {@link #usingTolerance} with a suitable tolerance in that case. (Remember that the exact result of floating point arithmetic is sensitive to apparently trivial changes such as replacing {@code (a + b) + c} with {@code a + (b + c)}, and that unless {@code strictfp} is in force even the result of {@code (a + b) + c} is sensitive to the JVM's choice of precision for the intermediate result.) This method is recommended when the code under test is specified as either copying a value without modification from its input or returning a well-defined literal or constant value. The check is actually executed by continuing the method chain. For example: <pre>{@code assertThat(actualFloatArray).usingExactEquality().contains(3.14159f); }</pre> <p>For convenience, some subsequent methods accept expected values as {@link Number} instances. These numbers must be either of type {@link Float}, {@link Integer}, or {@link Long}, and if they are {@link Integer} or {@link Long} then their absolute values must not exceed 2^24 which is 16,777,216. (This restriction ensures that the expected values have exact {@link Float} representations: using exact equality makes no sense if they do not.) <ul> <li>It considers {@link Float#POSITIVE_INFINITY}, {@link Float#NEGATIVE_INFINITY}, and {@link Float#NaN} to be equal to themselves (contrast with {@code usingTolerance(0.0)} which does not). <li>It does <i>not</i> consider {@code -0.0f} to be equal to {@code 0.0f} (contrast with {@code usingTolerance(0.0)} which does). <li>The subsequent methods in the chain may throw a {@link NullPointerException} if any expected {@link Float} instance is null. </ul>
usingExactEquality
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveFloatArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveFloatArraySubject.java
Apache-2.0
public IterableSubject asList() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(emptyList()); } return checkNoNeedToDisplayBothValues("asList()").that(Ints.asList(actual)); }
A subject for {@code int[]}. @author Christian Gruber ([email protected])
asList
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveIntArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveIntArraySubject.java
Apache-2.0
public IterableSubject asList() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(emptyList()); } return checkNoNeedToDisplayBothValues("asList()").that(Longs.asList(actual)); }
A subject for {@code long[]}. @author Christian Gruber ([email protected])
asList
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveLongArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveLongArraySubject.java
Apache-2.0
public IterableSubject asList() { if (actual == null) { failWithoutActual(simpleFact("cannot perform assertions on the contents of a null array")); return ignoreCheck().that(emptyList()); } return checkNoNeedToDisplayBothValues("asList()").that(Shorts.asList(actual)); }
A subject for {@code short[]}. @author Christian Gruber ([email protected])
asList
java
google/truth
core/src/main/java/com/google/common/truth/PrimitiveShortArraySubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/PrimitiveShortArraySubject.java
Apache-2.0
public SubjectT that(@Nullable ActualT actual) { return subjectFactory.createSubject(metadata, actual); }
In a fluent assertion chain, exposes the most common {@code that} method, which accepts a value under test and returns a {@link Subject}. <p>For more information about the methods in this class, see <a href="https://truth.dev/faq#full-chain">this FAQ entry</a>. <h3>For people extending Truth</h3> <p>You won't extend this type. When you write a custom subject, see <a href="https://truth.dev/extension">our doc on extensions</a>.
that
java
google/truth
core/src/main/java/com/google/common/truth/SimpleSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/SimpleSubjectBuilder.java
Apache-2.0
static void cleanStackTrace(Throwable throwable) { new StackTraceCleaner(throwable).clean(newIdentityHashSet()); }
<b>Call {@link Platform#cleanStackTrace} rather than calling this directly.</b> <p>Cleans the stack trace on the given {@link Throwable}, replacing the original stack trace stored on the instance (see {@link Throwable#setStackTrace(StackTraceElement[])}). <p>Removes Truth stack frames from the top and JUnit framework and reflective call frames from the bottom. Collapses the frames for various frameworks in the middle of the trace as well.
cleanStackTrace
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
@SuppressWarnings("SetAll") // not available under old versions of Android private void clean(Set<Throwable> seenThrowables) { // Stack trace cleaning can be disabled using a system property. if (isStackTraceCleaningDisabled()) { return; } /* * TODO(cpovirk): Consider wrapping this whole method in a try-catch in case there are any bugs. * It would be a shame for us to fail to report the "real" assertion failure because we're * instead reporting a bug in Truth's cosmetic stack cleaning. */ // Prevent infinite recursion if there is a reference cycle between Throwables. if (seenThrowables.contains(throwable)) { return; } seenThrowables.add(throwable); StackTraceElement[] stackFrames = throwable.getStackTrace(); int stackIndex = stackFrames.length - 1; for (; stackIndex >= 0 && !isTruthEntrance(stackFrames[stackIndex]); stackIndex--) { // Find first frame that enters Truth's world, and remove all above. } stackIndex += 1; int endIndex = 0; for (; endIndex < stackFrames.length && !isJUnitIntrastructure(stackFrames[endIndex]); endIndex++) { // Find last frame of setup frames, and remove from there down. } /* * If the stack trace would be empty, the error was probably thrown from "JUnit infrastructure" * frames. Keep those frames around (though much of JUnit itself and related startup frames will * still be removed by the remainder of this method) so that the user sees a useful stack. */ if (stackIndex >= endIndex) { endIndex = stackFrames.length; } for (; stackIndex < endIndex; stackIndex++) { StackTraceElementWrapper stackTraceElementWrapper = new StackTraceElementWrapper(stackFrames[stackIndex]); // Always keep frames that might be useful. if (stackTraceElementWrapper.getStackFrameType() == StackFrameType.NEVER_REMOVE) { endStreak(); cleanedStackTrace.add(stackTraceElementWrapper); continue; } // Otherwise, process the current frame for collapsing addToStreak(stackTraceElementWrapper); lastStackFrameElementWrapper = stackTraceElementWrapper; } // Close out the streak on the bottom of the stack. endStreak(); // Filter out testing framework and reflective calls from the bottom of the stack ListIterator<StackTraceElementWrapper> iterator = cleanedStackTrace.listIterator(cleanedStackTrace.size()); while (iterator.hasPrevious()) { StackTraceElementWrapper stackTraceElementWrapper = iterator.previous(); if (stackTraceElementWrapper.getStackFrameType() == StackFrameType.TEST_FRAMEWORK || stackTraceElementWrapper.getStackFrameType() == StackFrameType.REFLECTION) { iterator.remove(); } else { break; } } // Replace the stack trace on the Throwable with the cleaned one. StackTraceElement[] result = new StackTraceElement[cleanedStackTrace.size()]; for (int i = 0; i < result.length; i++) { result[i] = cleanedStackTrace.get(i).getStackTraceElement(); } throwable.setStackTrace(result); // Recurse on any related Throwables that are attached to this one if (throwable.getCause() != null) { new StackTraceCleaner(throwable.getCause()).clean(seenThrowables); } for (Throwable suppressed : throwable.getSuppressed()) { new StackTraceCleaner(suppressed).clean(seenThrowables); } }
Cleans the stack trace on {@code throwable}, replacing the trace that was originally on it.
clean
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
private void addToStreak(StackTraceElementWrapper stackTraceElementWrapper) { if (stackTraceElementWrapper.getStackFrameType() != currentStreakType) { endStreak(); currentStreakType = stackTraceElementWrapper.getStackFrameType(); currentStreakLength = 1; } else { currentStreakLength++; } }
Either adds the given frame to the running streak or closes out the running streak and starts a new one.
addToStreak
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
private void endStreak() { if (currentStreakLength == 0) { return; } if (currentStreakLength == 1) { // A single frame isn't a streak. Just include the frame as-is in the result. cleanedStackTrace.add(checkNotNull(lastStackFrameElementWrapper)); } else { // Add a single frame to the result summarizing the streak of framework frames cleanedStackTrace.add( createStreakReplacementFrame(checkNotNull(currentStreakType), currentStreakLength)); } clearStreak(); }
Ends the current streak, adding a summary frame to the result. Resets the streak counter.
endStreak
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
StackFrameType getStackFrameType() { return stackFrameType; }
Returns the type of this frame.
getStackFrameType
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
private static StackFrameType forClassName(String fullyQualifiedClassName) { // Never remove the frames from a test class. These will probably be the frame of a failing // assertion. // TODO(cpovirk): This is really only for tests in Truth itself, so this doesn't matter yet, // but.... If the Truth tests someday start calling into nested classes, we may want to add: // || fullyQualifiedClassName.contains("Test$") if (fullyQualifiedClassName.endsWith("Test") && !fullyQualifiedClassName.equals( "androidx.test.internal.runner.junit3.NonLeakyTestSuite$NonLeakyTest")) { return StackFrameType.NEVER_REMOVE; } for (StackFrameType stackFrameType : StackFrameType.values()) { if (stackFrameType.belongsToType(fullyQualifiedClassName)) { return stackFrameType; } } return StackFrameType.NEVER_REMOVE; }
Helper method to determine the frame type from the fully qualified class name.
forClassName
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
String getName() { return name; }
Returns the name of this frame type to display in the cleaned trace
getName
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
boolean belongsToType(String fullyQualifiedClassName) { for (String prefix : prefixes) { // TODO(cpovirk): Should we also check prefix + "$"? if (fullyQualifiedClassName.equals(prefix) || fullyQualifiedClassName.startsWith(prefix + ".")) { return true; } } return false; }
Returns true if the given frame belongs to this frame type based on the package and/or class name of the frame.
belongsToType
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
private static boolean isStackTraceCleaningDisabled() { // Reading system properties might be forbidden. try { return Boolean.parseBoolean( System.getProperty("com.google.common.truth.disable_stack_trace_cleaning")); } catch (SecurityException e) { // Hope for the best. return false; // TODO(cpovirk): Log a warning? Or is that likely to trigger other violations? } }
Returns true if stack trace cleaning is explicitly disabled in a system property. This switch is intended to be used when attempting to debug the frameworks which are collapsed or filtered out of stack traces by the cleaner.
isStackTraceCleaningDisabled
java
google/truth
core/src/main/java/com/google/common/truth/StackTraceCleaner.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StackTraceCleaner.java
Apache-2.0
@SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type public final OptionalSubject that(@Nullable Optional<?> actual) { return about(optionals()).that(actual); }
@since 1.3.0 (with access to {@link OptionalSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final OptionalIntSubject that(@Nullable OptionalInt actual) { return about(optionalInts()).that(actual); }
@since 1.4.0 (with access to {@link OptionalIntSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final OptionalLongSubject that(@Nullable OptionalLong actual) { return about(optionalLongs()).that(actual); }
@since 1.4.0 (with access to {@link OptionalLongSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final OptionalDoubleSubject that(@Nullable OptionalDouble actual) { return about(optionalDoubles()).that(actual); }
@since 1.4.0 (with access to {@link OptionalDoubleSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final StreamSubject that(@Nullable Stream<?> actual) { return about(streams()).that(actual); }
@since 1.3.0 (with access to {@link StreamSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final IntStreamSubject that(@Nullable IntStream actual) { return about(intStreams()).that(actual); }
@since 1.4.0 (with access to {@link IntStreamSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final LongStreamSubject that(@Nullable LongStream actual) { return about(longStreams()).that(actual); }
@since 1.4.0 (with access to {@link LongStreamSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
@GwtIncompatible @J2ObjCIncompatible @J2ktIncompatible public final PathSubject that(@Nullable Path actual) { return about(paths()).that(actual); }
@since 1.4.0 (with access to {@link PathSubject} previously part of {@code truth-java8-extension})
that
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final StandardSubjectBuilder withMessage(@Nullable String messageToPrepend) { return withMessage("%s", messageToPrepend); }
Returns a new instance that will output the given message before the main failure message. If this method is called multiple times, the messages will appear in the order that they were specified.
withMessage
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
public final StandardSubjectBuilder withMessage(String format, @Nullable Object... args) { return new StandardSubjectBuilder(metadata().withMessage(format, args)); }
Returns a new instance that will output the given message before the main failure message. If this method is called multiple times, the messages will appear in the order that they were specified. <p><b>Note:</b> the arguments will be substituted into the format template using {@link com.google.common.base.Strings#lenientFormat Strings.lenientFormat}. Note this only supports the {@code %s} specifier. @throws IllegalArgumentException if the number of placeholders in the format string does not equal the number of given arguments
withMessage
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
private FailureMetadata metadata() { checkStatePreconditions(); return metadataDoNotReferenceDirectly; }
Reports a failure. <p>To set a message, first call {@link #withMessage} (or, more commonly, use the shortcut {@link Truth#assertWithMessage}).
metadata
java
google/truth
core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StandardSubjectBuilder.java
Apache-2.0
@Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<StreamSubject, Stream<?>> streams() { return StreamSubject::new; }
Obsolete factory instance. This factory was previously necessary for assertions like {@code assertWithMessage(...).about(streams()).that(stream)....}. Now, you can perform assertions like that without the {@code about(...)} call. @deprecated Instead of {@code about(streams()).that(...)}, use just {@code that(...)}. Similarly, instead of {@code assertAbout(streams()).that(...)}, use just {@code assertThat(...)}.
streams
java
google/truth
core/src/main/java/com/google/common/truth/StreamSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StreamSubject.java
Apache-2.0
private static Factory<StreamSubject, Stream<?>> streams( Supplier<@Nullable List<?>> listSupplier) { return (metadata, actual) -> new StreamSubject(metadata, actual, listSupplier); }
Factory instance for creating an instance for which we already have a {@code listSupplier} from an existing instance. Naturally, the resulting factory should be used to create an instance only for the stream corresponding to {@code listSupplier}.
streams
java
google/truth
core/src/main/java/com/google/common/truth/StreamSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StreamSubject.java
Apache-2.0
@Override @Deprecated public void isEqualTo(@Nullable Object expected) { /* * We add a warning about stream equality. Doing so is a bit of a pain. (There might be a better * way.) * * We do need to create a StreamSubject (rather than a plain Subject) in order to get our * desired string representation (unless we edit Subject itself to create and expose a * Supplier<List> when given a Stream...). And we have to use a special Factory to avoid * re-collecting the stream. */ substituteCheck() .withMessage( "Warning: Stream equality is based on object identity. To compare Stream" + " contents, use methods like containsExactly.") .about(streams(listSupplier)) .that(actual) .superIsEqualTo(expected); }
@deprecated {@code streamA.isEqualTo(streamB)} always fails, except when passed the exact same stream reference. If you really want to test object identity, you can eliminate this deprecation warning by using {@link #isSameInstanceAs}. If you instead want to test the contents of the stream, use {@link #containsExactly} or similar methods.
isEqualTo
java
google/truth
core/src/main/java/com/google/common/truth/StreamSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StreamSubject.java
Apache-2.0
@Override @Deprecated public void isNotEqualTo(@Nullable Object unexpected) { if (actual() == unexpected) { /* * We override the supermethod's message: That method would ask for both * `String.valueOf(stream)` (for `unexpected`) and `actualCustomStringRepresentation()` (for * `actual()`). The two strings are almost certain to differ, since `valueOf` is normally * based on identity and `actualCustomStringRepresentation()` is based on contents. That can * lead to a confusing error message. * * We could include isEqualTo's warning about Stream's identity-based equality here, too. But * it doesn't seem necessary: The people we really want to warn are the people whose * assertions *pass*. And we've already attempted to do that with deprecation. */ failWithoutActual( fact("expected not to be", actualCustomStringRepresentationForPackageMembersToCall())); return; } /* * But, if the objects aren't identical, we delegate to the supermethod (which checks equals()) * just in case someone has decided to override Stream.equals in a strange way. (I haven't * checked whether this comes up in Google's codebase. I hope that it doesn't.) */ super.isNotEqualTo(unexpected); }
@deprecated {@code streamA.isNotEqualTo(streamB)} always passes, except when passed the exact same stream reference. If you really want to test object identity, you can eliminate this deprecation warning by using {@link #isNotSameInstanceAs}. If you instead want to test the contents of the stream, collect both streams to lists and perform assertions like {@link IterableSubject#isNotEqualTo} on them. In some cases, you may be able to use {@link StreamSubject} assertions like {@link #doesNotContain}.
isNotEqualTo
java
google/truth
core/src/main/java/com/google/common/truth/StreamSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StreamSubject.java
Apache-2.0
@Override @Deprecated public final void isEquivalentAccordingToCompareTo(@Nullable String other) { super.isEquivalentAccordingToCompareTo(other); }
@deprecated Use {@link #isEqualTo} instead. String comparison is consistent with equality.
isEquivalentAccordingToCompareTo
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void hasLength(int expectedLength) { checkArgument(expectedLength >= 0, "expectedLength(%s) must be >= 0", expectedLength); if (actual == null) { failWithActual(fact("expected a string with length", expectedLength)); return; } check("length()").that(actual.length()).isEqualTo(expectedLength); }
Checks that the actual value has the given length.
hasLength
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected an empty string")); } else if (!actual.isEmpty()) { failWithActual(simpleFact("expected to be empty")); } }
Checks that the actual value is the empty string.
isEmpty
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void isNotEmpty() { if (actual == null) { failWithActual(simpleFact("expected a non-empty string")); } else if (actual.isEmpty()) { failWithoutActual(simpleFact("expected not to be empty")); } }
Checks that the actual value is not the empty string.
isNotEmpty
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void contains(@Nullable CharSequence string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that contains", string); } else if (!actual.contains(string)) { failWithActual("expected to contain", string); } }
Checks that the actual value contains the given sequence.
contains
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void doesNotContain(@Nullable CharSequence string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that does not contain", string); } else if (actual.contains(string)) { failWithActual("expected not to contain", string); } }
Checks that the actual value does not contain the given sequence.
doesNotContain
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void startsWith(@Nullable String string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that starts with", string); } else if (!actual.startsWith(string)) { failWithActual("expected to start with", string); } }
Checks that the actual value starts with the given string.
startsWith
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void endsWith(@Nullable String string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that ends with", string); } else if (!actual.endsWith(string)) { failWithActual("expected to end with", string); } }
Checks that the actual value ends with the given string.
endsWith
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public CaseInsensitiveStringComparison ignoringCase() { return CaseInsensitiveStringComparison.create(this); }
Returns a {@link StringSubject}-like instance that will ignore the case of the characters. <p>Character equality ignoring case is defined as follows: Characters must be equal either after calling {@link Character#toLowerCase} or after calling {@link Character#toUpperCase}. Note that this is independent of any locale.
ignoringCase
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void isEqualTo(@Nullable String expected) { if (actual == null) { if (expected != null) { failWithoutActual( fact("expected a string that is equal to", expected), butWas(), simpleFact("(case is ignored)")); } } else { if (expected == null) { failWithoutActual( fact("expected", "null (null reference)"), butWas(), simpleFact("(case is ignored)")); } else if (!actual.equalsIgnoreCase(expected)) { failWithoutActual(fact("expected", expected), butWas(), simpleFact("(case is ignored)")); } } }
Checks that the actual value is equal to the given sequence (while ignoring case). For the purposes of this comparison, two strings are equal if either of the following is true: <ul> <li>They are equal according to {@link String#equalsIgnoreCase}. (In Kotlin terms: They are equal according to <a href="https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/equals.html">{@code actual.equals(expected, ignoreCase = true)}</a>.) <li>They are both null. </ul> <p>Example: "abc" is equal to "ABC", but not to "abcd".
isEqualTo
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void isNotEqualTo(@Nullable String unexpected) { if (actual == null) { if (unexpected == null) { failWithoutActual( fact("expected a string that is not equal to", "null (null reference)"), simpleFact("(case is ignored)")); } } else { if (actual.equalsIgnoreCase(unexpected)) { failWithoutActual( fact("expected not to be", unexpected), butWas(), simpleFact("(case is ignored)")); } } }
Checks that the actual value is not equal to the given string (while ignoring case). The meaning of equality is the same as for the {@link #isEqualTo} method.
isNotEqualTo
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
public void contains(@Nullable CharSequence expectedSequence) { checkNotNull(expectedSequence); String expected = expectedSequence.toString(); if (actual == null) { failWithoutActual( fact("expected a string that contains", expected), butWas(), simpleFact("(case is ignored)")); } else if (!containsIgnoreCase(actual, expected)) { failWithoutActual( fact("expected to contain", expected), butWas(), simpleFact("(case is ignored)")); } }
Checks that the actual value contains the given sequence (while ignoring case).
contains
java
google/truth
core/src/main/java/com/google/common/truth/StringSubject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/StringSubject.java
Apache-2.0
private void standardIsEqualTo(@Nullable Object expected) { ComparisonResult difference = compareForEquality(expected); if (!difference.valuesAreEqual()) { failEqualityCheck(EqualityCheck.EQUAL, expected, difference); } }
Checks that the value under test is equal to the given object. For the purposes of this comparison, two objects are equal if any of the following is true: <ul> <li>they are equal according to {@link Objects#equals} <li>they are arrays and are considered equal by the appropriate {@link Arrays#equals} overload <li>they are boxed integer types ({@code Byte}, {@code Short}, {@code Character}, {@code Integer}, or {@code Long}) and they are numerically equal when converted to {@code Long}. <li>the actual value is a boxed floating-point type ({@code Double} or {@code Float}), the expected value is an {@code Integer}, and the two are numerically equal when converted to {@code Double}. (This allows {@code assertThat(someDouble).isEqualTo(0)} to pass.) </ul> <p><b>Note:</b> This method does not test the {@link Object#equals} implementation itself; it <i>assumes</i> that method is functioning correctly according to its contract. Testing an {@code equals} implementation requires a utility such as <a href="https://mvnrepository.com/artifact/com.google.guava/guava-testlib">guava-testlib</a>'s <a href="https://static.javadoc.io/com.google.guava/guava-testlib/23.0/com/google/common/testing/EqualsTester.html">EqualsTester</a>. <p>In some cases, this method might not even call {@code equals}. It may instead perform other tests that will return the same result as long as {@code equals} is implemented according to the contract for its type.
standardIsEqualTo
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
private void standardIsNotEqualTo(@Nullable Object unexpected) { ComparisonResult difference = compareForEquality(unexpected); if (difference.valuesAreEqual()) { String unexpectedAsString = formatActualOrExpected(unexpected); if (actualCustomStringRepresentation().equals(unexpectedAsString)) { failWithoutActual(fact("expected not to be", unexpectedAsString)); } else { failWithoutActual( fact("expected not to be", unexpectedAsString), fact( "but was; string representation of actual value", actualCustomStringRepresentation())); } } }
Checks that the value under test is not equal to the given object. The meaning of equality is the same as for the {@link #isEqualTo} method.
standardIsNotEqualTo
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
public final void isSameInstanceAs(@Nullable Object expected) { if (actual != expected) { failEqualityCheck( SAME_INSTANCE, expected, /* * Pass through *whether* the values are equal so that failEqualityCheck() can print that * information. But remove the description of the difference, which is always about * content, since people calling isSameInstanceAs() are explicitly not interested in * content, only object identity. */ compareForEquality(expected).withoutDescription()); } }
Checks that the value under test is the same instance as the given object. <p>This method considers {@code null} to be "the same instance as" {@code null} and not the same instance as anything else.
isSameInstanceAs
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
public final void isNotSameInstanceAs(@Nullable Object unexpected) { if (actual == unexpected) { /* * We use actualCustomStringRepresentation() because it might be overridden to be better than * actual.toString()/unexpected.toString(). */ failWithoutActual( fact("expected not to be specific instance", actualCustomStringRepresentation())); } }
Checks that the value under test is not the same instance as the given object. <p>This method considers {@code null} to be "the same instance as" {@code null} and not the same instance as anything else.
isNotSameInstanceAs
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (actual == null) { failWithActual("expected instance of", clazz.getName()); return; } if (!isInstanceOfType(actual, clazz)) { if (Platform.classMetadataUnsupported()) { throw new UnsupportedOperationException( actualCustomStringRepresentation() + ", an instance of " + actual.getClass().getName() + ", may or may not be an instance of " + clazz.getName() + ". Under -XdisableClassMetadata, we do not have enough information to tell."); } failWithoutActual( fact("expected instance of", clazz.getName()), fact("but was instance of", actual.getClass().getName()), fact("with value", actualCustomStringRepresentation())); } }
Checks that the value under test is an instance of the given class.
isInstanceOf
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
public void isAnyOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) { isIn(accumulate(first, second, rest)); }
Checks that the value under test is equal to any of the given elements.
isAnyOf
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
public void isNotIn(@Nullable Iterable<?> iterable) { checkNotNull(iterable); if (Iterables.contains(iterable, actual)) { failWithActual("expected not to be any of", iterable); } }
Checks that the value under test is not equal to any element in the given iterable.
isNotIn
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
public void isNoneOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) { isNotIn(accumulate(first, second, rest)); }
Checks that the value under test is not equal to any of the given elements.
isNoneOf
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
final @Nullable Object actual() { return actual; }
Returns the actual value under test.
actual
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
static ComparisonResult fromEqualsResult(boolean equal) { return equal ? EQUAL : DIFFERENT_NO_DESCRIPTION; }
If {@code equal} is true, returns an equal result; if false, a non-equal result with no description.
fromEqualsResult
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
static ComparisonResult differentWithDescription(Fact... facts) { return new ComparisonResult(ImmutableList.copyOf(facts)); }
Returns a non-equal result with the given description.
differentWithDescription
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
ComparisonResult withoutDescription() { return fromEqualsResult(valuesAreEqual()); }
Returns an instance with the same "equal"/"not-equal" bit but with no description.
withoutDescription
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
private static ComparisonResult checkByteArrayEquals(byte[] expected, byte[] actual) { if (Arrays.equals(expected, actual)) { return ComparisonResult.equal(); } return ComparisonResult.differentWithDescription( fact("expected", Arrays.toString(expected)), fact("but was", Arrays.toString(actual))); }
Returns {@link ComparisonResult#equal} if the arrays are equal. If not equal, returns a string comparing the two arrays, displaying them in the style "[1, 2, 3]" to supplement the main failure message, which uses the style "010203."
checkByteArrayEquals
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0
@Deprecated final StandardSubjectBuilder check() { return new StandardSubjectBuilder(metadata.updateForCheckCall()); }
Returns a builder for creating a derived subject but without providing information about how the derived subject will relate to the current subject. In most cases, you should provide such information by using {@linkplain #check(String, Object...) the other overload}. @deprecated Use {@linkplain #check(String, Object...) the other overload}, which requires you to supply more information to include in any failure messages.
check
java
google/truth
core/src/main/java/com/google/common/truth/Subject.java
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Subject.java
Apache-2.0