
Shuu12121/CodeModernBERT-Owl-4.1
Fill-Mask
•
0.2B
•
Updated
•
102
code
stringlengths 25
201k
| docstring
stringlengths 19
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
55
| path
stringlengths 11
314
| url
stringlengths 62
377
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
static @Nullable String describeActualValue(String className, String methodName, int lineNumber) {
InferenceClassVisitor visitor;
try {
// TODO(cpovirk): Verify that methodName is correct for constructors and static initializers.
visitor = new InferenceClassVisitor(methodName);
} catch (IllegalArgumentException theVersionOfAsmIsOlderThanWeRequire) {
// TODO(cpovirk): Consider what minimum version the class and method visitors really need.
// TODO(cpovirk): Log a warning?
return null;
}
ClassLoader loader =
firstNonNull(
currentThread().getContextClassLoader(), ActualValueInference.class.getClassLoader());
/*
* We're assuming that classes were loaded in a simple way. In principle, we could do better
* with java.lang.instrument.
*/
InputStream stream = null;
try {
stream = loader.getResourceAsStream(className.replace('.', '/') + ".class");
// TODO(cpovirk): Disable inference if the bytecode version is newer than we've tested on?
new ClassReader(stream).accept(visitor, /* parsingOptions= */ 0);
ImmutableSet<StackEntry> actualsAtLine = visitor.actualValueAtLine.build().get(lineNumber);
/*
* It's very unlikely that more than one assertion would happen on the same line _but with
* different root actual values_.
*
* That is, it's common to have:
* assertThat(list).containsExactly(...).inOrder();
*
* But it's not common to have, all on one line:
* assertThat(list).isEmpty(); assertThat(list2).containsExactly(...);
*
* In principle, we could try to distinguish further by looking at what assertion method
* failed (which our caller could pass us by looking higher on the stack). But it's hard to
* imagine that it would be worthwhile.
*/
return actualsAtLine.size() == 1 ? getOnlyElement(actualsAtLine).description() : null;
} catch (IOException e) {
/*
* Likely "Class not found," perhaps from generated bytecode (or from StackTraceCleaner's
* pseudo-frames, which ideally ActualValueInference would tell it not to create).
*/
// TODO(cpovirk): Log a warning?
return null;
} catch (SecurityException e) {
// Inside Google, some tests run under a security manager that forbids filesystem access.
// TODO(cpovirk): Log a warning?
return null;
} finally {
closeQuietly(stream);
}
} | <b>Call {@link Platform#inferDescription} rather than calling this directly.</b> | describeActualValue | java | google/truth | core/src/main/java/com/google/common/truth/ActualValueInference.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java | Apache-2.0 |
InferredType getElementTypeIfArrayOrThrow() {
String descriptor = descriptor();
checkState(descriptor.charAt(0) == '[', "This type %s is not an array.", this);
return create(descriptor.substring(1));
} | If the type is an array, return the element type. Otherwise, throw an exception. | getElementTypeIfArrayOrThrow | java | google/truth | core/src/main/java/com/google/common/truth/ActualValueInference.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java | Apache-2.0 |
public void isEqualToIgnoringScale(String expected) {
compareValues(new BigDecimal(expected));
} | Checks that the actual value is equal to the value of the {@link BigDecimal} created from the
expected string (i.e., checks that {@code actual.comparesTo(new BigDecimal(expected)) == 0}).
<p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and
the scales, use {@link #isEqualTo(Object)}. | isEqualToIgnoringScale | java | google/truth | core/src/main/java/com/google/common/truth/BigDecimalSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java | Apache-2.0 |
public void isEqualToIgnoringScale(long expected) {
compareValues(new BigDecimal(expected));
} | Checks that the actual value is equal to the value of the {@link BigDecimal} created from the
expected {@code long} (i.e., checks that {@code actual.comparesTo(new BigDecimal(expected)) ==
0}).
<p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and
the scales, use {@link #isEqualTo(Object)}. | isEqualToIgnoringScale | java | google/truth | core/src/main/java/com/google/common/truth/BigDecimalSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java | Apache-2.0 |
@Override // To express more specific javadoc
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | Checks that the actual value (including scale) is equal to the given {@link BigDecimal}.
<p><b>Note:</b> If you only want to compare the values of the BigDecimals and not their scales,
use {@link #isEqualToIgnoringScale(BigDecimal)} instead. | isEqualTo | java | google/truth | core/src/main/java/com/google/common/truth/BigDecimalSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java | Apache-2.0 |
public void isTrue() {
if (actual == null) {
isEqualTo(true); // fails
} else if (!actual) {
failWithoutActual(simpleFact("expected to be true"));
}
} | Checks that the actual value is {@code true}. | isTrue | java | google/truth | core/src/main/java/com/google/common/truth/BooleanSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BooleanSubject.java | Apache-2.0 |
public final void isIn(@Nullable Range<T> range) {
T actual = actualAsT();
if (range == null) {
failWithoutActual(
simpleFact("could not perform range check because range is null"),
fact("value to test for membership was", actual));
} else if (actual == null || !range.contains(actual)) {
failWithActual("expected to be in range", range);
}
} | Checks that the actual value is in {@code range}. | isIn | java | google/truth | core/src/main/java/com/google/common/truth/ComparableSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java | Apache-2.0 |
public final void isNotIn(@Nullable Range<T> range) {
T actual = actualAsT();
if (range == null) {
failWithoutActual(
simpleFact("could not perform range check because range is null"),
fact("value to test for membership was", actual));
} else if (actual == null) {
failWithActual("expected a non-null value outside range", range);
} else if (range.contains(actual)) {
failWithActual("expected not to be in range", range);
}
} | Checks that the actual value is <i>not</i> in {@code range}. | isNotIn | java | google/truth | core/src/main/java/com/google/common/truth/ComparableSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java | Apache-2.0 |
public void isEquivalentAccordingToCompareTo(@Nullable T expected) {
Comparable<Object> actual = actualAsComparable();
if (expected == null) {
failWithoutActual(
simpleFact(
"expected a value equivalent to null according to compareTo, but compareTo is"
+ " required to reject null"),
fact("was", actual));
} else if (actual == null || actual.compareTo(expected) != 0) {
failWithActual("expected value that sorts equal to", expected);
}
} | Checks that the actual value is equivalent to {@code other} according to {@link
Comparable#compareTo}, (i.e., checks that {@code a.comparesTo(b) == 0}).
<p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link
#isEqualTo(Object)}. | isEquivalentAccordingToCompareTo | java | google/truth | core/src/main/java/com/google/common/truth/ComparableSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java | Apache-2.0 |
public final void isLessThan(@Nullable T other) {
Comparable<Object> actual = actualAsComparable();
if (other == null) {
failWithoutActual(
simpleFact(
"expected a value less than null according to compareTo, but compareTo is required to"
+ " reject null"),
fact("was", actual));
} else if (actual == null || actual.compareTo(other) >= 0) {
failWithActual("expected to be less than", other);
}
} | Checks that the actual value is less than {@code other}.
<p>To check that the actual value is less than <i>or equal to</i> {@code other}, use {@link
#isAtMost}. | isLessThan | java | google/truth | core/src/main/java/com/google/common/truth/ComparableSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java | Apache-2.0 |
static ImmutableList<Fact> makeComparisonFailureFacts(
ImmutableList<Fact> headFacts,
ImmutableList<Fact> tailFacts,
String expected,
String actual) {
return concat(headFacts, formatExpectedAndActual(expected, actual), tailFacts);
} | Contains part of the code responsible for creating a JUnit {@code ComparisonFailure} (if
available) or a plain {@code AssertionError} (if not).
<p>This particular class is responsible for the fallback when a platform offers {@code
ComparisonFailure} but it is not available in a particular test environment. In practice, that
should mean open-source JRE users who choose to exclude our JUnit 4 dependency.
<p>(This class also includes logic to format expected and actual values for easier reading.)
<p>Another part of the fallback logic is {@code Platform.ComparisonFailureWithFacts}, which has a
different implementation under GWT/j2cl, where {@code ComparisonFailure} is also unavailable but
we can't just recover from that at runtime. | makeComparisonFailureFacts | java | google/truth | core/src/main/java/com/google/common/truth/ComparisonFailures.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparisonFailures.java | Apache-2.0 |
public static <A extends @Nullable Object, E extends @Nullable Object> Correspondence<A, E> from(
BinaryPredicate<A, E> predicate, String description) {
return FromBinaryPredicate.create(predicate, description);
} | Constructs a {@link Correspondence} that compares actual and expected elements using the given
binary predicate.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if the data you are asserting about contains nulls, your predicate may be invoked
with null arguments. If this causes it to throw a {@link NullPointerException}, then your test
will fail. (See {@link Correspondence#compare} for more detail on how exceptions are handled.)
In particular, if your predicate is an instance method reference on the actual value (as in the
{@code String::contains} example below), your test will fail if it sees null actual values.
<p>Example using an instance method reference:
<pre>{@code
static final Correspondence<String, String> CONTAINS_SUBSTRING =
Correspondence.from(String::contains, "contains");
}</pre>
<p>Example using a static method reference:
<pre>{@code
class MyRecordTestHelper {
static final Correspondence<MyRecord, MyRecord> EQUIVALENCE =
Correspondence.from(MyRecordTestHelper::recordsEquivalent, "is equivalent to");
static boolean recordsEquivalent(MyRecord actual, MyRecord expected) {
// code to check whether records should be considered equivalent for testing purposes
}
}
}</pre>
<p>Example using a lambda:
<pre>{@code
static final Correspondence<Object, Class<?>> INSTANCE_OF =
Correspondence.from((obj, clazz) -> clazz.isInstance(obj), "is an instance of");
}</pre>
@param predicate a {@link BinaryPredicate} taking an actual and expected value (in that order)
and returning whether the actual value corresponds to the expected value in some way
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "contains"}, {@code "is an instance of"}, or {@code "is equivalent to"} | from | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
public static <A extends @Nullable Object, E extends @Nullable Object>
Correspondence<A, E> transforming(
Function<A, ? extends E> actualTransform, String description) {
return Transforming.create(actualTransform, identity(), description);
} | Constructs a {@link Correspondence} that compares elements by transforming the actual elements
using the given function and testing for equality with the expected elements. If the
transformed actual element (i.e. the output of the given function) is null, it will correspond
to a null expected element.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if you the data you are asserting about contains null actual values, your
function may be invoked with a null argument. If this causes it to throw a {@link
NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for more
detail on how exceptions are handled.) In particular, this applies if your function is an
instance method reference on the actual value (as in the example below). If you want a null
actual element to correspond to a null expected element, you must ensure that your function
transforms a null input to a null output.
<p>Example:
<pre>{@code
static final Correspondence<MyRecord, Integer> HAS_ID =
Correspondence.transforming(MyRecord::getId, "has an ID of");
}</pre>
This can be used as follows:
<pre>{@code
assertThat(myRecords).comparingElementsUsing(HAS_ID).containsExactly(123, 456, 789);
}</pre>
@param actualTransform a {@link Function} taking an actual value and returning a new value
which will be compared with an expected value to determine whether they correspond
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "has an ID of"} | transforming | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
public Correspondence<A, E> formattingDiffsUsing(DiffFormatter<? super A, ? super E> formatter) {
return FormattingDiffs.create(this, formatter);
} | Returns a new correspondence which is like this one, except that the given formatter may be
used to format the difference between a pair of elements that do not correspond.
<p>Note that, if you the data you are asserting about contains null actual or expected values,
the formatter may be invoked with a null argument. If this causes it to throw a {@link
NullPointerException}, that will be taken to indicate that the values cannot be diffed. (See
{@link Correspondence#formatDiff} for more detail on how exceptions are handled.) If you think
null values are likely, it is slightly cleaner to have the formatter return null in that case
instead of throwing.
<p>Example:
<pre>{@code
class MyRecordTestHelper {
static final Correspondence<MyRecord, MyRecord> EQUIVALENCE =
Correspondence.from(MyRecordTestHelper::recordsEquivalent, "is equivalent to")
.formattingDiffsUsing(MyRecordTestHelper::formatRecordDiff);
static boolean recordsEquivalent(MyRecord actual, MyRecord expected) {
// code to check whether records should be considered equivalent for testing purposes
}
static String formatRecordDiff(MyRecord actual, MyRecord expected) {
// code to format the diff between the records
}
}
}</pre> | formattingDiffsUsing | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
void addCompareException(
Class<?> callingClass,
Exception exception,
@Nullable Object actual,
@Nullable Object expected) {
if (firstCompareException == null) {
truncateStackTrace(exception, callingClass);
firstCompareException =
StoredException.create(exception, "compare", asList(actual, expected));
}
} | Adds an exception that was thrown during a {@code compare} call.
@param callingClass The class from which the {@code compare} method was called. When
reporting failures, stack traces will be truncated above elements in this class.
@param exception The exception encountered
@param actual The {@code actual} argument to the {@code compare} call during which the
exception was encountered
@param expected The {@code expected} argument to the {@code compare} call during which the
exception was encountered | addCompareException | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
void addActualKeyFunctionException(
Class<?> callingClass, Exception exception, @Nullable Object actual) {
if (firstPairingException == null) {
truncateStackTrace(exception, callingClass);
firstPairingException =
StoredException.create(exception, "actualKeyFunction.apply", asList(actual));
}
} | Adds an exception that was thrown during an {@code apply} call on the function used to key
actual elements.
@param callingClass The class from which the {@code apply} method was called. When reporting
failures, stack traces will be truncated above elements in this class.
@param exception The exception encountered
@param actual The {@code actual} argument to the {@code apply} call during which the
exception was encountered | addActualKeyFunctionException | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
void addExpectedKeyFunctionException(
Class<?> callingClass, Exception exception, @Nullable Object expected) {
if (firstPairingException == null) {
truncateStackTrace(exception, callingClass);
firstPairingException =
StoredException.create(exception, "expectedKeyFunction.apply", asList(expected));
}
} | Adds an exception that was thrown during an {@code apply} call on the function used to key
expected elements.
@param callingClass The class from which the {@code apply} method was called. When reporting
failures, stack traces will be truncated above elements in this class.
@param exception The exception encountered
@param expected The {@code expected} argument to the {@code apply} call during which the
exception was encountered | addExpectedKeyFunctionException | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
void addFormatDiffException(
Class<?> callingClass,
Exception exception,
@Nullable Object actual,
@Nullable Object expected) {
if (firstFormatDiffException == null) {
truncateStackTrace(exception, callingClass);
firstFormatDiffException =
StoredException.create(exception, "formatDiff", asList(actual, expected));
}
} | Adds an exception that was thrown during a {@code formatDiff} call.
@param callingClass The class from which the {@code formatDiff} method was called. When
reporting failures, stack traces will be truncated above elements in this class.
@param exception The exception encountered
@param actual The {@code actual} argument to the {@code formatDiff} call during which the
exception was encountered
@param expected The {@code expected} argument to the {@code formatDiff} call during which the
exception was encountered | addFormatDiffException | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
boolean hasCompareException() {
return firstCompareException != null;
} | Returns whether any exceptions thrown during {@code compare} calls were stored. | hasCompareException | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
ImmutableList<Fact> describeAsMainCause() {
checkState(firstCompareException != null);
// We won't do pairing or diff formatting unless a more meaningful failure was found, and if a
// more meaningful failure was found then we shouldn't be using this method:
checkState(firstPairingException == null);
checkState(firstFormatDiffException == null);
return ImmutableList.of(
simpleFact("one or more exceptions were thrown while comparing " + argumentLabel),
fact("first exception", firstCompareException.describe()));
} | Returns facts to use in a failure message when the exceptions from {@code compare} calls are
the main cause of the failure. At least one exception thrown during a {@code compare} call
must have been stored, and no exceptions from a {@code formatDiff} call. Assertions should
use this when exceptions were thrown while comparing elements and no more meaningful failure
was discovered by assuming a false return and continuing (see the javadoc for {@link
Correspondence#compare}). C.f. {@link #describeAsAdditionalInfo}. | describeAsMainCause | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
final boolean safeCompare(A actual, E expected, ExceptionStore exceptions) {
try {
return compare(actual, expected);
} catch (RuntimeException e) {
exceptions.addCompareException(Correspondence.class, e, actual, expected);
return false;
}
} | Invokes {@link #compare}, catching any exceptions. If the comparison does not throw, returns
the result. If it does throw, adds the exception to the given {@link ExceptionStore} and
returns false. This method can help with implementing the exception-handling policy described
above, but note that assertions using it <i>must</i> fail later if an exception was stored. | safeCompare | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
public @Nullable String formatDiff(A actual, E expected) {
return null;
} | Returns a {@link String} describing the difference between the {@code actual} and {@code
expected} values, if possible, or {@code null} if not.
<p>The implementation on the {@link Correspondence} base class always returns {@code null}. To
enable diffing, use {@link #formattingDiffsUsing} (or override this method in a subclass, but
factory methods are recommended over subclassing).
<p>Assertions should only invoke this with parameters for which {@link #compare} returns {@code
false}.
<p>If this throws an exception, that implies that it is not possible to describe the diffs. An
assertion will normally only call this method if it has established that its condition does not
hold: good practice dictates that, if this method throws, the assertion should catch the
exception and continue to describe the original failure as if this method had returned null,
mentioning the failure from this method as additional information. | formatDiff | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
final @Nullable String safeFormatDiff(A actual, E expected, ExceptionStore exceptions) {
try {
return formatDiff(actual, expected);
} catch (RuntimeException e) {
exceptions.addFormatDiffException(Correspondence.class, e, actual, expected);
return null;
}
} | Invokes {@link #formatDiff}, catching any exceptions. If the comparison does not throw, returns
the result. If it does throw, adds the exception to the given {@link ExceptionStore} and
returns null. | safeFormatDiff | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
boolean isEquality() {
return false;
} | Returns whether this is an equality correspondence, i.e. one returned by {@link #equality} or
one whose {@link #compare} delegates to one returned by {@link #equality}. | isEquality | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
final ImmutableList<Fact> describeForIterable() {
if (!isEquality()) {
return ImmutableList.of(
fact("testing whether", "actual element " + this + " expected element"));
} else {
return ImmutableList.of();
}
} | Returns a list of {@link Fact} instance describing how this correspondence compares elements of
an iterable. There will be one "testing whether" fact, unless this {@link #isEquality is an
equality correspondence}, in which case the list will be empty. | describeForIterable | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
final ImmutableList<Fact> describeForMapValues() {
if (!isEquality()) {
return ImmutableList.of(fact("testing whether", "actual value " + this + " expected value"));
} else {
return ImmutableList.of();
}
} | Returns a list of {@link Fact} instance describing how this correspondence compares values in a
map (or multimap). There will be one "testing whether" fact, unless this {@link #isEquality is
an equality correspondence}, in which case the list will be empty. | describeForMapValues | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
@Deprecated
@Override
public final boolean equals(@Nullable Object o) {
throw new UnsupportedOperationException(
"Correspondence.equals(object) is not supported. If you meant to compare objects, use"
+ " .compare(actual, expected) instead.");
} | @throws UnsupportedOperationException always
@deprecated {@link Object#equals(Object)} is not supported. If you meant to compare objects
using this {@link Correspondence}, use {@link #compare}. | equals | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
@Deprecated
@Override
public final int hashCode() {
throw new UnsupportedOperationException("Correspondence.hashCode() is not supported.");
} | @throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported. | hashCode | java | google/truth | core/src/main/java/com/google/common/truth/Correspondence.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java | Apache-2.0 |
protected final FailureMetadata metadata() {
return metadata;
} | Returns the {@link FailureMetadata} instance that {@code that} methods should pass to {@link
Subject} constructors. | metadata | java | google/truth | core/src/main/java/com/google/common/truth/CustomSubjectBuilder.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/CustomSubjectBuilder.java | Apache-2.0 |
private List<String> diff(
List<String> originalLines, List<String> revisedLines, int contextSize) {
reduceEqualLinesFromHeadAndTail(originalLines, revisedLines, contextSize);
originalLines = originalLines.subList(offsetHead, originalLines.size() - offsetTail);
revisedLines = revisedLines.subList(offsetHead, revisedLines.size() - offsetTail);
original = new int[originalLines.size() + 1];
revised = new int[revisedLines.size() + 1];
lcs = new int[originalLines.size() + 1][revisedLines.size() + 1];
for (int i = 0; i < originalLines.size(); i++) {
original[i + 1] = getIdByLine(originalLines.get(i));
}
for (int i = 0; i < revisedLines.size(); i++) {
revised[i + 1] = getIdByLine(revisedLines.get(i));
}
for (int i = 1; i < original.length; i++) {
for (int j = 1; j < revised.length; j++) {
if (original[i] == revised[j]) {
lcs[i][j] = lcs[i - 1][j - 1] + 1;
} else {
lcs[i][j] = max(lcs[i][j - 1], lcs[i - 1][j]);
}
}
}
calcUnifiedDiff(originalLines.size(), revisedLines.size());
calcReducedUnifiedDiff(contextSize);
return reducedUnifiedDiff;
} | A custom implementation of the diff algorithm based on the solution described at
https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
@author Yun Peng ([email protected]) | diff | java | google/truth | core/src/main/java/com/google/common/truth/DiffUtils.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DiffUtils.java | Apache-2.0 |
private Integer getIdByLine(String line) {
int newId = stringList.size();
Integer existingId = stringToId.put(line, newId);
if (existingId == null) {
stringList.add(line);
return newId;
} else {
stringToId.put(line, existingId);
return existingId;
}
} | Calculate an incremental Id for a given string. | getIdByLine | java | google/truth | core/src/main/java/com/google/common/truth/DiffUtils.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DiffUtils.java | Apache-2.0 |
@Deprecated
@Override
public boolean equals(@Nullable Object o) {
throw new UnsupportedOperationException(
"If you meant to compare doubles, use .of(double) instead.");
} | @throws UnsupportedOperationException always
@deprecated {@link Object#equals(Object)} is not supported on TolerantDoubleComparison. If
you meant to compare doubles, use {@link #of(double)} instead. | equals | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
public TolerantDoubleComparison isWithin(double tolerance) {
return TolerantDoubleComparison.comparing(
other -> {
if (!Double.isFinite(tolerance)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is not finite"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (Double.compare(tolerance, 0.0) < 0) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is negative"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (!Double.isFinite(other)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because expected value is not"
+ " finite"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (actual == null || !Double.isFinite(actual)) {
failWithoutActual(
numericFact("expected a finite value near", other),
numericFact("but was", actual),
numericFact("tolerance", tolerance));
} else if (!equalWithinTolerance(actual, other, tolerance)) {
failWithoutActual(
numericFact("expected", other),
numericFact("but was", actual),
numericFact("outside tolerance", tolerance));
}
});
} | Prepares for a check that the actual value is a finite number within the given tolerance of an
expected value that will be provided in the next call in the fluent chain.
<p>The check will fail if either the actual value or the expected value is {@link
Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}. To check
for those values, use {@link #isPositiveInfinity}, {@link #isNegativeInfinity}, {@link #isNaN},
or (with more generality) {@link #isEqualTo}.
<p>The check will pass if both values are zero, even if one is {@code 0.0} and the other is
{@code -0.0}. Use {@link #isEqualTo} to assert that a value is exactly {@code 0.0} or that it
is exactly {@code -0.0}.
<p>You can use a tolerance of {@code 0.0} to assert the exact equality of finite doubles, but
often {@link #isEqualTo} is preferable (note the different behaviours around non-finite values
and {@code -0.0}). See the documentation on {@link #isEqualTo} for advice on when exact
equality assertions are appropriate.
@param tolerance an inclusive upper bound on the difference between the actual value and
expected value allowed by the check, which must be a non-negative finite value, i.e. not
{@link Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0} | isWithin | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
public TolerantDoubleComparison isNotWithin(double tolerance) {
return TolerantDoubleComparison.comparing(
other -> {
if (!Double.isFinite(tolerance)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is not finite"),
numericFact("expected not to be", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (Double.compare(tolerance, 0.0) < 0) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is negative"),
numericFact("expected not to be", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (!Double.isFinite(other)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because expected value is not"
+ " finite"),
numericFact("expected not to be", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (actual == null || !Double.isFinite(actual)) {
failWithoutActual(
numericFact("expected a finite value that is not near", other),
numericFact("but was", actual),
numericFact("tolerance", tolerance));
} else if (!notEqualWithinTolerance(actual, other, tolerance)) {
failWithoutActual(
numericFact("expected not to be", other),
numericFact("but was", actual),
numericFact("within tolerance", tolerance));
}
});
} | Prepares for a check that the actual value is a finite number not within the given tolerance of
an expected value that will be provided in the next call in the fluent chain.
<p>The check will fail if either the actual value or the expected value is {@link
Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}. See {@link
#isFinite}, {@link #isNotNaN}, or {@link #isNotEqualTo} for checks with other behaviours.
<p>The check will fail if both values are zero, even if one is {@code 0.0} and the other is
{@code -0.0}. Use {@link #isNotEqualTo} for a test which fails for a value of exactly zero with
one sign but passes for zero with the opposite sign.
<p>You can use a tolerance of {@code 0.0} to assert the exact non-equality of finite doubles,
but sometimes {@link #isNotEqualTo} is preferable (note the different behaviours around
non-finite values and {@code -0.0}).
@param tolerance an exclusive lower bound on the difference between the actual value and
expected value allowed by the check, which must be a non-negative finite value, i.e. not
{@code Double.NaN}, {@code Double.POSITIVE_INFINITY}, or negative, including {@code -0.0} | isNotWithin | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
@Override
public void isEqualTo(@Nullable Object other) {
super.isEqualTo(other);
} | Asserts that the actual value is exactly equal to the given value, with equality defined as by
{@code Double#equals}. This method is <i>not</i> recommended when the code under test is doing
any kind of arithmetic: use {@link #isWithin} 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.
<p><b>Note:</b> The assertion {@code isEqualTo(0.0)} fails for an input of {@code -0.0}, and
vice versa. For an assertion that passes for either {@code 0.0} or {@code -0.0}, use {@link
#isZero}. | isEqualTo | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
@Override
public void isNotEqualTo(@Nullable Object other) {
super.isNotEqualTo(other);
} | Asserts that the actual value is not exactly equal to the given value, with equality defined as
by {@code Double#equals}. See {@link #isEqualTo} for advice on when exact equality is
recommended. Use {@link #isNotWithin} for an assertion with a tolerance.
<p><b>Note:</b> The assertion {@code isNotEqualTo(0.0)} passes for {@code -0.0}, and vice
versa. For an assertion that fails for either {@code 0.0} or {@code -0.0}, use {@link
#isNonZero}. | isNotEqualTo | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
public void isZero() {
if (actual == null || actual != 0.0) {
failWithActual(simpleFact("expected zero"));
}
} | Asserts that the actual value is zero (i.e. it is either {@code 0.0} or {@code -0.0}). | isZero | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
public void isNonZero() {
if (actual == null) {
failWithActual(simpleFact("expected a double other than zero"));
} else if (actual == 0.0) {
failWithActual(simpleFact("expected not to be zero"));
}
} | Asserts that the actual value is a non-null value other than zero (i.e. it is not {@code 0.0},
{@code -0.0} or {@code null}). | isNonZero | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
public void isFinite() {
if (actual == null || actual.isNaN() || actual.isInfinite()) {
failWithActual(simpleFact("expected to be finite"));
}
} | Asserts that the actual value is finite, i.e. not {@link Double#POSITIVE_INFINITY}, {@link
Double#NEGATIVE_INFINITY}, or {@link Double#NaN}. | isFinite | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
public void isNotNaN() {
if (actual == null) {
failWithActual(simpleFact("expected a double other than NaN"));
} else {
isNotEqualTo(NaN);
}
} | Asserts that the actual value is a non-null value other than {@link Double#NaN} (but it may be
{@link Double#POSITIVE_INFINITY} or {@link Double#NEGATIVE_INFINITY}). | isNotNaN | java | google/truth | core/src/main/java/com/google/common/truth/DoubleSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java | Apache-2.0 |
void enterRuleContext() {
this.inRuleContext = true;
} | Enters rule context to be ready to capture failures.
<p>This should be used only from framework code. This normally means from the {@link #apply}
method below, but our tests call it directly under J2CL. | enterRuleContext | java | google/truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ExpectFailure.java | Apache-2.0 |
void leaveRuleContext() {
this.inRuleContext = false;
} | Leaves rule context and verify if a failure has been caught if it's expected. | leaveRuleContext | java | google/truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ExpectFailure.java | Apache-2.0 |
void ensureFailureCaught() {
if (failureExpected && failure == null) {
throw new AssertionError(
"ExpectFailure.whenTesting() invoked, but no failure was caught."
+ Platform.EXPECT_FAILURE_WARNING_IF_GWT);
}
} | Ensures a failure is caught if it's expected (i.e., {@link #whenTesting} is called) and throws
error if not. | ensureFailureCaught | java | google/truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ExpectFailure.java | Apache-2.0 |
public AssertionError getFailure() {
if (failure == null) {
throw new AssertionError("ExpectFailure did not capture a failure.");
}
return failure;
} | Legacy method that returns the failure captured by {@link #whenTesting}, if one occurred. | getFailure | java | google/truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ExpectFailure.java | Apache-2.0 |
private void captureFailure(AssertionError captured) {
if (failure != null) {
// TODO(diamondm) is it worthwhile to add the failures as suppressed exceptions?
throw new AssertionError(
lenientFormat(
"ExpectFailure.whenTesting() caught multiple failures:\n\n%s\n\n%s\n",
Platform.getStackTraceAsString(failure), Platform.getStackTraceAsString(captured)));
}
failure = captured;
} | Captures the provided failure, or throws an {@link AssertionError} if a failure had previously
been captured. | captureFailure | java | google/truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ExpectFailure.java | Apache-2.0 |
@CanIgnoreReturnValue
public static AssertionError expectFailure(StandardSubjectBuilderCallback assertionCallback) {
ExpectFailure expectFailure = new ExpectFailure();
expectFailure.enterRuleContext(); // safe since this instance doesn't leave this method
assertionCallback.invokeAssertion(expectFailure.whenTesting());
return expectFailure.getFailure();
} | Captures and returns the failure produced by the assertion in the provided callback, similar to
{@code assertThrows()}:
<p>{@code AssertionError failure = expectFailure(whenTesting ->
whenTesting.that(4).isNotEqualTo(4));} | expectFailure | java | google/truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ExpectFailure.java | Apache-2.0 |
@CanIgnoreReturnValue
public static <S extends Subject, A> AssertionError expectFailureAbout(
Subject.Factory<S, A> factory, SimpleSubjectBuilderCallback<S, A> assertionCallback) {
return expectFailure(
whenTesting -> assertionCallback.invokeAssertion(whenTesting.about(factory)));
} | Captures and returns the failure produced by the assertion in the provided callback, similar to
{@code assertThrows()}:
<p>{@code AssertionError failure = expectFailureAbout(myTypes(), whenTesting ->
whenTesting.that(myType).hasProperty());} | expectFailureAbout | java | google/truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ExpectFailure.java | Apache-2.0 |
public static Fact fact(String key, @Nullable Object value) {
return new Fact(key, String.valueOf(value), /* padStart= */ false);
} | Creates a fact with the given key and value, which will be printed in a format like "key:
value." The value is converted to a string by calling {@code String.valueOf} on it. | fact | java | google/truth | core/src/main/java/com/google/common/truth/Fact.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Fact.java | Apache-2.0 |
public static Fact simpleFact(String key) {
return new Fact(key, null, /* padStart= */ false);
} | Creates a fact with no value, which will be printed in the format "key" (with no colon or
value).
<p>In most cases, prefer {@linkplain #fact key-value facts}, which give Truth more flexibility
in how to format the fact for display. {@code simpleFact} is useful primarily for:
<ul>
<li>messages from no-arg assertions. For example, {@code isNotEmpty()} would generate the
fact "expected not to be empty"
<li>prose that is part of a larger message. For example, {@code contains()} sometimes
displays facts like "expected to contain: ..." <i>"but did not"</i> "though it did
contain: ..."
</ul> | simpleFact | java | google/truth | core/src/main/java/com/google/common/truth/Fact.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Fact.java | Apache-2.0 |
@Override
public String toString() {
return value == null ? key : key + ": " + value;
} | Returns a simple string representation for the fact. While this is used in the output of {@code
TruthFailureSubject}, it's not used in normal failure messages, which automatically align facts
horizontally and indent multiline values. | toString | java | google/truth | core/src/main/java/com/google/common/truth/Fact.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Fact.java | Apache-2.0 |
static FailureMetadata forFailureStrategy(FailureStrategy failureStrategy) {
return new FailureMetadata(
failureStrategy, /* messages= */ ImmutableList.of(), /* steps= */ ImmutableList.of());
} | An opaque, immutable object containing state from the previous calls in the fluent assertion
chain. It appears primarily as a parameter to {@link Subject} constructors (and {@link
Subject.Factory} methods), which should pass it to the superclass constructor and not otherwise
use or store it. In particular, users should not attempt to call {@code Subject} constructors or
{@code Subject.Factory} methods directly. Instead, they should use the appropriate factory
method:
<ul>
<li>If you're writing a test: {@link Truth#assertAbout(Subject.Factory)}{@code .that(...)}
<li>If you're creating a derived subject from within another subject: {@code
check(...).about(...).that(...)}
<li>If you're testing your subject to verify that assertions fail when they should: {@link
ExpectFailure}
</ul>
<p>(One exception: Implementations of {@link CustomSubjectBuilder} do directly call constructors,
using their {@link CustomSubjectBuilder#metadata()} method to get an instance to pass to the
constructor.) | forFailureStrategy | java | google/truth | core/src/main/java/com/google/common/truth/FailureMetadata.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FailureMetadata.java | Apache-2.0 |
private ImmutableList<Fact> description() {
return description(/* factKey= */ "value of");
} | Returns a description of the final actual value, if it appears "interesting" enough to show.
The description is considered interesting if the chain of derived subjects ends with at least
one derivation that we have a name for. It's also considered interesting in the absence of
derived subjects if we inferred a name for the root actual value from the bytecode.
<p>We don't want to say: "value of string: expected [foo] but was [bar]" (OK, we might still
decide to say this, but for now, we don't.)
<p>We do want to say: "value of throwable.getMessage(): expected [foo] but was [bar]"
<p>We also want to say: "value of getLogMessages(): expected not to be empty"
<p>To support that, {@code descriptionIsInteresting} tracks whether we've been given context
through {@code check} calls <i>that include names</i> or, initially, whether we inferred a name
for the root actual value from the bytecode.
<p>If we're missing a naming function halfway through, we have to reset: We don't want to claim
that the value is "foo.bar.baz" when it's "foo.bar.somethingelse.baz." We have to go back to
"object.baz." (But note that {@link #rootUnlessThrowable} will still provide the value of the
root foo to the user as long as we had at least one naming function: We might not know the
root's exact relationship to the final object, but we know it's some object "different enough"
to be worth displaying.) | description | java | google/truth | core/src/main/java/com/google/common/truth/FailureMetadata.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FailureMetadata.java | Apache-2.0 |
private ImmutableList<Fact> description(String factKey) {
String description = inferDescription();
boolean descriptionIsInteresting = description != null;
for (Step step : steps) {
if (step.isCheckCall()) {
checkState(description != null);
if (step.descriptionUpdate == null) {
description = null;
descriptionIsInteresting = false;
} else {
description = verifyNotNull(step.descriptionUpdate.apply(description));
descriptionIsInteresting = true;
}
continue;
}
if (description == null) {
description = checkNotNull(step.subject).typeDescription();
}
}
return descriptionIsInteresting
? ImmutableList.of(fact(factKey, description))
: ImmutableList.of();
} | Overload of {@link #description()} that allows passing a custom key for the fact. | description | java | google/truth | core/src/main/java/com/google/common/truth/FailureMetadata.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FailureMetadata.java | Apache-2.0 |
private ImmutableList<Fact> rootUnlessThrowable() {
Step rootSubject = null;
boolean seenDerivation = false;
for (Step step : steps) {
if (step.isCheckCall()) {
/*
* If we don't have a description update, don't trigger display of a root object. (If we
* did, we'd change the messages of a bunch of existing subjects, and we don't want to bite
* that off yet.)
*
* If we do have a description update, then trigger display of a root object but only if the
* old and new values are "different enough" to be worth both displaying.
*/
seenDerivation |=
step.descriptionUpdate != null
&& step.valuesAreSimilar == OldAndNewValuesAreSimilar.DIFFERENT;
continue;
}
if (rootSubject == null) {
if (checkNotNull(step.subject).actual() instanceof Throwable) {
/*
* We'll already include the Throwable as a cause of the AssertionError (see rootCause()),
* so we don't need to include it again in the message.
*/
return ImmutableList.of();
}
rootSubject = step;
}
}
/*
* TODO(cpovirk): Maybe say "root foo was: ..." instead of just "foo was: ..." if there's more
* than one foo in the chain, if the description string doesn't start with "foo," and/or if the
* name we have is just "object?"
*/
return seenDerivation
? ImmutableList.of(
fact(
// TODO(cpovirk): Use inferDescription() here when appropriate? But it can be long.
checkNotNull(checkNotNull(rootSubject).subject).typeDescription() + " was",
checkNotNull(checkNotNull(rootSubject).subject)
.actualCustomStringRepresentationForPackageMembersToCall()))
: ImmutableList.of();
} | Returns the root actual value, if we know it's "different enough" from the final actual value.
<p>We don't want to say: "expected [foo] but was [bar]. string: [bar]"
<p>We do want to say: "expected [foo] but was [bar]. myObject: MyObject[string=bar, i=0]"
<p>To support that, {@code seenDerivation} tracks whether we've seen multiple actual values,
which is equivalent to whether we've seen multiple Subject instances or, more informally,
whether the user is making a chained assertion.
<p>There's one wrinkle: Sometimes chaining doesn't add information. This is often true with
"internal" chaining, like when StreamSubject internally creates an IterableSubject to delegate
to. The two subjects' string representations will be identical (or, in some cases, _almost_
identical), so there is no value in showing both. In such cases, implementations can call the
no-arg {@code checkNoNeedToDisplayBothValues()}, which sets {@code valuesAreSimilar},
instructing this method that that particular chain link "doesn't count." (Note also that there
are some edge cases that we're not sure how to handle yet, for which we might introduce
additional {@code check}-like methods someday.) | rootUnlessThrowable | java | google/truth | core/src/main/java/com/google/common/truth/FailureMetadata.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FailureMetadata.java | Apache-2.0 |
private @Nullable Throwable rootCause() {
for (Step step : steps) {
if (!step.isCheckCall() && checkNotNull(step.subject).actual() instanceof Throwable) {
return (Throwable) step.subject.actual();
}
}
return null;
} | Returns the first {@link Throwable} in the chain of actual values. Typically, we'll have a root
cause only if the assertion chain contains a {@link ThrowableSubject}. | rootCause | java | google/truth | core/src/main/java/com/google/common/truth/FailureMetadata.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FailureMetadata.java | Apache-2.0 |
@Deprecated
@Override
public boolean equals(@Nullable Object o) {
throw new UnsupportedOperationException(
"If you meant to compare floats, use .of(float) instead.");
} | @throws UnsupportedOperationException always
@deprecated {@link Object#equals(Object)} is not supported on TolerantFloatComparison. If you
meant to compare floats, use {@link #of(float)} instead. | equals | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
public TolerantFloatComparison isWithin(float tolerance) {
return TolerantFloatComparison.create(
other -> {
if (!Float.isFinite(tolerance)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is not finite"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (Float.compare(tolerance, 0.0f) < 0) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is negative"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (!Float.isFinite(other)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because expected value is not"
+ " finite"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (actual == null || !Float.isFinite(actual)) {
failWithoutActual(
numericFact("expected a finite value near", other),
numericFact("but was", actual),
numericFact("tolerance", tolerance));
} else if (!equalWithinTolerance(actual, other, tolerance)) {
failWithoutActual(
numericFact("expected", other),
numericFact("but was", actual),
numericFact("outside tolerance", tolerance));
}
});
} | Prepares for a check that the actual value is a finite number within the given tolerance of an
expected value that will be provided in the next call in the fluent chain.
<p>The check will fail if either the actual value or the expected value is {@link
Float#POSITIVE_INFINITY}, {@link Float#NEGATIVE_INFINITY}, or {@link Float#NaN}. To check for
those values, use {@link #isPositiveInfinity}, {@link #isNegativeInfinity}, {@link #isNaN}, or
(with more generality) {@link #isEqualTo}.
<p>The check will pass if both values are zero, even if one is {@code 0.0f} and the other is
{@code -0.0f}. Use {@link #isEqualTo} to assert that a value is exactly {@code 0.0f} or that it
is exactly {@code -0.0f}.
<p>You can use a tolerance of {@code 0.0f} to assert the exact equality of finite floats, but
often {@link #isEqualTo} is preferable (note the different behaviours around non-finite values
and {@code -0.0f}). See the documentation on {@link #isEqualTo} for advice on when exact
equality assertions are appropriate.
@param tolerance an inclusive upper bound on the difference between the actual value and
expected value allowed by the check, which must be a non-negative finite value, i.e. not
{@link Float#NaN}, {@link Float#POSITIVE_INFINITY}, or negative, including {@code -0.0f} | isWithin | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
public TolerantFloatComparison isNotWithin(float tolerance) {
return TolerantFloatComparison.create(
other -> {
if (!Float.isFinite(tolerance)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is not finite"),
numericFact("expected not to be", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (Float.compare(tolerance, 0.0f) < 0) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is negative"),
numericFact("expected not to be", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (!Float.isFinite(other)) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because expected value is not"
+ " finite"),
numericFact("expected not to be", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (actual == null || !Float.isFinite(actual)) {
failWithoutActual(
numericFact("expected a finite value that is not near", other),
numericFact("but was", actual),
numericFact("tolerance", tolerance));
} else if (!notEqualWithinTolerance(actual, other, tolerance)) {
failWithoutActual(
numericFact("expected not to be", other),
numericFact("but was", actual),
numericFact("within tolerance", tolerance));
}
});
} | Prepares for a check that the actual value is a finite number not within the given tolerance of
an expected value that will be provided in the next call in the fluent chain.
<p>The check will fail if either the actual value or the expected value is {@link
Float#POSITIVE_INFINITY}, {@link Float#NEGATIVE_INFINITY}, or {@link Float#NaN}. See {@link
#isFinite}, {@link #isNotNaN}, or {@link #isNotEqualTo} for checks with other behaviours.
<p>The check will fail if both values are zero, even if one is {@code 0.0f} and the other is
{@code -0.0f}. Use {@link #isNotEqualTo} for a test which fails for a value of exactly zero
with one sign but passes for zero with the opposite sign.
<p>You can use a tolerance of {@code 0.0f} to assert the exact non-equality of finite floats,
but sometimes {@link #isNotEqualTo} is preferable (note the different behaviours around
non-finite values and {@code -0.0f}).
@param tolerance an exclusive lower bound on the difference between the actual value and
expected value allowed by the check, which must be a non-negative finite value, i.e. not
{@code Float.NaN}, {@code Float.POSITIVE_INFINITY}, or negative, including {@code -0.0f} | isNotWithin | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
@Override
public void isEqualTo(@Nullable Object other) {
super.isEqualTo(other);
} | Asserts that the actual value is exactly equal to the given value, with equality defined as by
{@code Float#equals}. This method is <i>not</i> recommended when the code under test is doing
any kind of arithmetic: use {@link #isWithin} 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.
<p><b>Note:</b> The assertion {@code isEqualTo(0.0f)} fails for an input of {@code -0.0f}, and
vice versa. For an assertion that passes for either {@code 0.0f} or {@code -0.0f}, use {@link
#isZero}. | isEqualTo | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
@Override
public void isNotEqualTo(@Nullable Object other) {
super.isNotEqualTo(other);
} | Asserts that the actual value is not exactly equal to the given value, with equality defined as
by {@code Float#equals}. See {@link #isEqualTo} for advice on when exact equality is
recommended. Use {@link #isNotWithin} for an assertion with a tolerance.
<p><b>Note:</b> The assertion {@code isNotEqualTo(0.0f)} passes for {@code -0.0f}, and vice
versa. For an assertion that fails for either {@code 0.0f} or {@code -0.0f}, use {@link
#isNonZero}. | isNotEqualTo | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
public void isZero() {
if (actual == null || actual != 0.0f) {
failWithActual(simpleFact("expected zero"));
}
} | Asserts that the actual value is zero (i.e. it is either {@code 0.0f} or {@code -0.0f}). | isZero | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
public void isNonZero() {
if (actual == null) {
failWithActual(simpleFact("expected a float other than zero"));
} else if (actual == 0.0f) {
failWithActual(simpleFact("expected not to be zero"));
}
} | Asserts that the actual value is a non-null value other than zero (i.e. it is not {@code 0.0f},
{@code -0.0f} or {@code null}). | isNonZero | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
public void isFinite() {
if (actual == null || actual.isNaN() || actual.isInfinite()) {
failWithActual(simpleFact("expected to be finite"));
}
} | Asserts that the actual value is finite, i.e. not {@link Float#POSITIVE_INFINITY}, {@link
Float#NEGATIVE_INFINITY}, or {@link Float#NaN}. | isFinite | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
public void isNotNaN() {
if (actual == null) {
failWithActual(simpleFact("expected a float other than NaN"));
} else {
isNotEqualTo(NaN);
}
} | Asserts that the actual value is a non-null value other than {@link Float#NaN} (but it may be
{@link Float#POSITIVE_INFINITY} or {@link Float#NEGATIVE_INFINITY}). | isNotNaN | java | google/truth | core/src/main/java/com/google/common/truth/FloatSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java | Apache-2.0 |
static <U, V> ImmutableBiMap<U, V> maximumCardinalityBipartiteMatching(Multimap<U, V> graph) {
return HopcroftKarp.overBipartiteGraph(graph).perform();
} | Finds a <a
href="https://en.wikipedia.org/wiki/Matching_(graph_theory)#In_unweighted_bipartite_graphs">
maximum cardinality matching of a bipartite graph</a>. The vertices of one part of the
bipartite graph are identified by objects of type {@code U} using object equality. The vertices
of the other part are similarly identified by objects of type {@code V}. The input bipartite
graph is represented as a {@code Multimap<U, V>}: each entry represents an edge, with the key
representing the vertex in the first part and the value representing the value in the second
part. (Note that, even if {@code U} and {@code V} are the same type, equality between a key and
a value has no special significance: effectively, they are in different domains.) Fails if any
of the vertices (keys or values) are null. The output matching is similarly represented as a
{@code BiMap<U, V>} (the property that a matching has no common vertices translates into the
bidirectional uniqueness property of the {@link BiMap}).
<p>If there are multiple matchings which share the maximum cardinality, an arbitrary one is
returned. | maximumCardinalityBipartiteMatching | java | google/truth | core/src/main/java/com/google/common/truth/GraphMatching.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GraphMatching.java | Apache-2.0 |
static <U, V> HopcroftKarp<U, V> overBipartiteGraph(Multimap<U, V> graph) {
return new HopcroftKarp<>(graph);
} | Factory method which returns an instance ready to perform the algorithm over the bipartite
graph described by the given multimap. | overBipartiteGraph | java | google/truth | core/src/main/java/com/google/common/truth/GraphMatching.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GraphMatching.java | Apache-2.0 |
ImmutableBiMap<U, V> perform() {
BiMap<U, V> matching = HashBiMap.create();
while (true) {
// Perform the BFS as described below. This finds the length of the shortest augmenting path
// and a guide which locates all the augmenting paths of that length.
Map<U, Integer> layers = new HashMap<>();
Integer freeRhsVertexLayer = breadthFirstSearch(matching, layers);
if (freeRhsVertexLayer == null) {
// The BFS failed, i.e. we found no augmenting paths. So we're done.
break;
}
// Perform the DFS and update the matching as described below starting from each free LHS
// vertex. This finds a disjoint set of augmenting paths of the shortest length and updates
// the matching by computing the symmetric difference with that set.
for (U lhs : graph.keySet()) {
if (!matching.containsKey(lhs)) {
depthFirstSearch(matching, layers, freeRhsVertexLayer, lhs);
}
}
}
return ImmutableBiMap.copyOf(matching);
} | Performs the algorithm, and returns a bimap describing the matching found. | perform | java | google/truth | core/src/main/java/com/google/common/truth/GraphMatching.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GraphMatching.java | Apache-2.0 |
private @Nullable Integer breadthFirstSearch(BiMap<U, V> matching, Map<U, Integer> layers) {
Queue<U> queue = new ArrayDeque<>();
Integer freeRhsVertexLayer = null;
// Enqueue all free LHS vertices and assign them to layer 1.
for (U lhs : graph.keySet()) {
if (!matching.containsKey(lhs)) {
layers.put(lhs, 1);
queue.add(lhs);
}
}
// Now proceed with the BFS.
while (!queue.isEmpty()) {
U lhs = queue.remove();
int layer = checkNotNull(layers.get(lhs));
// If the BFS has proceeded past a layer in which a free RHS vertex was found, stop.
if (freeRhsVertexLayer != null && layer > freeRhsVertexLayer) {
break;
}
// We want to consider all the unmatched edges from the current LHS vertex to the RHS, and
// then all the matched edges from those RHS vertices back to the LHS, to find the next
// layer of LHS vertices. We actually iterate over all edges, both matched and unmatched,
// from the current LHS vertex: we'll just do nothing for matched edges.
for (V rhs : graph.get(lhs)) {
if (!matching.containsValue(rhs)) {
// We found a free RHS vertex. Record the layer at which we found it. Since the RHS
// vertex is free, there is no matched edge to follow. (Note that the edge from the LHS
// to the RHS must be unmatched, because a matched edge cannot lead to a free vertex.)
if (freeRhsVertexLayer == null) {
freeRhsVertexLayer = layer;
}
} else {
// We found an RHS vertex with a matched vertex back to the LHS. If we haven't visited
// that new LHS vertex yet, add it to the next layer. (If the edge from the LHS to the
// RHS was matched then the matched edge from the RHS to the LHS will lead back to the
// current LHS vertex, which has definitely been visited, so we correctly do nothing.)
U nextLhs = checkNotNull(matching.inverse().get(rhs));
if (!layers.containsKey(nextLhs)) {
layers.put(nextLhs, layer + 1);
queue.add(nextLhs);
}
}
}
}
return freeRhsVertexLayer;
} | Performs the Breadth-First Search phase of the algorithm. Specifically, treats the bipartite
graph as a directed graph where every unmatched edge (i.e. every edge not in the current
matching) is directed from the LHS vertex to the RHS vertex and every matched edge is
directed from the RHS vertex to the LHS vertex, and performs a BFS which starts from all of
the free LHS vertices (i.e. the LHS vertices which are not in the current matching) and stops
either at the end of a layer where a free RHS vertex is found or when the search is exhausted
if no free RHS vertex is found. Keeps track of which layer of the BFS each LHS vertex was
found in (for those LHS vertices visited during the BFS), so the free LHS vertices are in
layer 1, those reachable by following an unmatched edge from any free LHS vertex to any
non-free RHS vertex and then the matched edge back to a LHS vertex are in layer 2, etc. Note
that every path in a successful search starts with a free LHS vertex and ends with a free RHS
vertex, with every intermediate vertex being non-free.
@param matching A bimap describing the matching to be used for the BFS, which is not modified
by this method
@param layers A map to be filled with the layer of each LHS vertex visited during the BFS,
which should be empty when passed into this method and will be modified by this method
@return The number of the layer in which the first free RHS vertex was found, if any, and
{@code null} if the BFS was exhausted without finding any free RHS vertex | breadthFirstSearch | java | google/truth | core/src/main/java/com/google/common/truth/GraphMatching.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GraphMatching.java | Apache-2.0 |
@CanIgnoreReturnValue
private boolean depthFirstSearch(
BiMap<U, V> matching, Map<U, Integer> layers, int freeRhsVertexLayer, U lhs) {
// Note that this differs from the method described in the text of the wikipedia article (at
// time of writing) in two ways. Firstly, we proceed from a free LHS vertex to a free RHS
// vertex in the target layer instead of the other way around, which makes no difference.
// Secondly, we update the matching using the path found from each DFS after it is found,
// rather than using all the paths at the end of the phase. As explained above, the effect of
// this is that we automatically find only the disjoint set of paths, as required. This is,
// fact, the approach taken in the pseudocode of the wikipedia article (at time of writing).
int layer = checkNotNull(layers.get(lhs));
if (layer > freeRhsVertexLayer) {
// We've gone past the target layer, so we're not going to find what we're looking for.
return false;
}
// Consider every edge from this LHS vertex.
for (V rhs : graph.get(lhs)) {
if (!matching.containsValue(rhs)) {
// We found a free RHS vertex. (This must have been in the target layer because, by
// definition, no free RHS vertex is reachable in any earlier layer, and because we stop
// when we get past that layer.) We add the unmatched edge used to get here to the
// matching, and remove any previous matched edge leading to the LHS vertex.
matching.forcePut(lhs, rhs);
return true;
} else {
// We found a non-free RHS vertex. Follow the matched edge from that RHS vertex to find
// the next LHS vertex.
U nextLhs = checkNotNull(matching.inverse().get(rhs));
if (layers.containsKey(nextLhs) && layers.get(nextLhs) == layer + 1) {
// The next LHS vertex is in the next layer of the BFS, so we can use this path for our
// DFS. Recurse into the DFS.
if (depthFirstSearch(matching, layers, freeRhsVertexLayer, nextLhs)) {
// The DFS succeeded, and we're reversing back up the search path. At each stage we
// put the unmatched edge from the LHS to the RHS into the matching, and remove any
// matched edge previously leading to the LHS. The combined effect of all the
// modifications made while reversing all the way back up the search path is to update
// the matching as described in the javadoc.
matching.forcePut(lhs, rhs);
return true;
}
}
}
}
return false;
} | Performs the Depth-First Search phase of the algorithm. The DFS is guided by the BFS phase,
i.e. it only uses paths which were used in the BFS. That means the steps in the DFS proceed
from an LHS vertex via an unmatched edge to an RHS vertex and from an RHS vertex via a
matched edge to an LHS vertex only if that LHS vertex is one layer deeper in the BFS than the
previous one. It starts from the specified LHS vertex and stops either when it finds one of
the free RHS vertices located by the BFS or when the search is exhausted. If a free RHS
vertex is found then all the unmatched edges in the search path and added to the matching and
all the matched edges in the search path are removed from the matching; in other words, the
direction (which is determined by the matched/unmatched status) of every edge in the search
path is flipped. Note several properties of this update to the matching:
<ul>
<li>Because the search path must contain one more unmatched than matched edges, the effect
of this modification is to increase the size of the matching by one.
<li>This modification results in the free LHS vertex at the start of the path and the free
RHS vertex at the end of the path becoming non-free, while the intermediate non-free
vertices stay non-free.
<li>None of the edges used in this search path may be used in any further DFS. They cannot
be used in the same direction as they were in this DFS because their directions are
flipped; and they cannot be used in their new directions because we only use edges
leading to the next layer of the BFS and, after flipping the directions, these edges
now lead to the previous layer.
<li>As a consequence of the previous property, repeated invocations of this method will
find only paths which were used in the BFS and which were not used in any previous DFS
(i.e. the set of edges used in the paths found by repeated DFSes are disjoint).
</ul>
@param matching A bimap describing the matching to be used for the BFS, which will be
modified by this method as described above
@param layers A map giving the layer of each LHS vertex visited during the BFS, which will
not be modified by this method
@param freeRhsVertexLayer The number of the layer in which the first free RHS vertex was
found
@param lhs The LHS vertex from which to start the DFS
@return Whether or not the DFS was successful | depthFirstSearch | java | google/truth | core/src/main/java/com/google/common/truth/GraphMatching.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GraphMatching.java | Apache-2.0 |
@Deprecated
@Override
public boolean equals(@Nullable Object o) {
throw new UnsupportedOperationException(
"If you meant to compare ints, use .of(int) instead.");
} | @throws UnsupportedOperationException always
@deprecated {@link Object#equals(Object)} is not supported on TolerantIntegerComparison. If
you meant to compare ints, use {@link #of(int)} instead. | equals | java | google/truth | core/src/main/java/com/google/common/truth/IntegerSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IntegerSubject.java | Apache-2.0 |
@Deprecated
@SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely.
public static Factory<IntStreamSubject, IntStream> intStreams() {
return IntStreamSubject::new;
} | Obsolete factory instance. This factory was previously necessary for assertions like {@code
assertWithMessage(...).about(intStreams()).that(stream)....}. Now, you can perform assertions
like that without the {@code about(...)} call.
@deprecated Instead of {@code about(intStreams()).that(...)}, use just {@code that(...)}.
Similarly, instead of {@code assertAbout(intStreams()).that(...)}, use just {@code
assertThat(...)}. | intStreams | java | google/truth | core/src/main/java/com/google/common/truth/IntStreamSubject.java | https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IntStreamSubject.java | Apache-2.0 |
public final void isEmpty() {
if (!Iterables.isEmpty(checkNotNull(actual))) {
failWithActual(simpleFact("expected to be empty"));
}
} | Checks that the actual iterable is empty. | isEmpty | 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 |
public final void isNotEmpty() {
if (Iterables.isEmpty(checkNotNull(actual))) {
failWithoutActual(simpleFact("expected not to be empty"));
}
} | Checks that the actual iterable is not empty. | isNotEmpty | 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 |
public final void hasSize(int expectedSize) {
checkArgument(expectedSize >= 0, "expectedSize(%s) must be >= 0", expectedSize);
int actualSize = size(checkNotNull(actual));
check("size()").that(actualSize).isEqualTo(expectedSize);
} | Checks that the actual iterable has the given size. | hasSize | 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 |
public final void contains(@Nullable Object element) {
if (!Iterables.contains(checkNotNull(actual), element)) {
List<@Nullable Object> elementList = asList(element);
if (hasMatchingToStringPair(actual, elementList)) {
failWithoutActual(
fact("expected to contain", element),
fact("an instance of", objectToTypeName(element)),
simpleFact("but did not"),
fact(
"though it did contain",
countDuplicatesAndAddTypeInfo(
retainMatchingToString(actual, /* itemsToCheck= */ elementList))),
fullContents());
} else {
failWithActual("expected to contain", element);
}
}
} | Checks that the actual iterable contains the supplied item. | contains | 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 |
public final void doesNotContain(@Nullable Object element) {
if (Iterables.contains(checkNotNull(actual), element)) {
failWithActual("expected not to contain", element);
}
} | Checks that the actual iterable does not contain the supplied item. | doesNotContain | 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 |
public final void containsNoDuplicates() {
List<Multiset.Entry<?>> duplicates = new ArrayList<>();
for (Multiset.Entry<?> entry : LinkedHashMultiset.create(checkNotNull(actual)).entrySet()) {
if (entry.getCount() > 1) {
duplicates.add(entry);
}
}
if (!duplicates.isEmpty()) {
failWithoutActual(
simpleFact("expected not to contain duplicates"),
fact("but contained", duplicates),
fullContents());
}
} | Checks that the actual iterable does not contain duplicate elements. | containsNoDuplicates | 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 |
public final void containsAnyOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
containsAnyIn(accumulate(first, second, rest));
} | Checks that the actual iterable contains at least one of the provided objects. | containsAnyOf | 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 |
public final void containsAnyIn(@Nullable Iterable<?> expected) {
checkNotNull(expected);
Collection<?> actual = iterableToCollection(checkNotNull(this.actual));
for (Object item : expected) {
if (actual.contains(item)) {
return;
}
}
if (hasMatchingToStringPair(actual, expected)) {
failWithoutActual(
fact("expected to contain any of", countDuplicatesAndAddTypeInfo(expected)),
simpleFact("but did not"),
fact(
"though it did contain",
countDuplicatesAndAddTypeInfo(
retainMatchingToString(checkNotNull(this.actual), /* itemsToCheck= */ expected))),
fullContents());
} else {
failWithActual("expected to contain any of", expected);
}
} | Checks that the actual iterable contains at least one of the objects contained in the provided
collection. | containsAnyIn | 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 |
@SuppressWarnings("AvoidObjectArrays")
public final void containsAnyIn(@Nullable Object[] expected) {
containsAnyIn(asList(expected));
} | Checks that the actual iterable contains at least one of the objects contained in the provided
array. | containsAnyIn | 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 |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object firstExpected,
@Nullable Object secondExpected,
@Nullable Object @Nullable ... restOfExpected) {
return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected));
} | Checks that the actual iterable contains at least all the expected elements. If an element
appears more than once in the expected elements to this call then it must appear at least that
number of times in the actual elements.
<p>To also test that the contents appear in the given order, make a call to {@code inOrder()}
on the object returned by this method. The expected elements must appear in the given order
within the actual elements, but they are not required to be consecutive. | containsAtLeast | 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 static void moveElements(
List<?> input, Collection<@Nullable Object> output, int maxElements) {
for (int i = 0; i < maxElements; i++) {
output.add(input.remove(0));
}
} | Removes at most the given number of available elements from the input list and adds them to the
given output collection. | moveElements | 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 |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... expected) {
List<@Nullable Object> expectedAsList =
expected == null ? asList((@Nullable Object) null) : asList(expected);
return containsExactlyElementsIn(
expectedAsList,
expected != null && expected.length == 1 && expected[0] instanceof Iterable);
} | Checks that the actual iterable contains exactly the provided objects.
<p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the
parameters asserts that the object must likewise be duplicated exactly 3 times in the actual
iterable.
<p>To also test that the contents appear in the given order, make a call to {@code inOrder()}
on the object returned by this method.
<p>To test that the iterable contains the same elements as an array, prefer {@link
#containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list of
elements, not an element itself. This helps human readers and avoids a compiler warning. | containsExactly | 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 |
@CanIgnoreReturnValue
public final Ordered containsExactlyElementsIn(@Nullable Iterable<?> expected) {
return containsExactlyElementsIn(expected, /* addElementsInWarning= */ false);
} | Checks that the actual iterable contains exactly the provided objects.
<p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the {@code
Iterable} parameter asserts that the object must likewise be duplicated exactly 3 times in the
actual iterable.
<p>To also test that the contents appear in the given order, make a call to {@code inOrder()}
on the object returned by this method. | containsExactlyElementsIn | 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 |
public final void containsNoneOf(
@Nullable Object firstExcluded,
@Nullable Object secondExcluded,
@Nullable Object @Nullable ... restOfExcluded) {
containsNoneIn(accumulate(firstExcluded, secondExcluded, restOfExcluded));
}
/**
* Checks that the actual iterable contains none of the elements contained in the excluded
* iterable.
*/
public final void containsNoneIn(@Nullable Iterable<?> excluded) {
Collection<?> actual = iterableToCollection(checkNotNull(this.actual));
checkNotNull(excluded); // TODO(cpovirk): Produce a better exception message.
List<@Nullable Object> present = new ArrayList<>();
for (Object item : Sets.newLinkedHashSet(excluded)) {
if (actual.contains(item)) {
present.add(item);
}
}
if (!present.isEmpty()) {
failWithoutActual(
fact("expected not to contain any of", annotateEmptyStrings(excluded)),
fact("but contained", annotateEmptyStrings(present)),
fullContents());
}
} | Checks that the actual iterable contains none of the excluded objects. | containsNoneOf | 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 |
@SuppressWarnings("AvoidObjectArrays")
public final void containsNoneIn(@Nullable Object[] excluded) {
containsNoneIn(asList(excluded));
} | Checks that the actual iterable contains none of the elements contained in the excluded array. | containsNoneIn | 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 |
@SuppressWarnings({"unchecked"})
public final void isInStrictOrder(Comparator<?> comparator) {
checkNotNull(comparator);
pairwiseCheck(
"expected to be in strict order",
(prev, next) -> ((Comparator<@Nullable Object>) comparator).compare(prev, next) < 0);
} | Checks that the actual iterable is strictly ordered, according to the given comparator.
Strictly ordered means that each element in the iterable is <i>strictly</i> greater than the
element that preceded it.
@throws ClassCastException if any pair of elements is not mutually Comparable | isInStrictOrder | 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 |
@Override
@Deprecated
public void isNoneOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
super.isNoneOf(first, second, rest);
} | @deprecated You probably meant to call {@link #containsNoneOf} instead. | isNoneOf | 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 |
public <A extends @Nullable Object, E extends @Nullable Object>
UsingCorrespondence<A, E> comparingElementsUsing(
Correspondence<? super A, ? super E> correspondence) {
return new UsingCorrespondence<>(this, correspondence);
} | Starts a method chain for a check in which the actual elements (i.e. the elements of the {@link
Iterable} under test) are compared to expected elements using the given {@link Correspondence}.
The actual elements must be of type {@code A}, the expected elements must be of type {@code E}.
The check is actually executed by continuing the method chain. For example:
<pre>{@code
assertThat(actualIterable).comparingElementsUsing(correspondence).contains(expected);
}</pre>
where {@code actualIterable} is an {@code Iterable<A>} (or, more generally, an {@code
Iterable<? extends A>}), {@code correspondence} is a {@code Correspondence<A, E>}, and {@code
expected} is an {@code E}.
<p>Any of the methods on the returned object may throw {@link ClassCastException} if they
encounter an actual element that is not of type {@code A}. | comparingElementsUsing | 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 |
public <T extends @Nullable Object> UsingCorrespondence<T, T> formattingDiffsUsing(
DiffFormatter<? super T, ? super T> formatter) {
return comparingElementsUsing(Correspondence.<T>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 element (i.e. an element of the
{@link Iterable} under test) and the element it is expected to be equal to, but isn't. The
actual and expected elements must be of type {@code T}. The check is actually executed by
continuing the method chain. You may well want to use {@link
UsingCorrespondence#displayingDiffsPairedBy} to specify how the elements should be paired up
for diffing. For example:
<pre>{@code
assertThat(actualFoos)
.formattingDiffsUsing(FooTestHelper::formatDiff)
.displayingDiffsPairedBy(Foo::getId)
.containsExactly(foo1, foo2, foo3);
}</pre>
where {@code actualFoos} is an {@code Iterable<Foo>}, {@code FooTestHelper.formatDiff} is a
static method taking two {@code Foo} arguments and returning a {@link String}, {@code
Foo.getId} is a no-arg instance method returning some kind of ID, and {@code foo1}, {code
foo2}, and {@code foo3} are {@code Foo} instances.
<p>Unlike when using {@link #comparingElementsUsing}, the elements 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 an actual element that is not of type {@code T}.
@since 1.1 | formattingDiffsUsing | 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 |
@DoNotCall(
"UsingCorrespondence.equals() is not supported. Did you mean to call"
+ " containsExactlyElementsIn(expected) instead of equals(expected)?")
@Deprecated
@Override
public final boolean equals(@Nullable Object o) {
throw new UnsupportedOperationException(
"UsingCorrespondence.equals() is not supported. Did you mean to call"
+ " containsExactlyElementsIn(expected) instead of equals(expected)?");
} | @throws UnsupportedOperationException always
@deprecated {@link Object#equals(Object)} is not supported on Truth subjects or intermediate
classes. If you are writing a test assertion (actual vs. expected), use methods liks
{@link #containsExactlyElementsIn(Iterable)} instead. | equals | 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 |
@DoNotCall("UsingCorrespondence.hashCode() is not supported.")
@Deprecated
@Override
public final int hashCode() {
throw new UnsupportedOperationException("UsingCorrespondence.hashCode() is not supported.");
} | @throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported on Truth types. | hashCode | 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 |
public UsingCorrespondence<A, E> displayingDiffsPairedBy(Function<? super E, ?> keyFunction) {
@SuppressWarnings("unchecked") // throwing ClassCastException is the correct behaviour
Function<? super A, ?> actualKeyFunction = (Function<? super A, ?>) keyFunction;
return displayingDiffsPairedBy(actualKeyFunction, keyFunction);
} | Specifies a way to pair up unexpected and missing elements in the message when an assertion
fails. For example:
<pre>{@code
assertThat(actualRecords)
.comparingElementsUsing(RECORD_CORRESPONDENCE)
.displayingDiffsPairedBy(MyRecord::getId)
.containsExactlyElementsIn(expectedRecords);
}</pre>
<p><b>Important</b>: The {code keyFunction} function must be able to accept both the actual
and the unexpected elements, i.e. it must satisfy {@code Function<? super A, ?>} as well as
{@code Function<? super E, ?>}. If that constraint is not met then a subsequent method may
throw {@link ClassCastException}. Use the two-parameter overload if you need to specify
different key functions for the actual and expected elements.
<p>On assertions where it makes sense to do so, the elements are paired as follows: they are
keyed by {@code keyFunction}, and if an unexpected element and a missing element have the
same non-null key then they are paired up. (Elements with null keys are not paired.) The
failure message will show paired elements together, and a diff will be shown if the {@link
Correspondence#formatDiff} method returns non-null.
<p>The expected elements given in the assertion should be uniquely keyed by {@code
keyFunction}. If multiple missing elements have the same key then the pairing will be
skipped.
<p>Useful key functions will have the property that key equality is less strict than the
correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code
actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} is
true then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there
are cases where {@code actualKey} is equal to {@code expectedKey} but {@code
correspondence.compare(actual, expected)} is false.
<p>If the {@code apply} method on the key function throws an exception then the element will
be treated as if it had a null key and not paired. (The first such exception will be noted in
the failure message.)
<p>Note that calling this method makes no difference to whether a test passes or fails, it
just improves the message if it fails. | displayingDiffsPairedBy | 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 |
public UsingCorrespondence<A, E> displayingDiffsPairedBy(
Function<? super A, ?> actualKeyFunction, Function<? super E, ?> expectedKeyFunction) {
return new UsingCorrespondence<>(
subject, correspondence, Pairer.create(actualKeyFunction, expectedKeyFunction));
} | Specifies a way to pair up unexpected and missing elements in the message when an assertion
fails. For example:
<pre>{@code
assertThat(actualFoos)
.comparingElementsUsing(FOO_BAR_CORRESPONDENCE)
.displayingDiffsPairedBy(Foo::getId, Bar::getFooId)
.containsExactlyElementsIn(expectedBar);
}</pre>
<p>On assertions where it makes sense to do so, the elements are paired as follows: the
unexpected elements are keyed by {@code actualKeyFunction}, the missing elements are keyed by
{@code expectedKeyFunction}, and if an unexpected element and a missing element have the same
non-null key then they are paired up. (Elements with null keys are not paired.) The failure
message will show paired elements together, and a diff will be shown if the {@link
Correspondence#formatDiff} method returns non-null.
<p>The expected elements given in the assertion should be uniquely keyed by {@code
expectedKeyFunction}. If multiple missing elements have the same key then the pairing will be
skipped.
<p>Useful key functions will have the property that key equality is less strict than the
correspondence, i.e. given {@code actual} and {@code expected} values with keys {@code
actualKey} and {@code expectedKey}, if {@code correspondence.compare(actual, expected)} is
true then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, but there
are cases where {@code actualKey} is equal to {@code expectedKey} but {@code
correspondence.compare(actual, expected)} is false.
<p>If the {@code apply} method on either of the key functions throws an exception then the
element will be treated as if it had a null key and not paired. (The first such exception
will be noted in the failure message.)
<p>Note that calling this method makes no difference to whether a test passes or fails, it
just improves the message if it fails. | displayingDiffsPairedBy | 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 |
public void contains(E expected) {
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
for (A actual : getCastActual()) {
if (correspondence.safeCompare(actual, expected, exceptions)) {
// Found a match, but we still need to fail if we hit an exception along the way.
if (exceptions.hasCompareException()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.addAll(exceptions.describeAsMainCause())
.add(fact("expected to contain", expected))
.addAll(correspondence.describeForIterable())
.add(fact("found match (but failing because of exception)", actual))
.add(subject.fullContents())
.build());
}
return;
}
}
// Found no match. Fail, reporting elements that have the correct key if there are any.
if (pairer != null) {
List<A> keyMatches = pairer.pairOne(expected, getCastActual(), exceptions);
if (!keyMatches.isEmpty()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.add(fact("expected to contain", expected))
.addAll(correspondence.describeForIterable())
.add(simpleFact("but did not"))
.addAll(
formatExtras(
"though it did contain elements with correct key",
expected,
keyMatches,
exceptions))
.add(simpleFact("---"))
.add(subject.fullContents())
.addAll(exceptions.describeAsAdditionalInfo())
.build());
return;
}
}
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.add(fact("expected to contain", expected))
.addAll(correspondence.describeForIterable())
.add(subject.butWas())
.addAll(exceptions.describeAsAdditionalInfo())
.build());
} | Checks that the actual iterable contains at least one element that corresponds to the given
expected element. | contains | 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 |
public void doesNotContain(E excluded) {
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
List<A> matchingElements = new ArrayList<>();
for (A actual : getCastActual()) {
if (correspondence.safeCompare(actual, excluded, exceptions)) {
matchingElements.add(actual);
}
}
// Fail if we found any matches.
if (!matchingElements.isEmpty()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.add(fact("expected not to contain", excluded))
.addAll(correspondence.describeForIterable())
.add(fact("but contained", countDuplicates(matchingElements)))
.add(subject.fullContents())
.addAll(exceptions.describeAsAdditionalInfo())
.build());
return;
}
// Found no match, but we still need to fail if we hit an exception along the way.
if (exceptions.hasCompareException()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.addAll(exceptions.describeAsMainCause())
.add(fact("expected not to contain", excluded))
.addAll(correspondence.describeForIterable())
.add(simpleFact("found no match (but failing because of exception)"))
.add(subject.fullContents())
.build());
}
} | Checks that none of the actual elements correspond to the given element. | doesNotContain | 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 |
@SafeVarargs
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable E @Nullable ... expected) {
return containsExactlyElementsIn(expected == null ? asList((E) null) : asList(expected));
} | Checks that actual iterable contains exactly elements that correspond to the expected
elements, i.e. that there is a 1:1 mapping between the actual elements and the expected
elements where each pair of elements correspond.
<p>To also test that the contents appear in the given order, make a call to {@code inOrder()}
on the object returned by this method.
<p>To test that the iterable contains the elements corresponding to those in an array, prefer
{@link #containsExactlyElementsIn(Object[])}. It makes clear that the given array is a list
of elements, not an element itself. This helps human readers and avoids a compiler warning. | containsExactly | 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 correspondInOrderExactly(
Iterator<? extends A> actual, Iterator<? extends E> expected) {
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
while (actual.hasNext() && expected.hasNext()) {
A actualElement = actual.next();
E expectedElement = expected.next();
// Return false if the elements didn't correspond, or if the correspondence threw an
// exception. We'll fall back on the any-order assertion in this case.
if (!correspondence.safeCompare(actualElement, expectedElement, exceptions)) {
return false;
}
}
// No need to check the ExceptionStore, as we'll already have returned false on any exception.
return !(actual.hasNext() || expected.hasNext());
} | Returns whether the actual and expected iterators have the same number of elements and, when
iterated pairwise, every pair of actual and expected values satisfies the correspondence.
Returns false if any comparison threw an exception. | correspondInOrderExactly | 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 ImmutableSetMultimap<Integer, Integer> findCandidateMapping(
List<? extends A> actual,
List<? extends E> expected,
Correspondence.ExceptionStore exceptions) {
ImmutableSetMultimap.Builder<Integer, Integer> mapping = ImmutableSetMultimap.builder();
for (int actualIndex = 0; actualIndex < actual.size(); actualIndex++) {
for (int expectedIndex = 0; expectedIndex < expected.size(); expectedIndex++) {
if (correspondence.safeCompare(
actual.get(actualIndex), expected.get(expectedIndex), exceptions)) {
mapping.put(actualIndex, expectedIndex);
}
}
}
return mapping.build();
} | Given a list of actual elements and a list of expected elements, finds a many:many mapping
between actual and expected elements where a pair of elements maps if it satisfies the
correspondence. Returns this mapping as a multimap where the keys are indexes into the actual
list and the values are indexes into the expected list. Any exceptions are treated as if the
elements did not correspond, and the exception added to the store. | findCandidateMapping | 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 failIfCandidateMappingHasMissingOrExtra(
List<? extends A> actual,
List<? extends E> expected,
ImmutableSetMultimap<Integer, Integer> mapping,
Correspondence.ExceptionStore exceptions) {
List<? extends A> extra = findNotIndexed(actual, mapping.keySet());
List<? extends E> missing = findNotIndexed(expected, mapping.inverse().keySet());
if (!missing.isEmpty() || !extra.isEmpty()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.addAll(describeMissingOrExtra(missing, extra, exceptions))
.add(fact("expected", 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 actual element maps to at least one
expected element and vice versa, and fails if this is not the case. Returns whether the
assertion failed. | failIfCandidateMappingHasMissingOrExtra | 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 |
This dataset contains Java methods paired with their Javadoc comments, extracted from open-source Java repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.
Each entry includes:
code
: The source code of a java function or method.docstring
: The docstring or Javadoc associated with the function/method.func_name
: The name of the function/method.language
: The programming language (always "java").repo
: The GitHub repository from which the code was sourced (e.g., "owner/repo").path
: The file path within the repository where the function/method is located.url
: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).license
: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0").
Additional metrics if available (from Lizard tool):ccn
: Cyclomatic Complexity Number.params
: Number of parameters of the function/method.nloc
: Non-commenting lines of code.token_count
: Number of tokens in the function/method.The dataset is divided into the following splits:
train
: 1,553,016 examplesvalidation
: 15,165 examplestest
: 17,927 examplesThe data was collected by:
.java
) using tree-sitter to extract functions/methods and their docstrings/Javadoc.lizard
tool to calculate code metrics (CCN, NLOC, params).This dataset can be used for tasks such as:
The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD).
Each sample includes its original license information in the license
field.
The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0),
but users should respect the original licenses of the underlying code.
from datasets import load_dataset
# Load the dataset
dataset = load_dataset("Shuu12121/java-treesitter-dedupe_doc-filtered-dataset")
# Access a split (e.g., train)
train_data = dataset["train"]
# Print the first example
print(train_data[0])