code
stringlengths 23
201k
| docstring
stringlengths 17
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
72
| path
stringlengths 11
317
| url
stringlengths 57
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
static TolerantNumericEquality create(double tolerance) {
return new TolerantNumericEquality(tolerance);
}
|
Returns a {@link Correspondence} between {@link Number} instances that considers instances to
correspond (i.e. {@link Correspondence#compare(Object, Object)} returns {@code true}) if the
double values of each instance (i.e. the result of calling {@link Number#doubleValue()} on
them) are finite values within {@code tolerance} of each other.
<ul>
<li>It does not consider instances to correspond if either value is infinite or NaN.
<li>The conversion to double may result in a loss of precision for some numeric types.
<li>The {@link Correspondence#compare(Object, Object)} method throws a {@link
NullPointerException} if either {@link Number} instance is null.
</ul>
@param tolerance an inclusive upper bound on the difference between the double values of the
two {@link Number} instances, which must be a non-negative finite value, i.e. not {@link
Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0}
|
create
|
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
|
@SuppressWarnings("unchecked") // safe covariant cast
static <T extends @Nullable Object> Correspondence<T, T> equality() {
return (Equality<T>) Equality.INSTANCE;
}
|
Returns a correspondence which compares elements using object equality, i.e. giving the same
assertions as you would get without a correspondence. This exists so that we can add a
diff-formatting functionality to it. See e.g. {@link IterableSubject#formattingDiffsUsing}.
|
equality
|
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
|
@Override
public boolean compare(T actual, T expected) {
return Objects.equals(actual, expected);
}
|
Returns a correspondence which compares elements using object equality, i.e. giving the same
assertions as you would get without a correspondence. This exists so that we can add a
diff-formatting functionality to it. See e.g. {@link IterableSubject#formattingDiffsUsing}.
|
compare
|
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
|
@Override
public String toString() {
// This should normally not be used, since isEquality() returns true, but it should do
// something sensible anyway:
return "is equal to";
}
|
Returns a correspondence which compares elements using object equality, i.e. giving the same
assertions as you would get without a correspondence. This exists so that we can add a
diff-formatting functionality to it. See e.g. {@link IterableSubject#formattingDiffsUsing}.
|
toString
|
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
|
@Override
boolean isEquality() {
return true;
}
|
Returns a correspondence which compares elements using object equality, i.e. giving the same
assertions as you would get without a correspondence. This exists so that we can add a
diff-formatting functionality to it. See e.g. {@link IterableSubject#formattingDiffsUsing}.
|
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
|
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
|
@Override
public boolean compare(A actual, E expected) {
return delegate.compare(actual, expected);
}
|
Returns a {@link String} describing the difference between the {@code actual} and {@code
expected} values, if possible, or {@code null} if not.
|
compare
|
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
|
@Override
public @Nullable String formatDiff(A actual, E expected) {
return formatter.formatDiff(actual, expected);
}
|
Returns a {@link String} describing the difference between the {@code actual} and {@code
expected} values, if possible, or {@code null} if not.
|
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
|
@Override
public String toString() {
return delegate.toString();
}
|
Returns a {@link String} describing the difference between the {@code actual} and {@code
expected} values, if possible, or {@code null} if not.
|
toString
|
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
|
@Override
boolean isEquality() {
return delegate.isEquality();
}
|
Returns a {@link String} describing the difference between the {@code actual} and {@code
expected} values, if possible, or {@code null} if not.
|
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
|
static <A extends @Nullable Object, E extends @Nullable Object> FormattingDiffs<A, E> create(
Correspondence<A, E> delegate, DiffFormatter<? super A, ? super E> formatter) {
return new FormattingDiffs<>(delegate, formatter);
}
|
Returns a {@link String} describing the difference between the {@code actual} and {@code
expected} values, if possible, or {@code null} if not.
|
create
|
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
|
private String describe() {
return Strings.lenientFormat(
"%s(%s) threw %s\n---",
methodName, ARGUMENT_JOINER.join(methodArguments), getStackTraceAsString(exception));
}
|
Returns a String describing the exception stored. This includes a stack trace (except under
j2cl, where this is not available). It also has a separator at the end, so that when this
appears at the end of an {@code AssertionError} message, the stack trace of the stored
exception is distinguishable from the stack trace of the {@code AssertionError}.
|
describe
|
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
|
static StoredException create(Exception exception, String methodName, List<?> methodArguments) {
return new StoredException(exception, methodName, methodArguments);
}
|
Returns a String describing the exception stored. This includes a stack trace (except under
j2cl, where this is not available). It also has a separator at the end, so that when this
appears at the end of an {@code AssertionError} message, the stack trace of the stored
exception is distinguishable from the stack trace of the {@code AssertionError}.
|
create
|
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
|
static ExceptionStore forIterable() {
return new ExceptionStore("elements");
}
|
Helper object to store exceptions encountered while executing a {@link Correspondence} method.
|
forIterable
|
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
|
static ExceptionStore forMapValues() {
return new ExceptionStore("values");
}
|
Helper object to store exceptions encountered while executing a {@link Correspondence} method.
|
forMapValues
|
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
|
ImmutableList<Fact> describeAsAdditionalInfo() {
ImmutableList.Builder<Fact> builder = ImmutableList.builder();
if (firstCompareException != null) {
builder.add(
simpleFact(
"additionally, one or more exceptions were thrown while comparing "
+ argumentLabel));
builder.add(fact("first exception", firstCompareException.describe()));
}
if (firstPairingException != null) {
builder.add(
simpleFact(
"additionally, one or more exceptions were thrown while keying "
+ argumentLabel
+ " for pairing"));
builder.add(fact("first exception", firstPairingException.describe()));
}
if (firstFormatDiffException != null) {
builder.add(
simpleFact("additionally, one or more exceptions were thrown while formatting diffs"));
builder.add(fact("first exception", firstFormatDiffException.describe()));
}
return builder.build();
}
|
If any exceptions are stored, returns facts to use in a failure message when the exceptions
should be noted as additional info; if empty, returns an empty list. Assertions should use
this when exceptions were thrown while comparing elements but more meaningful failures were
discovered by assuming a false return and continuing (see the javadoc for {@link
Correspondence#compare}), or when exceptions were thrown by other methods while generating
the failure message. C.f. {@link #describeAsMainCause}.
|
describeAsAdditionalInfo
|
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
|
private static void truncateStackTrace(Exception exception, Class<?> callingClass) {
StackTraceElement[] original = exception.getStackTrace();
int keep = 0;
while (keep < original.length
&& !original[keep].getClassName().equals(callingClass.getName())) {
keep++;
}
exception.setStackTrace(Arrays.copyOf(original, keep));
}
|
If any exceptions are stored, returns facts to use in a failure message when the exceptions
should be noted as additional info; if empty, returns an empty list. Assertions should use
this when exceptions were thrown while comparing elements but more meaningful failures were
discovered by assuming a false return and continuing (see the javadoc for {@link
Correspondence#compare}), or when exceptions were thrown by other methods while generating
the failure message. C.f. {@link #describeAsMainCause}.
|
truncateStackTrace
|
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
|
private void reduceEqualLinesFromHeadAndTail(
List<String> original, List<String> revised, int contextSize) {
int head = 0;
int maxHead = min(original.size(), revised.size());
while (head < maxHead && original.get(head).equals(revised.get(head))) {
head++;
}
head = max(head - contextSize, 0);
offsetHead = head;
int tail = 0;
int maxTail = min(original.size() - head - contextSize, revised.size() - head - contextSize);
while (tail < maxTail
&& original
.get(original.size() - 1 - tail)
.equals(revised.get(revised.size() - 1 - tail))) {
tail++;
}
tail = max(tail - contextSize, 0);
offsetTail = tail;
}
|
An optimization to reduce the problem size by removing equal lines from head and tail.
|
reduceEqualLinesFromHeadAndTail
|
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 void calcUnifiedDiff(int i, int j) {
while (i > 0 || j > 0) {
if (i > 0
&& j > 0
&& original[i] == revised[j]
// Make sure the diff output is identical to the diff command line tool when there are
// multiple solutions.
&& lcs[i - 1][j - 1] + 1 > lcs[i - 1][j]
&& lcs[i - 1][j - 1] + 1 > lcs[i][j - 1]) {
unifiedDiffType.add(' ');
unifiedDiffContentId.add(original[i]);
i--;
j--;
} else if (j > 0 && (i == 0 || lcs[i][j - 1] >= lcs[i - 1][j])) {
unifiedDiffType.add('+');
unifiedDiffContentId.add(revised[j]);
j--;
} else if (i > 0 && (j == 0 || lcs[i][j - 1] < lcs[i - 1][j])) {
unifiedDiffType.add('-');
unifiedDiffContentId.add(original[i]);
i--;
}
}
Collections.reverse(unifiedDiffType);
Collections.reverse(unifiedDiffContentId);
}
|
An optimization to reduce the problem size by removing equal lines from head and tail.
|
calcUnifiedDiff
|
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 void calcReducedUnifiedDiff(int contextSize) {
// The index of the next line we're going to process in fullDiff.
int next = 0;
// The number of lines in original/revised file after the diff lines we've processed.
int lineNumOrigin = offsetHead;
int lineNumRevised = offsetHead;
while (next < unifiedDiffType.size()) {
// The start and end index of the current block in fullDiff
int start;
int end;
// The start line number of the block in original/revised file.
int startLineOrigin;
int startLineRevised;
// Find the next diff line that is not an equal line.
while (next < unifiedDiffType.size() && unifiedDiffType.get(next).equals(' ')) {
next++;
lineNumOrigin++;
lineNumRevised++;
}
if (next == unifiedDiffType.size()) {
break;
}
// Calculate the start line index of the current block in fullDiff
start = max(0, next - contextSize);
// Record the start line number in original and revised file of the current block
startLineOrigin = lineNumOrigin - (next - start - 1);
startLineRevised = lineNumRevised - (next - start - 1);
// The number of consecutive equal lines in fullDiff, we must find at least
// contextSize * 2 + 1 equal lines to identify the end of the block.
int equalLines = 0;
// Let `end` points to the last non-equal diff line
end = next;
while (next < unifiedDiffType.size() && equalLines < contextSize * 2 + 1) {
if (unifiedDiffType.get(next).equals(' ')) {
equalLines++;
lineNumOrigin++;
lineNumRevised++;
} else {
equalLines = 0;
// Record the latest non-equal diff line
end = next;
if (unifiedDiffType.get(next).equals('-')) {
lineNumOrigin++;
} else {
// line starts with "+"
lineNumRevised++;
}
}
next++;
}
// Calculate the end line index of the current block in fullDiff
end = min(end + contextSize + 1, unifiedDiffType.size());
// Calculate the size of the block content in original/revised file
int blockSizeOrigin = lineNumOrigin - startLineOrigin - (next - end - 1);
int blockSizeRevised = lineNumRevised - startLineRevised - (next - end - 1);
reducedUnifiedDiff.add(
"@@ -"
+ startLineOrigin
+ ","
+ blockSizeOrigin
+ " +"
+ startLineRevised
+ ","
+ blockSizeRevised
+ " @@");
for (int i = start; i < end; i++) {
reducedUnifiedDiff.add(
unifiedDiffType.get(i) + stringList.get(unifiedDiffContentId.get(i)));
}
}
}
|
Generate the unified diff with a given context size
@param contextSize The context size we should leave at the beginning and end of each block.
|
calcReducedUnifiedDiff
|
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
|
static List<String> generateUnifiedDiff(
List<String> original, List<String> revised, int contextSize) {
return new DiffUtils().diff(original, revised, contextSize);
}
|
Generate the unified diff with a given context size
@param contextSize The context size we should leave at the beginning and end of each block.
|
generateUnifiedDiff
|
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
|
@Deprecated
@Override
public int hashCode() {
throw new UnsupportedOperationException("Subject.hashCode() is not supported.");
}
|
@throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported on TolerantDoubleComparison
|
hashCode
|
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
|
static TolerantDoubleComparison comparing(DoubleComparer comparer) {
return new TolerantDoubleComparison(comparer);
}
|
@throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported on TolerantDoubleComparison
|
comparing
|
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
|
@Override
@Deprecated
public void isEquivalentAccordingToCompareTo(@Nullable Double other) {
super.isEquivalentAccordingToCompareTo(other);
}
|
@deprecated Use {@link #isWithin} or {@link #isEqualTo} instead (see documentation for advice).
|
isEquivalentAccordingToCompareTo
|
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
|
public void isGreaterThan(int other) {
isGreaterThan((double) other);
}
|
Checks that the actual value is greater than {@code other}.
<p>To check that the actual value is greater than <i>or equal to</i> {@code other}, use {@link
#isAtLeast}.
|
isGreaterThan
|
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 isLessThan(int other) {
isLessThan((double) 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/DoubleSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/DoubleSubject.java
|
Apache-2.0
|
public void isAtMost(int other) {
isAtMost((double) other);
}
|
Checks that the actual value is less than or equal to {@code other}.
<p>To check that the actual value is <i>strictly</i> less than {@code other}, use {@link
#isLessThan}.
|
isAtMost
|
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 isAtLeast(int other) {
isAtLeast((double) other);
}
|
Checks that the actual value is greater than or equal to {@code other}.
<p>To check that the actual value is <i>strictly</i> greater than {@code other}, use {@link
#isGreaterThan}.
|
isAtLeast
|
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
|
static Factory<DoubleSubject, Double> doubles() {
return DoubleSubject::new;
}
|
Checks that the actual value is greater than or equal to {@code other}.
<p>To check that the actual value is <i>strictly</i> greater than {@code other}, use {@link
#isGreaterThan}.
|
doubles
|
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 TruthFailureSubject assertThat(@Nullable AssertionError actual) {
return assertAbout(truthFailures()).that(actual);
}
|
Creates a subject for asserting about the given {@link AssertionError}, usually one produced by
Truth.
|
assertThat
|
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
|
@Override
@GwtIncompatible("org.junit.rules.TestRule")
@J2ktIncompatible
public Statement apply(Statement base, Description description) {
checkNotNull(base);
checkNotNull(description);
return new Statement() {
@Override
public void evaluate() throws Throwable {
enterRuleContext();
try {
base.evaluate();
} finally {
leaveRuleContext();
}
ensureFailureCaught();
}
};
}
|
Creates a subject for asserting about the given {@link AssertionError}, usually one produced by
Truth.
|
apply
|
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
|
@Override
public void evaluate() throws Throwable {
enterRuleContext();
try {
base.evaluate();
} finally {
leaveRuleContext();
}
ensureFailureCaught();
}
|
Creates a subject for asserting about the given {@link AssertionError}, usually one produced by
Truth.
|
evaluate
|
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 String makeMessage(ImmutableList<String> messages, ImmutableList<Fact> facts) {
int longestKeyLength = 0;
int longestIntPartValueLength = 0;
boolean seenNewlineInValue = false;
for (Fact fact : facts) {
if (fact.value != null) {
longestKeyLength = max(longestKeyLength, fact.key.length());
if (fact.padStart) {
int decimalIndex = fact.value.indexOf('.');
if (decimalIndex != -1) {
longestIntPartValueLength = max(longestIntPartValueLength, decimalIndex);
} else {
longestIntPartValueLength = max(longestIntPartValueLength, fact.value.length());
}
}
// TODO(cpovirk): Look for other kinds of newlines.
seenNewlineInValue |= fact.value.contains("\n");
}
}
StringBuilder builder = new StringBuilder();
for (String message : messages) {
builder.append(message);
builder.append('\n');
}
/*
* *Usually* the first fact is printed at the beginning of a new line. However, when this
* exception is the cause of another exception, that exception will print it starting after
* "Caused by: " on the same line. The other exception sometimes also reuses this message as its
* own message. In both of those scenarios, the first line doesn't start at column 0, so the
* horizontal alignment is thrown off.
*
* There's not much we can do about this, short of always starting with a newline (which would
* leave a blank line at the beginning of the message in the normal case).
*/
for (Fact fact : facts) {
if (fact.value == null) {
builder.append(fact.key);
} else if (seenNewlineInValue) {
builder.append(fact.key);
builder.append(":\n");
builder.append(indent(fact.value));
} else {
builder.append(padEnd(fact.key, longestKeyLength, ' '));
builder.append(": ");
if (fact.padStart) {
int decimalIndex = fact.value.indexOf('.');
if (decimalIndex != -1) {
builder.append(
padStart(fact.value.substring(0, decimalIndex), longestIntPartValueLength, ' '));
builder.append(fact.value.substring(decimalIndex));
} else {
builder.append(padStart(fact.value, longestIntPartValueLength, ' '));
}
} else {
builder.append(fact.value);
}
}
builder.append('\n');
}
if (builder.length() > 0) {
builder.setLength(builder.length() - 1); // remove trailing \n
}
return builder.toString();
}
|
Formats the given messages and facts into a string for use as the message of a test failure. In
particular, this method horizontally aligns the beginning of fact values.
|
makeMessage
|
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
|
private static String indent(String value) {
// We don't want to indent with \t because the text would align exactly with the stack trace.
// We don't want to indent with \t\t because it would be very far for people with 8-space tabs.
// Let's compromise and indent by 4 spaces, which is different than both 2- and 8-space tabs.
return " " + value.replace("\n", "\n ");
}
|
Formats the given messages and facts into a string for use as the message of a test failure. In
particular, this method horizontally aligns the beginning of fact values.
|
indent
|
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
|
static Step subjectCreation(Subject subject) {
return new Step(checkNotNull(subject), null, null);
}
|
The data from a call to either (a) a {@link Subject} constructor or (b) {@link Subject#check}.
|
subjectCreation
|
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
|
static Step checkCall(
@Nullable OldAndNewValuesAreSimilar valuesAreSimilar,
@Nullable Function<String, String> descriptionUpdate) {
return new Step(null, descriptionUpdate, valuesAreSimilar);
}
|
The data from a call to either (a) a {@link Subject} constructor or (b) {@link Subject#check}.
|
checkCall
|
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
|
boolean isCheckCall() {
return subject == null;
}
|
The data from a call to either (a) a {@link Subject} constructor or (b) {@link Subject#check}.
|
isCheckCall
|
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
|
FailureMetadata updateForSubject(Subject subject) {
ImmutableList<Step> steps = append(this.steps, Step.subjectCreation(subject));
return derive(messages, steps);
}
|
Returns a new instance that includes the given subject in its chain of values. Truth users do
not need to call this method directly; Truth automatically accumulates context, starting from
the initial that(...) call and continuing into any chained calls, like {@link
ThrowableSubject#hasMessageThat}.
|
updateForSubject
|
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
|
FailureMetadata updateForCheckCall() {
ImmutableList<Step> steps = append(this.steps, Step.checkCall(null, null));
return derive(messages, steps);
}
|
Returns a new instance that includes the given subject in its chain of values. Truth users do
not need to call this method directly; Truth automatically accumulates context, starting from
the initial that(...) call and continuing into any chained calls, like {@link
ThrowableSubject#hasMessageThat}.
|
updateForCheckCall
|
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
|
FailureMetadata updateForCheckCall(
OldAndNewValuesAreSimilar valuesAreSimilar, Function<String, String> descriptionUpdate) {
checkNotNull(descriptionUpdate);
ImmutableList<Step> steps =
append(this.steps, Step.checkCall(valuesAreSimilar, descriptionUpdate));
return derive(messages, steps);
}
|
Returns a new instance that includes the given subject in its chain of values. Truth users do
not need to call this method directly; Truth automatically accumulates context, starting from
the initial that(...) call and continuing into any chained calls, like {@link
ThrowableSubject#hasMessageThat}.
|
updateForCheckCall
|
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
|
FailureMetadata withMessage(String format, @Nullable Object[] args) {
ImmutableList<LazyMessage> messages = append(this.messages, LazyMessage.create(format, args));
return derive(messages, steps);
}
|
Returns a new instance whose failures will contain the given message. The way for Truth users
to set a message is {@code check(...).withMessage(...).that(...)} (for calls from within a
{@code Subject}) or {@link Truth#assertWithMessage} (for most other calls).
|
withMessage
|
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
|
void failEqualityCheck(ImmutableList<Fact> tailFacts, String expected, String actual) {
doFail(
makeComparisonFailure(
evaluateAll(messages),
makeComparisonFailureFacts(
description(), concat(tailFacts, rootUnlessThrowable()), expected, actual),
expected,
actual,
rootCause()));
}
|
Returns a new instance whose failures will contain the given message. The way for Truth users
to set a message is {@code check(...).withMessage(...).that(...)} (for calls from within a
{@code Subject}) or {@link Truth#assertWithMessage} (for most other calls).
|
failEqualityCheck
|
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
|
void fail(ImmutableList<Fact> facts) {
doFail(
AssertionErrorWithFacts.create(
evaluateAll(messages),
concat(description(), facts, rootUnlessThrowable()),
rootCause()));
}
|
Returns a new instance whose failures will contain the given message. The way for Truth users
to set a message is {@code check(...).withMessage(...).that(...)} (for calls from within a
{@code Subject}) or {@link Truth#assertWithMessage} (for most other calls).
|
fail
|
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
|
void failForNullThrowable(String message) {
doFail(
AssertionErrorWithFacts.create(
evaluateAll(messages),
concat(
// unusual case: put a fact *before* the description
ImmutableList.of(simpleFact(message)),
description(/* factKey= */ "null Throwable was"),
rootUnlessThrowable()),
rootCause()));
}
|
Special failure method for {@link ThrowableSubject} to use when users try to assert about the
cause or message of a null {@link Throwable}.
|
failForNullThrowable
|
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 void doFail(AssertionError failure) {
cleanStackTrace(failure);
strategy.fail(failure);
}
|
Special failure method for {@link ThrowableSubject} to use when users try to assert about the
cause or message of a null {@link Throwable}.
|
doFail
|
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 FailureMetadata derive(ImmutableList<LazyMessage> messages, ImmutableList<Step> steps) {
return new FailureMetadata(strategy, messages, steps);
}
|
Special failure method for {@link ThrowableSubject} to use when users try to assert about the
cause or message of a null {@link Throwable}.
|
derive
|
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
|
@Deprecated
@Override
public int hashCode() {
throw new UnsupportedOperationException("Subject.hashCode() is not supported.");
}
|
@throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported on TolerantFloatComparison
|
hashCode
|
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 TolerantFloatComparison create(FloatComparer comparer) {
return new TolerantFloatComparison(comparer);
}
|
@throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported on TolerantFloatComparison
|
create
|
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
|
@Override
@Deprecated
public void isEquivalentAccordingToCompareTo(@Nullable Float other) {
super.isEquivalentAccordingToCompareTo(other);
}
|
@deprecated Use {@link #isWithin} or {@link #isEqualTo} instead (see documentation for advice).
|
isEquivalentAccordingToCompareTo
|
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
|
public void isGreaterThan(int other) {
/*
* We must perform the comparison as a `double` in order to compare `float` to `int` without
* loss of precision.
*
* The only downside to delegating to `DoubleSubject` should be that we may display the actual
* value with greater precision than would be required to uniquely identify it as a `float`.
* (Similarly, we will display the `int` as a `double`. But that may be just as well for
* consistency reasons.)
*
* We could instead perform the comparison manually here, but it would require duplicating the
* code from `ComparableSubject.isGreaterThan`.
*/
asDouble.isGreaterThan(other);
}
|
Checks that the actual value is greater than {@code other}.
<p>To check that the actual value is greater than <i>or equal to</i> {@code other}, use {@link
#isAtLeast}.
|
isGreaterThan
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.