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 |
|---|---|---|---|---|---|---|---|
public void isLessThan(int other) {
// For discussion of this delegation, see isGreaterThan.
asDouble.isLessThan(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/FloatSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java
|
Apache-2.0
|
public void isAtMost(int other) {
// For discussion of this delegation, see isGreaterThan.
asDouble.isAtMost(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/FloatSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java
|
Apache-2.0
|
public void isAtLeast(int other) {
// For discussion of this delegation, see isGreaterThan.
asDouble.isAtLeast(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/FloatSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/FloatSubject.java
|
Apache-2.0
|
static Factory<FloatSubject, Float> floats() {
return FloatSubject::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}.
|
floats
|
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
|
public void isPresent() {
if (actual == null) {
failWithActual(simpleFact("expected present optional"));
} else if (!actual.isPresent()) {
failWithoutActual(simpleFact("expected to be present"));
}
}
|
Checks that the actual {@link Optional} contains a value.
|
isPresent
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
|
Apache-2.0
|
public void isAbsent() {
if (actual == null) {
failWithActual(simpleFact("expected absent optional"));
} else if (actual.isPresent()) {
failWithoutActual(
simpleFact("expected to be absent"), fact("but was present with value", actual.get()));
}
}
|
Checks that the actual {@link Optional} does not contain a value.
|
isAbsent
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
|
Apache-2.0
|
public void hasValue(@Nullable Object expected) {
if (expected == null) {
failWithoutActual(
simpleFact("expected an optional with a null value, but that is impossible"),
fact("was", actual));
} else if (actual == null) {
failWithActual("expected an optional with value", expected);
} else if (!actual.isPresent()) {
failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent"));
} else {
checkNoNeedToDisplayBothValues("get()").that(actual.get()).isEqualTo(expected);
}
}
|
Checks that the actual {@link Optional} contains the given value.
<p>To make more complex assertions on the optional's value, split your assertion in two:
<pre>{@code
assertThat(myOptional).isPresent();
assertThat(myOptional.get()).contains("foo");
}</pre>
|
hasValue
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
|
Apache-2.0
|
static Factory<GuavaOptionalSubject, Optional<?>> guavaOptionals() {
return GuavaOptionalSubject::new;
}
|
Checks that the actual {@link Optional} contains the given value.
<p>To make more complex assertions on the optional's value, split your assertion in two:
<pre>{@code
assertThat(myOptional).isPresent();
assertThat(myOptional.get()).contains("foo");
}</pre>
|
guavaOptionals
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/GuavaOptionalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/GuavaOptionalSubject.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
@Override
public int hashCode() {
throw new UnsupportedOperationException("Subject.hashCode() is not supported.");
}
|
@throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported on TolerantIntegerComparison
|
hashCode
|
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
|
static TolerantIntegerComparison create(IntegerComparer comparer) {
return new TolerantIntegerComparison(comparer);
}
|
@throws UnsupportedOperationException always
@deprecated {@link Object#hashCode()} is not supported on TolerantIntegerComparison
|
create
|
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
|
public TolerantIntegerComparison isWithin(int tolerance) {
return TolerantIntegerComparison.create(
other -> {
if (tolerance < 0) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is negative"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (actual == null) {
failWithoutActual(
numericFact("expected a 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 number within the given tolerance of an
expected value that will be provided in the next call in the fluent chain.
@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 value.
@since 1.2
|
isWithin
|
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
|
public TolerantIntegerComparison isNotWithin(int tolerance) {
return TolerantIntegerComparison.create(
other -> {
if (tolerance < 0) {
failWithoutActual(
simpleFact(
"could not perform approximate-equality check because tolerance is negative"),
numericFact("expected", other),
numericFact("was", actual),
numericFact("tolerance", tolerance));
} else if (actual == null) {
failWithoutActual(
numericFact("expected a value that is not near", other),
numericFact("but was", actual),
numericFact("tolerance", tolerance));
} else if (equalWithinTolerance(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 number not within the given tolerance of an
expected value that will be provided in the next call in the fluent chain.
@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 value.
@since 1.2
|
isNotWithin
|
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
|
@Override
@Deprecated
public final void isEquivalentAccordingToCompareTo(@Nullable Integer other) {
super.isEquivalentAccordingToCompareTo(other);
}
|
@deprecated Use {@link #isEqualTo} instead. Integer comparison is consistent with equality.
|
isEquivalentAccordingToCompareTo
|
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
|
static Factory<IntegerSubject, Integer> integers() {
return IntegerSubject::new;
}
|
@deprecated Use {@link #isEqualTo} instead. Integer comparison is consistent with equality.
|
integers
|
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
|
@SuppressWarnings("GoodTime") // false positive; b/122617528
public void containsAnyOf(int first, int second, int... rest) {
checkThatContentsList().containsAnyOf(first, second, box(rest));
}
|
Checks that the actual stream contains at least one of the given elements.
|
containsAnyOf
|
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
|
@SuppressWarnings("GoodTime") // false positive; b/122617528
@CanIgnoreReturnValue
public Ordered containsAtLeast(int first, int second, int... rest) {
return checkThatContentsList().containsAtLeast(first, second, box(rest));
}
|
Checks that the actual stream contains all of the given elements. If an element appears more
than once in the given elements, 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/IntStreamSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IntStreamSubject.java
|
Apache-2.0
|
@CanIgnoreReturnValue
public Ordered containsAtLeastElementsIn(@Nullable Iterable<?> expected) {
return checkThatContentsList().containsAtLeastElementsIn(expected);
}
|
Checks that the actual stream contains all of the given elements. If an element appears more
than once in the given elements, 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.
|
containsAtLeastElementsIn
|
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
|
@CanIgnoreReturnValue
public Ordered containsExactlyElementsIn(@Nullable Iterable<?> expected) {
return checkThatContentsList().containsExactlyElementsIn(expected);
}
|
Checks that the actual stream contains exactly the given elements.
<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
stream.
<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/IntStreamSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IntStreamSubject.java
|
Apache-2.0
|
@SuppressWarnings("GoodTime") // false positive; b/122617528
public void containsNoneOf(int first, int second, int... rest) {
checkThatContentsList().containsNoneOf(first, second, box(rest));
}
|
Checks that the actual stream does not contain any of the given elements.
|
containsNoneOf
|
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
|
private IterableSubject checkThatContentsList() {
return substituteCheck().that(listSupplier.get());
}
|
Be careful with using this, as documented on {@link Subject#substituteCheck}.
|
checkThatContentsList
|
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
|
private static Supplier<@Nullable List<?>> listCollector(@Nullable IntStream actual) {
return () -> actual == null ? null : actual.boxed().collect(toCollection(ArrayList::new));
}
|
Be careful with using this, as documented on {@link Subject#substituteCheck}.
|
listCollector
|
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
|
private static Object[] box(int[] rest) {
return IntStream.of(rest).boxed().toArray(Integer[]::new);
}
|
Be careful with using this, as documented on {@link Subject#substituteCheck}.
|
box
|
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
|
@Override
protected String actualCustomStringRepresentation() {
if (actual != null) {
// Check the value of iterable.toString() against the default Object.toString() implementation
// so that we can avoid things like
// "com.google.common.graph.Traverser$GraphTraverser$1@5e316c74"
String objectToString =
actual.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(actual));
if (actual.toString().equals(objectToString)) {
return Iterables.toString(actual);
}
}
return super.actualCustomStringRepresentation();
}
|
Constructor for use by subclasses. If you want to create an instance of this class itself, call
{@link Subject#check(String, Object...) check(...)}{@code .that(actual)}.
|
actualCustomStringRepresentation
|
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
public void isEqualTo(@Nullable Object expected) {
@SuppressWarnings("UndefinedEquals") // method contract requires testing iterables for equality
boolean equal = Objects.equals(actual, expected);
if (equal) {
return;
}
// Fail but with a more descriptive message:
if (actual instanceof List && expected instanceof List) {
containsExactlyElementsIn((List<?>) expected).inOrder();
} else if ((actual instanceof Set && expected instanceof Set)
|| (actual instanceof Multiset && expected instanceof Multiset)) {
containsExactlyElementsIn((Collection<?>) expected);
} else {
/*
* TODO(b/18430105): Consider a special message if comparing incompatible collection types
* (similar to what MultimapSubject has).
*/
super.isEqualTo(expected);
}
}
|
Constructor for use by subclasses. If you want to create an instance of this class itself, call
{@link Subject#check(String, Object...) check(...)}{@code .that(actual)}.
|
isEqualTo
|
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 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
|
@SuppressWarnings("BuilderCollapser")
@CanIgnoreReturnValue
public final Ordered containsAtLeastElementsIn(@Nullable Iterable<?> expectedIterable) {
List<?> actual = Lists.newLinkedList(checkNotNull(this.actual));
Collection<?> expected = iterableToCollection(expectedIterable);
List<@Nullable Object> missing = new ArrayList<>();
List<@Nullable Object> actualNotInOrder = new ArrayList<>();
boolean ordered = true;
// step through the expected elements...
for (Object e : expected) {
int index = actual.indexOf(e);
if (index != -1) { // if we find the element in the actual list...
// drain all the elements that come before that element into actualNotInOrder
moveElements(actual, actualNotInOrder, index);
// and remove the element from the actual list
actual.remove(0);
} else { // otherwise try removing it from actualNotInOrder...
if (actualNotInOrder.remove(e)) { // if it was in actualNotInOrder, we're not in order
ordered = false;
} else { // if it's not in actualNotInOrder, we're missing an expected element
missing.add(e);
}
}
}
// if we have any missing expected elements, fail
if (!missing.isEmpty()) {
return failAtLeast(expected, missing);
}
return ordered
? IN_ORDER
: () -> {
ImmutableList.Builder<Fact> facts = ImmutableList.builder();
facts.add(simpleFact("required elements were all found, but order was wrong"));
facts.add(fact("expected order for required elements", expected));
List<Object> actualOrder = newArrayList(checkNotNull(IterableSubject.this.actual));
if (actualOrder.retainAll(expected)) {
facts.add(fact("but order was", actualOrder));
facts.add(fullContents());
failWithoutActual(facts.build());
} else {
failWithActual(facts.build());
}
};
}
|
Checks that the actual iterable contains at least all the expected elements. If an element
appears more than once in the expected elements 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.
|
containsAtLeastElementsIn
|
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
@SuppressWarnings("AvoidObjectArrays")
public final Ordered containsAtLeastElementsIn(@Nullable Object[] expected) {
return containsAtLeastElementsIn(asList(expected));
}
|
Checks that the actual iterable contains at least all the expected elements. If an element
appears more than once in the expected elements 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.
|
containsAtLeastElementsIn
|
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 Ordered failAtLeast(Collection<?> expected, Collection<?> missingRawObjects) {
List<?> nearMissRawObjects =
retainMatchingToString(checkNotNull(actual), /* itemsToCheck= */ missingRawObjects);
ImmutableList.Builder<Fact> facts = ImmutableList.builder();
facts.addAll(
makeElementFactsForBoth(
"missing", missingRawObjects, "though it did contain", nearMissRawObjects));
/*
* TODO(cpovirk): Make makeElementFactsForBoth support generating just "though it did contain"
* rather than "though it did contain (2)?" Users might interpret the number as the *total*
* number of actual elements (or the total number of non-matched elements). (Frankly, they might
* think that even *without* the number.... Can we do better than the phrase "though it did
* contain," which has been our standard so far?) Or maybe it's all clear enough in context,
* since this error shows up only to inform users of type mismatches.
*/
facts.add(fact("expected to contain at least", expected));
facts.add(butWas());
failWithoutActual(facts.build());
return ALREADY_FAILED;
}
|
Checks that the actual iterable contains at least all the expected elements. If an element
appears more than once in the expected elements 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.
|
failAtLeast
|
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
|
@CanIgnoreReturnValue
@SuppressWarnings({
"AvoidObjectArrays",
"ContainsExactlyElementsInUnnecessaryWrapperAroundArray",
"ContainsExactlyElementsInWithVarArgsToExactly"
})
public final Ordered containsExactlyElementsIn(@Nullable Object @Nullable [] expected) {
return containsExactlyElementsIn(asList(checkNotNull(expected)));
}
|
Checks that the actual iterable contains exactly the provided objects.
<p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array
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
|
private Ordered containsExactlyElementsIn(
@Nullable Iterable<?> required, boolean addElementsInWarning) {
checkNotNull(required);
Iterator<?> actualIter = checkNotNull(actual).iterator();
Iterator<?> requiredIter = required.iterator();
if (!requiredIter.hasNext()) {
if (actualIter.hasNext()) {
isEmpty(); // fails
return ALREADY_FAILED;
} else {
return IN_ORDER;
}
}
// Step through both iterators comparing elements pairwise.
boolean isFirst = true;
while (actualIter.hasNext() && requiredIter.hasNext()) {
Object actualElement = actualIter.next();
Object requiredElement = requiredIter.next();
// As soon as we encounter a pair of elements that differ, we know that inOrder()
// cannot succeed, so we can check the rest of the elements more normally.
// Since any previous pairs of elements we iterated over were equal, they have no
// effect on the result now.
if (!Objects.equals(actualElement, requiredElement)) {
if (isFirst && !actualIter.hasNext() && !requiredIter.hasNext()) {
/*
* There's exactly one actual element and exactly one expected element, and they don't
* match, so throw a ComparisonFailure. The logical way to do that would be
* `check(...).that(actualElement).isEqualTo(requiredElement)`. But isEqualTo has magic
* behavior for arrays and primitives, behavior that's inconsistent with how this method
* otherwise behaves. For consistency, we want to rely only on the equal() call we've
* already made. So we expose a special method for this and call it from here.
*
* TODO(b/135918662): Consider always throwing ComparisonFailure if there is exactly one
* missing and exactly one extra element, even if there were additional (matching)
* elements. However, this will probably be useful less often, and it will be tricky to
* explain. First, what would we say, "value of: iterable.onlyElementThatDidNotMatch()?"
* And second, it feels weirder to call out a single element when the expected and actual
* values had multiple elements. Granted, Fuzzy Truth already does this, so maybe it's OK?
* But Fuzzy Truth doesn't (yet) make the mismatched value so prominent.
*/
checkNoNeedToDisplayBothValues("onlyElement()")
.that(actualElement)
.failEqualityCheckForEqualsWithoutDescription(requiredElement);
return ALREADY_FAILED;
}
// Missing elements; elements that are not missing will be removed as we iterate.
List<@Nullable Object> missing = new ArrayList<>();
missing.add(requiredElement);
Iterators.addAll(missing, requiredIter);
// Extra elements that the actual iterable had but shouldn't have.
List<@Nullable Object> extra = new ArrayList<>();
// Remove all actual elements from missing, and add any that weren't in missing
// to extra.
if (!missing.remove(actualElement)) {
extra.add(actualElement);
}
while (actualIter.hasNext()) {
Object item = actualIter.next();
if (!missing.remove(item)) {
extra.add(item);
}
}
if (missing.isEmpty() && extra.isEmpty()) {
/*
* This containsExactly() call is a success. But the iterables were not in the same order,
* so return an object that will fail the test if the user calls inOrder().
*/
return () ->
failWithActual(
simpleFact("contents match, but order was wrong"), fact("expected", required));
}
return failExactly(required, addElementsInWarning, missing, extra);
}
isFirst = false;
}
// Here, we must have reached the end of one of the iterators without finding any
// pairs of elements that differ. If the actual iterator still has elements, they're
// extras. If the required iterator has elements, they're missing elements.
if (actualIter.hasNext()) {
return failExactly(
required,
addElementsInWarning,
/* missingRawObjects= */ ImmutableList.of(),
/* extraRawObjects= */ newArrayList(actualIter));
} else if (requiredIter.hasNext()) {
return failExactly(
required,
addElementsInWarning,
/* missingRawObjects= */ newArrayList(requiredIter),
/* extraRawObjects= */ ImmutableList.of());
}
// If neither iterator has elements, we reached the end and the elements were in
// order, so inOrder() can just succeed.
return IN_ORDER;
}
|
Checks that the actual iterable contains exactly the provided objects.
<p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array
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
|
private Ordered failExactly(
Iterable<?> required,
boolean addElementsInWarning,
Collection<?> missingRawObjects,
Collection<?> extraRawObjects) {
ImmutableList.Builder<Fact> facts = ImmutableList.builder();
facts.addAll(
makeElementFactsForBoth("missing", missingRawObjects, "unexpected", extraRawObjects));
facts.add(fact("expected", required));
facts.add(butWas());
if (addElementsInWarning) {
facts.add(
simpleFact(
"Passing an iterable to the varargs method containsExactly(Object...) is "
+ "often not the correct thing to do. Did you mean to call "
+ "containsExactlyElementsIn(Iterable) instead?"));
}
failWithoutActual(facts.build());
return ALREADY_FAILED;
}
|
Checks that the actual iterable contains exactly the provided objects.
<p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array
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.
|
failExactly
|
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 ImmutableList<Fact> makeElementFactsForBoth(
String firstKey,
Collection<?> firstCollection,
String secondKey,
Collection<?> secondCollection) {
// TODO(kak): Possible enhancement: Include "[1 copy]" if the element does appear in
// the actual iterable but not enough times. Similarly for unexpected extra items.
boolean addTypeInfo = hasMatchingToStringPair(firstCollection, secondCollection);
DuplicateGroupedAndTyped first =
countDuplicatesAndMaybeAddTypeInfoReturnObject(firstCollection, addTypeInfo);
DuplicateGroupedAndTyped second =
countDuplicatesAndMaybeAddTypeInfoReturnObject(secondCollection, addTypeInfo);
ElementFactGrouping grouping = pickGrouping(first.entrySet(), second.entrySet());
ImmutableList.Builder<Fact> facts = ImmutableList.builder();
ImmutableList<Fact> firstFacts = makeElementFacts(firstKey, first, grouping);
ImmutableList<Fact> secondFacts = makeElementFacts(secondKey, second, grouping);
facts.addAll(firstFacts);
if (firstFacts.size() > 1 && secondFacts.size() > 1) {
facts.add(simpleFact(""));
}
facts.addAll(secondFacts);
facts.add(simpleFact("---"));
return facts.build();
}
|
Checks that the actual iterable contains exactly the provided objects.
<p>Multiplicity is respected. For example, an object duplicated exactly 3 times in the array
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.
|
makeElementFactsForBoth
|
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 ImmutableList<Fact> makeElementFacts(
String label, DuplicateGroupedAndTyped elements, ElementFactGrouping grouping) {
if (elements.isEmpty()) {
return ImmutableList.of();
}
if (grouping == ALL_IN_ONE_FACT) {
return ImmutableList.of(fact(keyToGoWithElementsString(label, elements), elements));
}
ImmutableList.Builder<Fact> facts = ImmutableList.builder();
facts.add(simpleFact(keyToServeAsHeader(label, elements)));
int n = 1;
for (Multiset.Entry<?> entry : elements.entrySet()) {
int count = entry.getCount();
Object item = entry.getElement();
facts.add(fact(numberString(n, count), item));
n += count;
}
return facts.build();
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
makeElementFacts
|
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 String keyToGoWithElementsString(String label, DuplicateGroupedAndTyped elements) {
/*
* elements.toString(), which the caller is going to use, includes the homogeneous type (if
* any), so we don't want to include it here. (And it's better to have it in the value, rather
* than in the key, so that it doesn't push the horizontally aligned values over too far.)
*/
return lenientFormat("%s (%s)", label, elements.totalCopies());
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
keyToGoWithElementsString
|
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 String keyToServeAsHeader(String label, DuplicateGroupedAndTyped elements) {
/*
* The caller of this method outputs each individual element manually (as opposed to calling
* elements.toString()), so the homogeneous type isn't present unless we add it. Fortunately, we
* can add it here without pushing the horizontally aligned values over, as this key won't have
* an associated value, so it won't factor into alignment.
*/
String key = keyToGoWithElementsString(label, elements);
if (elements.getHomogeneousTypeToDisplay() != null) {
key += " (" + elements.getHomogeneousTypeToDisplay() + ")";
}
return key;
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
keyToServeAsHeader
|
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 String numberString(int n, int count) {
return count == 1 ? lenientFormat("#%s", n) : lenientFormat("#%s [%s copies]", n, count);
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
numberString
|
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 ElementFactGrouping pickGrouping(
Iterable<Multiset.Entry<?>> first, Iterable<Multiset.Entry<?>> second) {
boolean firstHasMultiple = hasMultiple(first);
boolean secondHasMultiple = hasMultiple(second);
if ((firstHasMultiple || secondHasMultiple) && anyContainsCommaOrNewline(first, second)) {
return FACT_PER_ELEMENT;
}
if (firstHasMultiple && containsEmptyOrLong(first)) {
return FACT_PER_ELEMENT;
}
if (secondHasMultiple && containsEmptyOrLong(second)) {
return FACT_PER_ELEMENT;
}
return ALL_IN_ONE_FACT;
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
pickGrouping
|
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 boolean anyContainsCommaOrNewline(Iterable<Multiset.Entry<?>>... lists) {
for (Multiset.Entry<?> entry : concat(lists)) {
String s = String.valueOf(entry.getElement());
if (s.contains("\n") || s.contains(",")) {
return true;
}
}
return false;
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
anyContainsCommaOrNewline
|
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 boolean hasMultiple(Iterable<Multiset.Entry<?>> entries) {
int totalCount = 0;
for (Multiset.Entry<?> entry : entries) {
totalCount += entry.getCount();
if (totalCount > 1) {
return true;
}
}
return false;
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
hasMultiple
|
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 boolean containsEmptyOrLong(Iterable<Multiset.Entry<?>> entries) {
int totalLength = 0;
for (Multiset.Entry<?> entry : entries) {
String s = entryString(entry);
if (s.isEmpty()) {
return true;
}
totalLength += s.length();
}
return totalLength > 200;
}
|
Returns a list of facts (zero, one, or many, depending on the number of elements and the
grouping policy) describing the given missing, unexpected, or near-miss elements.
|
containsEmptyOrLong
|
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
|
@SuppressWarnings({"unchecked"})
public final void isInOrder(Comparator<?> comparator) {
checkNotNull(comparator);
pairwiseCheck(
"expected to be in order",
(prev, next) -> ((Comparator<@Nullable Object>) comparator).compare(prev, next) <= 0);
}
|
Checks that the actual iterable is ordered, according to the given comparator. Ordered means
that each element in the iterable is greater than or equal to the element that preceded it.
@throws ClassCastException if any pair of elements is not mutually Comparable
|
isInOrder
|
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 void pairwiseCheck(String expectedFact, PairwiseChecker checker) {
Iterator<?> iterator = checkNotNull(actual).iterator();
if (iterator.hasNext()) {
Object prev = iterator.next();
while (iterator.hasNext()) {
Object next = iterator.next();
if (!checker.check(prev, next)) {
failWithoutActual(
simpleFact(expectedFact),
fact("but contained", prev),
fact("followed by", next),
fullContents());
return;
}
prev = next;
}
}
}
|
Checks that the actual iterable is ordered, according to the given comparator. Ordered means
that each element in the iterable is greater than or equal to the element that preceded it.
@throws ClassCastException if any pair of elements is not mutually Comparable
|
pairwiseCheck
|
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
|
@Override
@Deprecated
public void isNotIn(@Nullable Iterable<?> iterable) {
checkNotNull(iterable);
if (Iterables.contains(iterable, actual)) {
failWithActual("expected not to be any of", iterable);
}
List<@Nullable Object> nonIterables = new ArrayList<>();
for (Object element : iterable) {
if (!(element instanceof Iterable<?>)) {
nonIterables.add(element);
}
}
if (!nonIterables.isEmpty()) {
failWithoutActual(
simpleFact(
lenientFormat(
"The actual value is an Iterable, and you've written a test that compares it to "
+ "some objects that are not Iterables. Did you instead mean to check "
+ "whether its *contents* match any of the *contents* of the given values? "
+ "If so, call containsNoneOf(...)/containsNoneIn(...) instead. "
+ "Non-iterables: %s",
nonIterables)));
}
}
|
@deprecated You probably meant to call {@link #containsNoneIn} instead.
|
isNotIn
|
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 Fact fullContents() {
return fact("full contents", actualCustomStringRepresentationForPackageMembersToCall());
}
|
@deprecated You probably meant to call {@link #containsNoneIn} instead.
|
fullContents
|
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
|
@Deprecated
@DoNotCall("UsingCorrespondence.toString() is not supported.")
@Override
public final String toString() {
throw new UnsupportedOperationException(
"UsingCorrespondence.toString() is not supported. Did you mean to call"
+ " assertThat(foo.toString()) instead of assertThat(foo).toString()?");
}
|
@throws UnsupportedOperationException always
@deprecated {@link Object#toString()} is not supported on Truth subjects.
|
toString
|
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
|
@CanIgnoreReturnValue
public Ordered containsExactlyElementsIn(@Nullable Iterable<? extends E> expected) {
List<A> actualList = iterableToList(getCastActual());
List<? extends E> expectedList = iterableToList(checkNotNull(expected));
if (expectedList.isEmpty()) {
if (actualList.isEmpty()) {
return IN_ORDER;
} else {
subject.isEmpty(); // fails
return ALREADY_FAILED;
}
}
// Check if the elements correspond in order. This allows the common case of a passing test
// using inOrder() to complete in linear time.
if (correspondInOrderExactly(actualList.iterator(), expectedList.iterator())) {
return IN_ORDER;
}
// We know they don't correspond in order, so we're going to have to do an any-order test.
// Find a many:many mapping between the indexes of the elements which correspond, and check
// it for completeness.
// Exceptions from Correspondence.compare are stored and treated as if false was returned.
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
ImmutableSetMultimap<Integer, Integer> candidateMapping =
findCandidateMapping(actualList, expectedList, exceptions);
if (failIfCandidateMappingHasMissingOrExtra(
actualList, expectedList, candidateMapping, exceptions)) {
return ALREADY_FAILED;
}
// We know that every expected element maps to at least one actual element, and vice versa.
// Find a maximal 1:1 mapping, and check it for completeness.
ImmutableBiMap<Integer, Integer> maximalOneToOneMapping =
findMaximalOneToOneMapping(candidateMapping);
if (failIfOneToOneMappingHasMissingOrExtra(
actualList, expectedList, maximalOneToOneMapping, exceptions)) {
return ALREADY_FAILED;
}
// Check whether we caught any exceptions from Correspondence.compare. We do the any-order
// assertions treating exceptions as if false was returned before this, because the failure
// messages are normally more useful (e.g. reporting that the actual iterable contained an
// unexpected null) but we are contractually obliged to throw here if the assertions passed.
if (exceptions.hasCompareException()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.addAll(exceptions.describeAsMainCause())
.add(fact("expected", expected))
.addAll(correspondence.describeForIterable())
.add(simpleFact("found all expected elements (but failing because of exception)"))
.add(subject.fullContents())
.build());
return ALREADY_FAILED;
}
// The 1:1 mapping is complete, so the test succeeds (but we know from above that the mapping
// is not in order).
return () ->
subject.failWithActual(
ImmutableList.<Fact>builder()
.add(simpleFact("contents match, but order was wrong"))
.add(fact("expected", expected))
.addAll(correspondence.describeForIterable())
.build());
}
|
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.
|
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
|
@CanIgnoreReturnValue
@SuppressWarnings("AvoidObjectArrays")
public Ordered containsExactlyElementsIn(E @Nullable [] expected) {
return containsExactlyElementsIn(asList(checkNotNull(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.
|
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
|
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
|
private ImmutableList<Fact> describeMissingOrExtra(
List<? extends E> missing,
List<? extends A> extra,
Correspondence.ExceptionStore exceptions) {
if (pairer != null) {
Pairing<A, E> pairing = pairer.pair(missing, extra, exceptions);
if (pairing != null) {
return describeMissingOrExtraWithPairing(pairing, exceptions);
} else {
return ImmutableList.<Fact>builder()
.addAll(describeMissingOrExtraWithoutPairing(missing, extra))
.add(
simpleFact(
"a key function which does not uniquely key the expected elements was"
+ " provided and has consequently been ignored"))
.build();
}
} else if (missing.size() == 1 && !extra.isEmpty()) {
return ImmutableList.<Fact>builder()
.add(fact("missing (1)", missing.get(0)))
.addAll(formatExtras("unexpected", missing.get(0), extra, exceptions))
.add(simpleFact("---"))
.build();
} else {
return describeMissingOrExtraWithoutPairing(missing, extra);
}
}
|
Given a list of missing elements and a list of extra elements, at least one of which must be
non-empty, returns facts describing them. Exceptions from calling {@link
Correspondence#formatDiff} are stored in {@code exceptions}.
|
describeMissingOrExtra
|
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 ImmutableList<Fact> describeMissingOrExtraWithoutPairing(
List<? extends E> missing, List<? extends A> extra) {
return makeElementFactsForBoth("missing", missing, "unexpected", extra);
}
|
Given a list of missing elements and a list of extra elements, at least one of which must be
non-empty, returns facts describing them. Exceptions from calling {@link
Correspondence#formatDiff} are stored in {@code exceptions}.
|
describeMissingOrExtraWithoutPairing
|
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 ImmutableList<Fact> describeMissingOrExtraWithPairing(
Pairing<A, E> pairing, Correspondence.ExceptionStore exceptions) {
ImmutableList.Builder<Fact> facts = ImmutableList.builder();
for (Object key : pairing.pairedKeysToExpectedValues.keySet()) {
E missing = pairing.pairedKeysToExpectedValues.get(key);
List<A> extras = pairing.pairedKeysToActualValues.get(key);
facts.add(fact("for key", key));
facts.add(fact("missing", missing));
facts.addAll(formatExtras("unexpected", missing, extras, exceptions));
facts.add(simpleFact("---"));
}
if (!pairing.unpairedActualValues.isEmpty() || !pairing.unpairedExpectedValues.isEmpty()) {
facts.add(simpleFact("elements without matching keys:"));
facts.addAll(
describeMissingOrExtraWithoutPairing(
pairing.unpairedExpectedValues, pairing.unpairedActualValues));
}
return facts.build();
}
|
Given a list of missing elements and a list of extra elements, at least one of which must be
non-empty, returns facts describing them. Exceptions from calling {@link
Correspondence#formatDiff} are stored in {@code exceptions}.
|
describeMissingOrExtraWithPairing
|
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 ImmutableList<Fact> formatExtras(
String label,
E missing,
List<? extends A> extras,
Correspondence.ExceptionStore exceptions) {
List<@Nullable String> diffs = new ArrayList<>(extras.size());
boolean hasDiffs = false;
for (int i = 0; i < extras.size(); i++) {
A extra = extras.get(i);
String diff = correspondence.safeFormatDiff(extra, missing, exceptions);
diffs.add(diff);
if (diff != null) {
hasDiffs = true;
}
}
if (hasDiffs) {
ImmutableList.Builder<Fact> extraFacts = ImmutableList.builder();
extraFacts.add(simpleFact(lenientFormat("%s (%s)", label, extras.size())));
for (int i = 0; i < extras.size(); i++) {
A extra = extras.get(i);
extraFacts.add(fact(lenientFormat("#%s", i + 1), extra));
if (diffs.get(i) != null) {
extraFacts.add(fact("diff", diffs.get(i)));
}
}
return extraFacts.build();
} else {
return ImmutableList.of(
fact(lenientFormat("%s (%s)", label, extras.size()), countDuplicates(extras)));
}
}
|
Given a list of missing elements and a list of extra elements, at least one of which must be
non-empty, returns facts describing them. Exceptions from calling {@link
Correspondence#formatDiff} are stored in {@code exceptions}.
|
formatExtras
|
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 <T extends @Nullable Object> List<T> findNotIndexed(
List<T> list, Set<Integer> indexes) {
if (indexes.size() == list.size()) {
// If there are as many distinct valid indexes are there are elements in the list then every
// index must be in there once.
return asList();
}
List<T> notIndexed = new ArrayList<>();
for (int index = 0; index < list.size(); index++) {
if (!indexes.contains(index)) {
notIndexed.add(list.get(index));
}
}
return notIndexed;
}
|
Returns all the elements of the given list other than those with the given indexes. Assumes
that all the given indexes really are valid indexes into the list.
|
findNotIndexed
|
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 ImmutableBiMap<Integer, Integer> findMaximalOneToOneMapping(
ImmutableMultimap<Integer, Integer> edges) {
/*
* Finding this 1:1 mapping is analogous to finding a maximum cardinality bipartite matching
* (https://en.wikipedia.org/wiki/Matching_(graph_theory)#In_unweighted_bipartite_graphs).
* - The two sets of elements together correspond to the vertices of a graph.
* - The many:many mapping corresponds to the edges of that graph.
* - The graph is therefore bipartite, with the two sets of elements corresponding to the two
* parts.
* - A 1:1 mapping corresponds to a matching on that bipartite graph (aka an independent edge
* set, i.e. a subset of the edges with no common vertices).
* - And the 1:1 mapping which includes the largest possible number of elements corresponds
* to the maximum cardinality matching.
*
* So we'll apply a standard algorithm for doing maximum cardinality bipartite matching.
*/
return GraphMatching.maximumCardinalityBipartiteMatching(edges);
}
|
Given a many:many mapping between actual elements and expected elements, finds a 1:1 mapping
which is the subset of that many:many mapping which includes the largest possible number of
elements. The input and output mappings are each described as a map or multimap where the
keys are indexes into the actual list and the values are indexes into the expected list. If
there are multiple possible output mappings tying for the largest possible, this returns an
arbitrary one.
|
findMaximalOneToOneMapping
|
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 failIfOneToOneMappingHasMissingOrExtra(
List<? extends A> actual,
List<? extends E> expected,
BiMap<Integer, Integer> mapping,
Correspondence.ExceptionStore exceptions) {
List<? extends A> extra = findNotIndexed(actual, mapping.keySet());
List<? extends E> missing = findNotIndexed(expected, mapping.values());
if (!missing.isEmpty() || !extra.isEmpty()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.add(
simpleFact(
"in an assertion requiring a 1:1 mapping between the expected and the"
+ " actual elements, each actual element matches as least one expected"
+ " element, and vice versa, but there was no 1:1 mapping"))
.add(
simpleFact(
"using the most complete 1:1 mapping (or one such mapping, if there is a"
+ " tie)"))
.addAll(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 1:1 mapping between
actual and expected elements specified as a bimap of indexes into the actual list to indexes
into the expected list, checks that every actual element maps to an expected element and vice
versa, and fails if this is not the case. Returns whether the assertion failed.
|
failIfOneToOneMappingHasMissingOrExtra
|
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 containsAtLeast(E first, E second, E @Nullable ... rest) {
return containsAtLeastElementsIn(accumulate(first, second, rest));
}
|
Checks that the actual iterable contains elements that correspond to all the expected
elements, i.e. that there is a 1:1 mapping between any subset of 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. The elements must appear in the given order within the
actual iterable, 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
|
@CanIgnoreReturnValue
public Ordered containsAtLeastElementsIn(Iterable<? extends E> expected) {
List<A> actualList = iterableToList(getCastActual());
List<? extends E> expectedList = iterableToList(expected);
// Check if the expected elements correspond in order to any subset of the actual elements.
// This allows the common case of a passing test using inOrder() to complete in linear time.
if (correspondInOrderAllIn(actualList.iterator(), expectedList.iterator())) {
return IN_ORDER;
}
// We know they don't correspond in order, so we're going to have to do an any-order test.
// Find a many:many mapping between the indexes of the elements which correspond, and check
// it for completeness.
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
ImmutableSetMultimap<Integer, Integer> candidateMapping =
findCandidateMapping(actualList, expectedList, exceptions);
if (failIfCandidateMappingHasMissing(
actualList, expectedList, candidateMapping, exceptions)) {
return ALREADY_FAILED;
}
// We know that every expected element maps to at least one actual element, and vice versa.
// Find a maximal 1:1 mapping, and check it for completeness.
ImmutableBiMap<Integer, Integer> maximalOneToOneMapping =
findMaximalOneToOneMapping(candidateMapping);
if (failIfOneToOneMappingHasMissing(
actualList, expectedList, maximalOneToOneMapping, exceptions)) {
return ALREADY_FAILED;
}
// Check whether we caught any exceptions from Correspondence.compare. As with
// containsExactlyElementIn, we do the any-order assertions treating exceptions as if false
// was returned before this, but we are contractually obliged to throw here if the assertions
// passed.
if (exceptions.hasCompareException()) {
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.addAll(exceptions.describeAsMainCause())
.add(fact("expected to contain at least", expected))
.addAll(correspondence.describeForIterable())
.add(simpleFact("found all expected elements (but failing because of exception)"))
.add(subject.fullContents())
.build());
return ALREADY_FAILED;
}
// The 1:1 mapping maps all the expected elements, so the test succeeds (but we know from
// above that the mapping is not in order).
return () ->
subject.failWithActual(
ImmutableList.<Fact>builder()
.add(simpleFact("required elements were all found, but order was wrong"))
.add(fact("expected order for required elements", expected))
.addAll(correspondence.describeForIterable())
.build());
}
|
Checks that the actual iterable contains elements that correspond to all the expected
elements, i.e. that there is a 1:1 mapping between any subset of 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. The elements must appear in the given order within the
actual iterable, but they are not required to be consecutive.
|
containsAtLeastElementsIn
|
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
@SuppressWarnings("AvoidObjectArrays")
public Ordered containsAtLeastElementsIn(E[] expected) {
return containsAtLeastElementsIn(asList(expected));
}
|
Checks that the actual iterable contains elements that correspond to all the expected
elements, i.e. that there is a 1:1 mapping between any subset of 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. The elements must appear in the given order within the
actual iterable, but they are not required to be consecutive.
|
containsAtLeastElementsIn
|
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 correspondInOrderAllIn(
Iterator<? extends A> actual, Iterator<? extends E> expected) {
// We take a greedy approach here, iterating through the expected elements and pairing each
// with the first applicable actual element. This is fine for the in-order test, since there's
// no way that paring an expected element with a later actual element permits a solution which
// couldn't be achieved by pairing it with the first. (For the any-order test, we may want to
// pair an expected element with a later actual element so that we can pair the earlier actual
// element with a later expected element, but that doesn't apply here.)
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
while (expected.hasNext()) {
E expectedElement = expected.next();
// Return false if we couldn't find the expected exception, or if the correspondence threw
// an exception. We'll fall back on the any-order assertion in this case.
if (!findCorresponding(actual, expectedElement, exceptions)
|| exceptions.hasCompareException()) {
return false;
}
}
return true;
}
|
Returns whether all the elements of the expected iterator and any subset of the elements of
the actual iterator can be paired up in order, such that every pair of actual and expected
elements satisfies the correspondence. Returns false if any comparison threw an exception.
|
correspondInOrderAllIn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/IterableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
|
Apache-2.0
|
private boolean findCorresponding(
Iterator<? extends A> actual, E expectedElement, Correspondence.ExceptionStore exceptions) {
while (actual.hasNext()) {
A actualElement = actual.next();
if (correspondence.safeCompare(actualElement, expectedElement, exceptions)) {
return true;
}
}
return false;
}
|
Advances the actual iterator looking for an element which corresponds to the expected
element. Returns whether or not it finds one.
|
findCorresponding
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/IterableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
|
Apache-2.0
|
private boolean failIfCandidateMappingHasMissing(
List<? extends A> actual,
List<? extends E> expected,
ImmutableSetMultimap<Integer, Integer> mapping,
Correspondence.ExceptionStore exceptions) {
List<? extends E> missing = findNotIndexed(expected, mapping.inverse().keySet());
if (!missing.isEmpty()) {
List<? extends A> extra = findNotIndexed(actual, mapping.keySet());
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.addAll(describeMissing(missing, extra, exceptions))
.add(fact("expected to contain at least", expected))
.addAll(correspondence.describeForIterable())
.add(subject.butWas())
.addAll(exceptions.describeAsAdditionalInfo())
.build());
return true;
}
return false;
}
|
Given a list of actual elements, a list of expected elements, and a many:many mapping between
actual and expected elements specified as a multimap of indexes into the actual list to
indexes into the expected list, checks that every expected element maps to at least one
actual element, and fails if this is not the case. Actual elements which do not map to any
expected elements are ignored.
|
failIfCandidateMappingHasMissing
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/IterableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
|
Apache-2.0
|
private ImmutableList<Fact> describeMissing(
List<? extends E> missing,
List<? extends A> extra,
Correspondence.ExceptionStore exceptions) {
if (pairer != null) {
Pairing<A, E> pairing = pairer.pair(missing, extra, exceptions);
if (pairing != null) {
return describeMissingWithPairing(pairing, exceptions);
} else {
return ImmutableList.<Fact>builder()
.addAll(describeMissingWithoutPairing(missing))
.add(
simpleFact(
"a key function which does not uniquely key the expected elements was"
+ " provided and has consequently been ignored"))
.build();
}
} else {
// N.B. For containsAny, we do not treat having exactly one missing element as a special
// case (as we do for containsExactly). Showing extra elements has lower utility for
// containsAny (because they are allowed by the assertion) so we only show them if the user
// has explicitly opted in by specifying a pairing.
return describeMissingWithoutPairing(missing);
}
}
|
Given a list of missing elements, which must be non-empty, and a list of extra elements,
returns a list of facts describing the missing elements, diffing against the extra ones where
appropriate.
|
describeMissing
|
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 ImmutableList<Fact> describeMissingWithoutPairing(List<? extends E> missing) {
return makeElementFactsForBoth("missing", missing, "unexpected", ImmutableList.of());
}
|
Given a list of missing elements, which must be non-empty, and a list of extra elements,
returns a list of facts describing the missing elements, diffing against the extra ones where
appropriate.
|
describeMissingWithoutPairing
|
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 ImmutableList<Fact> describeMissingWithPairing(
Pairing<A, E> pairing, Correspondence.ExceptionStore exceptions) {
ImmutableList.Builder<Fact> facts = ImmutableList.builder();
for (Object key : pairing.pairedKeysToExpectedValues.keySet()) {
E missing = pairing.pairedKeysToExpectedValues.get(key);
List<A> extras = pairing.pairedKeysToActualValues.get(key);
facts.add(fact("for key", key));
facts.add(fact("missing", missing));
facts.addAll(
formatExtras("did contain elements with that key", missing, extras, exceptions));
facts.add(simpleFact("---"));
}
if (!pairing.unpairedExpectedValues.isEmpty()) {
facts.add(simpleFact("elements without matching keys:"));
facts.addAll(describeMissingWithoutPairing(pairing.unpairedExpectedValues));
}
return facts.build();
}
|
Given a list of missing elements, which must be non-empty, and a list of extra elements,
returns a list of facts describing the missing elements, diffing against the extra ones where
appropriate.
|
describeMissingWithPairing
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/IterableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
|
Apache-2.0
|
private boolean failIfOneToOneMappingHasMissing(
List<? extends A> actual,
List<? extends E> expected,
BiMap<Integer, Integer> mapping,
Correspondence.ExceptionStore exceptions) {
List<? extends E> missing = findNotIndexed(expected, mapping.values());
if (!missing.isEmpty()) {
List<? extends A> extra = findNotIndexed(actual, mapping.keySet());
subject.failWithoutActual(
ImmutableList.<Fact>builder()
.add(
simpleFact(
"in an assertion requiring a 1:1 mapping between the expected and a subset"
+ " of the actual elements, each actual element matches as least one"
+ " expected element, and vice versa, but there was no 1:1 mapping"))
.add(
simpleFact(
"using the most complete 1:1 mapping (or one such mapping, if there is a"
+ " tie)"))
.addAll(describeMissing(missing, extra, exceptions))
.add(fact("expected to contain at least", expected))
.addAll(correspondence.describeForIterable())
.add(subject.butWas())
.addAll(exceptions.describeAsAdditionalInfo())
.build());
return true;
}
return false;
}
|
Given a list of expected elements, and a 1:1 mapping between actual and expected elements
specified as a bimap of indexes into the actual list to indexes into the expected list,
checks that every expected element maps to an actual element. Actual elements which do not
map to any expected elements are ignored.
|
failIfOneToOneMappingHasMissing
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/IterableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/IterableSubject.java
|
Apache-2.0
|
@SafeVarargs
public final void containsAnyOf(E first, E second, E @Nullable ... rest) {
containsAnyIn(accumulate(first, second, rest));
}
|
Checks that the actual iterable contains at least one element that corresponds to at least
one of the expected elements.
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.