proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/Assumptions.java
AssumptionMethodInterceptor
intercept
class AssumptionMethodInterceptor { @RuntimeType public static Object intercept(@This AbstractAssert<?, ?> assertion, @SuperCall Callable<Object> proxy) throws Exception {<FILL_FUNCTION_BODY>} }
try { Object result = proxy.call(); if (result != assertion && result instanceof AbstractAssert) { return asAssumption((AbstractAssert<?, ?>) result).withAssertionState(assertion); } return result; } catch (AssertionError e) { throw assumptionNotMet(e); }
60
86
146
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/AtomicBooleanAssert.java
AtomicBooleanAssert
usingComparator
class AtomicBooleanAssert extends AbstractAssert<AtomicBooleanAssert, AtomicBoolean> { @VisibleForTesting Booleans booleans = Booleans.instance(); public AtomicBooleanAssert(AtomicBoolean actual) { super(actual, AtomicBooleanAssert.class); } /** * Verifies that the actual atomic value is true. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new AtomicBoolean(true)).isTrue(); * * // assertion will fail * assertThat(new AtomicBoolean(false)).isTrue();</code></pre> * * @return this assertion object. * @throws AssertionError if the actual atomic is {@code null}. * @throws AssertionError if the actual atomic value is false. * * @since 2.7.0 / 3.7.0 */ public AtomicBooleanAssert isTrue() { isNotNull(); assertEqual(true); return myself; } /** * Verifies that the actual atomic value is false. * <p> * Example: * <pre><code class='java'> // assertion will pass * assertThat(new AtomicBoolean(false)).isFalse(); * * // assertion will fail * assertThat(new AtomicBoolean(true)).isFalse();</code></pre> * * @return this assertion object. * @throws AssertionError if the actual atomic is {@code null}. * @throws AssertionError if the actual atomic value is true. * * @since 2.7.0 / 3.7.0 */ public AtomicBooleanAssert isFalse() { isNotNull(); assertEqual(false); return myself; } /** * Do not use this method. * * @deprecated Custom Comparator is not supported for Boolean comparison. * @throws UnsupportedOperationException if this method is called. */ @Override @Deprecated public AtomicBooleanAssert usingComparator(Comparator<? super AtomicBoolean> customComparator) { return usingComparator(customComparator, null); } /** * Do not use this method. * * @deprecated Custom Comparator is not supported for Boolean comparison. * @throws UnsupportedOperationException if this method is called. */ @Override @Deprecated public AtomicBooleanAssert usingComparator(Comparator<? super AtomicBoolean> customComparator, String customComparatorDescription) {<FILL_FUNCTION_BODY>} private void assertEqual(boolean expected) { if (!objects.getComparisonStrategy().areEqual(actual.get(), expected)) { throwAssertionError(shouldHaveValue(actual, expected)); } } }
throw new UnsupportedOperationException("custom Comparator is not supported for AtomicBoolean comparison");
731
25
756
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public org.assertj.core.api.AtomicBooleanAssert describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public org.assertj.core.api.AtomicBooleanAssert doesNotHave(Condition<? super java.util.concurrent.atomic.AtomicBoolean>) ,public org.assertj.core.api.AtomicBooleanAssert doesNotHaveSameClassAs(java.lang.Object) ,public org.assertj.core.api.AtomicBooleanAssert doesNotHaveSameHashCodeAs(java.lang.Object) ,public org.assertj.core.api.AtomicBooleanAssert doesNotHaveToString(java.lang.String) ,public transient org.assertj.core.api.AtomicBooleanAssert doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public org.assertj.core.api.AtomicBooleanAssert has(Condition<? super java.util.concurrent.atomic.AtomicBoolean>) ,public org.assertj.core.api.AtomicBooleanAssert hasSameClassAs(java.lang.Object) ,public org.assertj.core.api.AtomicBooleanAssert hasSameHashCodeAs(java.lang.Object) ,public org.assertj.core.api.AtomicBooleanAssert hasToString(java.lang.String) ,public transient org.assertj.core.api.AtomicBooleanAssert hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public org.assertj.core.api.AtomicBooleanAssert is(Condition<? super java.util.concurrent.atomic.AtomicBoolean>) ,public org.assertj.core.api.AtomicBooleanAssert isEqualTo(java.lang.Object) ,public org.assertj.core.api.AtomicBooleanAssert isExactlyInstanceOf(Class<?>) ,public transient org.assertj.core.api.AtomicBooleanAssert isIn(java.lang.Object[]) ,public org.assertj.core.api.AtomicBooleanAssert isIn(Iterable<?>) ,public org.assertj.core.api.AtomicBooleanAssert isInstanceOf(Class<?>) ,public transient org.assertj.core.api.AtomicBooleanAssert isInstanceOfAny(Class<?>[]) ,public org.assertj.core.api.AtomicBooleanAssert isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public org.assertj.core.api.AtomicBooleanAssert isNot(Condition<? super java.util.concurrent.atomic.AtomicBoolean>) ,public org.assertj.core.api.AtomicBooleanAssert isNotEqualTo(java.lang.Object) ,public org.assertj.core.api.AtomicBooleanAssert isNotExactlyInstanceOf(Class<?>) ,public transient org.assertj.core.api.AtomicBooleanAssert isNotIn(java.lang.Object[]) ,public org.assertj.core.api.AtomicBooleanAssert isNotIn(Iterable<?>) ,public org.assertj.core.api.AtomicBooleanAssert isNotInstanceOf(Class<?>) ,public transient org.assertj.core.api.AtomicBooleanAssert isNotInstanceOfAny(Class<?>[]) ,public org.assertj.core.api.AtomicBooleanAssert isNotNull() ,public transient org.assertj.core.api.AtomicBooleanAssert isNotOfAnyClassIn(Class<?>[]) ,public org.assertj.core.api.AtomicBooleanAssert isNotSameAs(java.lang.Object) ,public void isNull() ,public transient org.assertj.core.api.AtomicBooleanAssert isOfAnyClassIn(Class<?>[]) ,public org.assertj.core.api.AtomicBooleanAssert isSameAs(java.lang.Object) ,public org.assertj.core.api.AtomicBooleanAssert matches(Predicate<? super java.util.concurrent.atomic.AtomicBoolean>) ,public org.assertj.core.api.AtomicBooleanAssert matches(Predicate<? super java.util.concurrent.atomic.AtomicBoolean>, java.lang.String) ,public transient org.assertj.core.api.AtomicBooleanAssert overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public org.assertj.core.api.AtomicBooleanAssert overridingErrorMessage(Supplier<java.lang.String>) ,public org.assertj.core.api.AtomicBooleanAssert satisfies(Condition<? super java.util.concurrent.atomic.AtomicBoolean>) ,public final transient org.assertj.core.api.AtomicBooleanAssert satisfies(Consumer<? super java.util.concurrent.atomic.AtomicBoolean>[]) ,public final transient org.assertj.core.api.AtomicBooleanAssert satisfies(ThrowingConsumer<? super java.util.concurrent.atomic.AtomicBoolean>[]) ,public final transient org.assertj.core.api.AtomicBooleanAssert satisfiesAnyOf(Consumer<? super java.util.concurrent.atomic.AtomicBoolean>[]) ,public final transient org.assertj.core.api.AtomicBooleanAssert satisfiesAnyOf(ThrowingConsumer<? super java.util.concurrent.atomic.AtomicBoolean>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public org.assertj.core.api.AtomicBooleanAssert usingComparator(Comparator<? super java.util.concurrent.atomic.AtomicBoolean>) ,public org.assertj.core.api.AtomicBooleanAssert usingComparator(Comparator<? super java.util.concurrent.atomic.AtomicBoolean>, java.lang.String) ,public org.assertj.core.api.AtomicBooleanAssert usingDefaultComparator() ,public transient org.assertj.core.api.AtomicBooleanAssert withFailMessage(java.lang.String, java.lang.Object[]) ,public org.assertj.core.api.AtomicBooleanAssert withFailMessage(Supplier<java.lang.String>) ,public org.assertj.core.api.AtomicBooleanAssert withRepresentation(org.assertj.core.presentation.Representation) ,public org.assertj.core.api.AtomicBooleanAssert withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed java.util.concurrent.atomic.AtomicBoolean actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed org.assertj.core.api.AtomicBooleanAssert myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/AtomicMarkableReferenceAssert.java
AtomicMarkableReferenceAssert
isNotMarked
class AtomicMarkableReferenceAssert<VALUE> extends AbstractAtomicReferenceAssert<AtomicMarkableReferenceAssert<VALUE>, VALUE, AtomicMarkableReference<VALUE>> { public AtomicMarkableReferenceAssert(AtomicMarkableReference<VALUE> actual) { super(actual, AtomicMarkableReferenceAssert.class); } /** * Verifies that the actual {@link AtomicMarkableReference} contains the given value. * <p> * Example: * <pre><code class='java'> AtomicMarkableReference&lt;String&gt; ref = new AtomicMarkableReference&lt;&gt;("foo", true); * * // this assertion succeeds: * assertThat(ref).hasValue("foo"); * * // this assertion fails: * assertThat(ref).hasValue("bar");</code></pre> * * @param expectedValue the expected value inside the {@link AtomicMarkableReference}. * @return this assertion object. * @since 2.7.0 / 3.7.0 */ @Override public AtomicMarkableReferenceAssert<VALUE> hasReference(VALUE expectedValue) { return super.hasReference(expectedValue); } @Override protected VALUE getReference() { return actual.getReference(); } /** * Verifies that the actual {@link AtomicMarkableReference} is marked. * <p> * Examples: * <pre><code class='java'> // this assertion succeeds: * assertThat(new AtomicMarkableReference&lt;&gt;("actual", true)).isMarked(); * * // this assertion fails: * assertThat(new AtomicMarkableReference&lt;&gt;("actual", false)).isMarked();</code></pre> * * @return this assertion object. * @since 2.7.0 / 3.7.0 */ public AtomicMarkableReferenceAssert<VALUE> isMarked() { boolean marked = actual.isMarked(); if (!marked) throwAssertionError(shouldBeMarked(actual)); return this; } /** * Verifies that the actual {@link AtomicMarkableReference} is <b>not</b> marked. * <p> * Examples: * <pre><code class='java'> // this assertion succeeds: * assertThat(new AtomicMarkableReference&lt;&gt;("actual", false)).isNotMarked(); * * // this assertion fails: * assertThat(new AtomicMarkableReference&lt;&gt;("actual", true)).isNotMarked();</code></pre> * * @return this assertion object. * @since 2.7.0 / 3.7.0 */ public AtomicMarkableReferenceAssert<VALUE> isNotMarked() {<FILL_FUNCTION_BODY>} }
boolean marked = actual.isMarked(); if (marked) throwAssertionError(shouldNotBeMarked(actual)); return this;
737
39
776
<methods>public AtomicMarkableReferenceAssert<VALUE> hasReference(VALUE) <variables>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/AtomicReferenceAssert.java
AtomicReferenceAssert
hasValueSatisfying
class AtomicReferenceAssert<V> extends AbstractAssert<AtomicReferenceAssert<V>, AtomicReference<V>> { public AtomicReferenceAssert(AtomicReference<V> actual) { super(actual, AtomicReferenceAssert.class); } /** * Verifies that the atomic under test has the given value. * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat(new AtomicReference("foo")).hasValue("foo"); * * // assertion fails * assertThat(new AtomicReference("foo")).hasValue("bar");</code></pre> * * @param expectedValue the expected value. * @return {@code this} assertion object. * @throws AssertionError if the atomic under test is {@code null}. * @throws AssertionError if the atomic under test does not have the given value. * @since 2.7.0 / 3.7.0 */ public AtomicReferenceAssert<V> hasValue(V expectedValue) { isNotNull(); V actualValue = actual.get(); if (!objects.getComparisonStrategy().areEqual(actualValue, expectedValue)) { throw assertionError(shouldHaveValue(actual, expectedValue)); } return myself; } /** * Verifies that the atomic under test does not have the given value. * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat(new AtomicReference("foo")).doesNotHaveValue("bar"); * * // assertion fails * assertThat(new AtomicReference("foo")).doesNotHaveValue("foo");</code></pre> * * @param nonExpectedValue the value not expected. * @return {@code this} assertion object. * @throws AssertionError if the atomic under test is {@code null}. * @throws AssertionError if the atomic under test has the given value. * * @since 2.7.0 / 3.7.0 */ public AtomicReferenceAssert<V> doesNotHaveValue(V nonExpectedValue) { isNotNull(); V actualValue = actual.get(); if (objects.getComparisonStrategy().areEqual(actualValue, nonExpectedValue)) { throw assertionError(shouldNotContainValue(actual, nonExpectedValue)); } return myself; } /** * Verifies that the atomic under test has a value satisfying the given predicate. * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat(new AtomicReference("foo")).hasValueMatching(result -&gt; result != null); * * // assertion fails * assertThat(new AtomicReference("foo")).hasValueMatching(result -&gt; result == null); </code></pre> * * @param predicate the {@link Predicate} to apply on the resulting value. * @return {@code this} assertion object. * @throws NullPointerException if the given {@link Predicate} is null * @throws AssertionError if the atomic under test is {@code null}. * @throws AssertionError if the atomic under test value does not matches with the given predicate. * * @since 3.18.0 */ public AtomicReferenceAssert<V> hasValueMatching(Predicate<? super V> predicate) { return hasValueMatching(predicate, PredicateDescription.GIVEN); } /** * Verifies that the atomic under test has a value satisfying the given predicate, the string parameter is used in the error message * to describe the predicate. * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat(new AtomicReference("foo")).hasValueMatching(result -&gt; result != null, "expected not null"); * * // assertion fails * assertThat(new AtomicReference("foo")).hasValueMatching(result -&gt; result == null, "expected null"); * </code></pre> * * @param predicate the {@link Predicate} to apply on the resulting value. * @param description the {@link Predicate} description. * @return {@code this} assertion object. * @throws NullPointerException if the given {@link Predicate} is null * @throws AssertionError if the atomic under test is {@code null}. * @throws AssertionError if the atomic under test value does not matches with the given predicate. * * @since 3.18.0 */ public AtomicReferenceAssert<V> hasValueMatching(Predicate<? super V> predicate, String description) { return hasValueMatching(predicate, new PredicateDescription(description)); } private AtomicReferenceAssert<V> hasValueMatching(Predicate<? super V> predicate, PredicateDescription description) { requireNonNull(predicate, "The predicate must not be null"); isNotNull(); V actualValue = actual.get(); if (!predicate.test(actualValue)) { throw assertionError(shouldMatch(actualValue, predicate, description)); } return myself; } /** * Verifies that the atomic under test has a value satisfying the given requirements. * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat(new AtomicReference("foo")).hasValueSatisfying(result -&gt; assertThat(result).isNotBlank()); * * // assertion fails * assertThat(new AtomicReference("foo")).hasValueSatisfying(result -&gt; assertThat(result).isBlank()); </code></pre> * * @param requirements to assert on the actual object - must not be null. * @return this assertion object. * * @throws NullPointerException if the given {@link Consumer} is null * @throws AssertionError if the atomic under test is {@code null}. * @throws AssertionError if the atomic under test value does not satisfies with the given requirements. * * @since 3.18.0 */ public AtomicReferenceAssert<V> hasValueSatisfying(Consumer<? super V> requirements) {<FILL_FUNCTION_BODY>} /** * Verifies that the atomic under test has the {@code null} value. * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat(new AtomicReference(null)).hasNullValue(); * * // assertion fails * assertThat(new AtomicReference("foo")).hasNullValue();</code></pre> * * @return {@code this} assertion object. * @throws AssertionError if the atomic under test does not have the null value. * @since 3.25.0 */ public AtomicReferenceAssert<V> hasNullValue() { return hasValue(null); } /** * Verifies that the atomic under test does not have the {@code null} value. * <p> * Example: * <pre><code class='java'> // assertion succeeds * assertThat(new AtomicReference("foo")).doesNotHaveNullValue(); * * // assertion fails * assertThat(new AtomicReference(null)).doesNotHaveNullValue();</code></pre> * * @return {@code this} assertion object. * @throws AssertionError if the atomic under test has the null value. * @since 3.25.0 */ public AtomicReferenceAssert<V> doesNotHaveNullValue() { return doesNotHaveValue(null); } }
requireNonNull(requirements, "The Consumer<? super V> expressing the assertions requirements must not be null"); isNotNull(); requirements.accept(actual.get()); return myself;
1,946
51
1,997
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public AtomicReferenceAssert<V> describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public AtomicReferenceAssert<V> doesNotHave(Condition<? super AtomicReference<V>>) ,public AtomicReferenceAssert<V> doesNotHaveSameClassAs(java.lang.Object) ,public AtomicReferenceAssert<V> doesNotHaveSameHashCodeAs(java.lang.Object) ,public AtomicReferenceAssert<V> doesNotHaveToString(java.lang.String) ,public transient AtomicReferenceAssert<V> doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public AtomicReferenceAssert<V> has(Condition<? super AtomicReference<V>>) ,public AtomicReferenceAssert<V> hasSameClassAs(java.lang.Object) ,public AtomicReferenceAssert<V> hasSameHashCodeAs(java.lang.Object) ,public AtomicReferenceAssert<V> hasToString(java.lang.String) ,public transient AtomicReferenceAssert<V> hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public AtomicReferenceAssert<V> is(Condition<? super AtomicReference<V>>) ,public AtomicReferenceAssert<V> isEqualTo(java.lang.Object) ,public AtomicReferenceAssert<V> isExactlyInstanceOf(Class<?>) ,public transient AtomicReferenceAssert<V> isIn(java.lang.Object[]) ,public AtomicReferenceAssert<V> isIn(Iterable<?>) ,public AtomicReferenceAssert<V> isInstanceOf(Class<?>) ,public transient AtomicReferenceAssert<V> isInstanceOfAny(Class<?>[]) ,public AtomicReferenceAssert<V> isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public AtomicReferenceAssert<V> isNot(Condition<? super AtomicReference<V>>) ,public AtomicReferenceAssert<V> isNotEqualTo(java.lang.Object) ,public AtomicReferenceAssert<V> isNotExactlyInstanceOf(Class<?>) ,public transient AtomicReferenceAssert<V> isNotIn(java.lang.Object[]) ,public AtomicReferenceAssert<V> isNotIn(Iterable<?>) ,public AtomicReferenceAssert<V> isNotInstanceOf(Class<?>) ,public transient AtomicReferenceAssert<V> isNotInstanceOfAny(Class<?>[]) ,public AtomicReferenceAssert<V> isNotNull() ,public transient AtomicReferenceAssert<V> isNotOfAnyClassIn(Class<?>[]) ,public AtomicReferenceAssert<V> isNotSameAs(java.lang.Object) ,public void isNull() ,public transient AtomicReferenceAssert<V> isOfAnyClassIn(Class<?>[]) ,public AtomicReferenceAssert<V> isSameAs(java.lang.Object) ,public AtomicReferenceAssert<V> matches(Predicate<? super AtomicReference<V>>) ,public AtomicReferenceAssert<V> matches(Predicate<? super AtomicReference<V>>, java.lang.String) ,public transient AtomicReferenceAssert<V> overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public AtomicReferenceAssert<V> overridingErrorMessage(Supplier<java.lang.String>) ,public AtomicReferenceAssert<V> satisfies(Condition<? super AtomicReference<V>>) ,public final transient AtomicReferenceAssert<V> satisfies(Consumer<? super AtomicReference<V>>[]) ,public final transient AtomicReferenceAssert<V> satisfies(ThrowingConsumer<? super AtomicReference<V>>[]) ,public final transient AtomicReferenceAssert<V> satisfiesAnyOf(Consumer<? super AtomicReference<V>>[]) ,public final transient AtomicReferenceAssert<V> satisfiesAnyOf(ThrowingConsumer<? super AtomicReference<V>>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public AtomicReferenceAssert<V> usingComparator(Comparator<? super AtomicReference<V>>) ,public AtomicReferenceAssert<V> usingComparator(Comparator<? super AtomicReference<V>>, java.lang.String) ,public AtomicReferenceAssert<V> usingDefaultComparator() ,public transient AtomicReferenceAssert<V> withFailMessage(java.lang.String, java.lang.Object[]) ,public AtomicReferenceAssert<V> withFailMessage(Supplier<java.lang.String>) ,public AtomicReferenceAssert<V> withRepresentation(org.assertj.core.presentation.Representation) ,public AtomicReferenceAssert<V> withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed AtomicReference<V> actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed AtomicReferenceAssert<V> myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/AtomicStampedReferenceAssert.java
AtomicStampedReferenceAssert
hasStamp
class AtomicStampedReferenceAssert<VALUE> extends AbstractAtomicReferenceAssert<AtomicStampedReferenceAssert<VALUE>, VALUE, AtomicStampedReference<VALUE>> { public AtomicStampedReferenceAssert(AtomicStampedReference<VALUE> actual) { super(actual, AtomicStampedReferenceAssert.class); } /** * Verifies that the actual {@link AtomicStampedReference} contains the given value. * <p> * Example: * <pre><code class='java'> AtomicStampedReferenceAssert&lt;String&gt; ref = new AtomicStampedReferenceAssert&lt;&gt;("foo", 123); * * // this assertion succeeds: * assertThat(ref).hasValue("foo"); * * // this assertion fails: * assertThat(ref).hasValue("bar");</code></pre> * * @param expectedValue the expected value inside the {@link AtomicStampedReference}. * @return this assertion object. * @since 2.7.0 / 3.7.0 */ @Override public AtomicStampedReferenceAssert<VALUE> hasReference(VALUE expectedValue) { return super.hasReference(expectedValue); } @Override protected VALUE getReference() { return actual.getReference(); } /** * Verifies that the actual {@link AtomicStampedReference} has the given stamp. * * Examples: * <pre><code class='java'> // this assertion succeeds: * assertThat(new AtomicStampedReference&lt;&gt;("actual", 1234)).hasStamp(1234); * * // this assertion fails: * assertThat(new AtomicStampedReference&lt;&gt;("actual", 1234)).hasStamp(5678);</code></pre> * * @param expectedStamp the expected stamp inside the {@link AtomicStampedReference}. * @return this assertion object. * @since 2.7.0 / 3.7.0 */ public AtomicStampedReferenceAssert<VALUE> hasStamp(int expectedStamp) {<FILL_FUNCTION_BODY>} }
int timestamp = actual.getStamp(); if (timestamp != expectedStamp) throwAssertionError(shouldHaveStamp(actual, expectedStamp)); return this;
565
46
611
<methods>public AtomicStampedReferenceAssert<VALUE> hasReference(VALUE) <variables>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/ClassBasedNavigableIterableAssert.java
ClassBasedNavigableIterableAssert
buildAssert
class ClassBasedNavigableIterableAssert<SELF extends ClassBasedNavigableIterableAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>, ACTUAL extends Iterable<? extends ELEMENT>, ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> extends AbstractIterableAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> { private Class<ELEMENT_ASSERT> assertClass; @SuppressWarnings({ "rawtypes", "unchecked" }) public static <ACTUAL extends Iterable<? extends ELEMENT>, ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> ClassBasedNavigableIterableAssert<?, ACTUAL, ELEMENT, ELEMENT_ASSERT> assertThat(ACTUAL actual, Class<ELEMENT_ASSERT> assertClass) { return new ClassBasedNavigableIterableAssert(actual, ClassBasedNavigableIterableAssert.class, assertClass); } // @format:on public ClassBasedNavigableIterableAssert(ACTUAL actual, Class<?> selfType, Class<ELEMENT_ASSERT> assertClass) { super(actual, selfType); this.assertClass = assertClass; } @SuppressWarnings("unchecked") @Override protected SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable) { return (SELF) new ClassBasedNavigableIterableAssert<>(iterable, ClassBasedNavigableIterableAssert.class, assertClass); } @Override public ELEMENT_ASSERT toAssert(ELEMENT value, String description) { return buildAssert(value, description, value.getClass()); } private <V> ELEMENT_ASSERT buildAssert(V value, String description, Class<?> clazz) {<FILL_FUNCTION_BODY>} }
try { Constructor<?>[] declaredConstructors = assertClass.getDeclaredConstructors(); // find a matching Assert constructor for E or one of its subclass. for (Constructor<?> constructor : declaredConstructors) { if (constructor.getParameterCount() == 1 && constructor.getParameterTypes()[0].isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") ELEMENT_ASSERT newAssert = (ELEMENT_ASSERT) constructor.newInstance(value); return newAssert.as(description); } } throw new RuntimeException("Failed to find a constructor matching " + value + " class to build the expected Assert class"); } catch (Exception e) { throw new RuntimeException("Failed to build an assert object with " + value + ": " + e.getMessage(), e); }
498
212
710
<methods>public SELF allMatch(Predicate<? super ELEMENT>) ,public SELF allMatch(Predicate<? super ELEMENT>, java.lang.String) ,public SELF allSatisfy(Consumer<? super ELEMENT>) ,public SELF allSatisfy(ThrowingConsumer<? super ELEMENT>) ,public SELF anyMatch(Predicate<? super ELEMENT>) ,public SELF anySatisfy(Consumer<? super ELEMENT>) ,public SELF anySatisfy(ThrowingConsumer<? super ELEMENT>) ,public SELF are(Condition<? super ELEMENT>) ,public SELF areAtLeast(int, Condition<? super ELEMENT>) ,public SELF areAtLeastOne(Condition<? super ELEMENT>) ,public SELF areAtMost(int, Condition<? super ELEMENT>) ,public SELF areExactly(int, Condition<? super ELEMENT>) ,public SELF areNot(Condition<? super ELEMENT>) ,public transient SELF as(java.lang.String, java.lang.Object[]) ,public SELF as(org.assertj.core.description.Description) ,public final transient SELF contains(ELEMENT[]) ,public SELF containsAll(Iterable<? extends ELEMENT>) ,public SELF containsAnyElementsOf(Iterable<? extends ELEMENT>) ,public final transient SELF containsAnyOf(ELEMENT[]) ,public final transient SELF containsExactly(ELEMENT[]) ,public SELF containsExactlyElementsOf(Iterable<? extends ELEMENT>) ,public final transient SELF containsExactlyInAnyOrder(ELEMENT[]) ,public SELF containsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT>) ,public SELF containsNull() ,public final transient SELF containsOnly(ELEMENT[]) ,public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT>) ,public SELF containsOnlyNulls() ,public final transient SELF containsOnlyOnce(ELEMENT[]) ,public SELF containsOnlyOnceElementsOf(Iterable<? extends ELEMENT>) ,public final transient SELF containsSequence(ELEMENT[]) ,public SELF containsSequence(Iterable<? extends ELEMENT>) ,public final transient SELF containsSubsequence(ELEMENT[]) ,public SELF containsSubsequence(Iterable<? extends ELEMENT>) ,public SELF describedAs(org.assertj.core.description.Description) ,public transient SELF describedAs(java.lang.String, java.lang.Object[]) ,public SELF doNotHave(Condition<? super ELEMENT>) ,public final transient SELF doesNotContain(ELEMENT[]) ,public SELF doesNotContainAnyElementsOf(Iterable<? extends ELEMENT>) ,public SELF doesNotContainNull() ,public final transient SELF doesNotContainSequence(ELEMENT[]) ,public SELF doesNotContainSequence(Iterable<? extends ELEMENT>) ,public final transient SELF doesNotContainSubsequence(ELEMENT[]) ,public SELF doesNotContainSubsequence(Iterable<? extends ELEMENT>) ,public SELF doesNotHave(Condition<? super ACTUAL>) ,public transient SELF doesNotHaveAnyElementsOfTypes(Class<?>[]) ,public SELF doesNotHaveDuplicates() ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public ELEMENT_ASSERT element(int) ,public ASSERT element(int, InstanceOfAssertFactory<?,ASSERT>) ,public transient SELF elements(int[]) ,public final transient SELF endsWith(ELEMENT, ELEMENT[]) ,public SELF endsWith(ELEMENT[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(java.lang.String) ,public AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extracting(java.lang.String, Class<P>) ,public transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> extracting(java.lang.String[]) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(Function<? super ELEMENT,V>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(ThrowingExtractor<? super ELEMENT,V,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> extracting(Function<? super ELEMENT,?>[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> extractingResultOf(java.lang.String) ,public AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extractingResultOf(java.lang.String, Class<P>) ,public SELF filteredOn(java.lang.String, java.lang.Object) ,public SELF filteredOn(java.lang.String, FilterOperator<?>) ,public SELF filteredOn(Condition<? super ELEMENT>) ,public SELF filteredOn(Function<? super ELEMENT,T>, T) ,public SELF filteredOn(Predicate<? super ELEMENT>) ,public SELF filteredOnAssertions(Consumer<? super ELEMENT>) ,public SELF filteredOnAssertions(ThrowingConsumer<? super ELEMENT>) ,public SELF filteredOnNull(java.lang.String) ,public ELEMENT_ASSERT first() ,public ASSERT first(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(Function<? super ELEMENT,? extends Collection<V>>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(Function<? super ELEMENT,?>[]) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(java.lang.String) ,public transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(java.lang.String[]) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(Function<? super ELEMENT,? extends Collection<V>>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatMap(Function<? super ELEMENT,?>[]) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatMap(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>[]) ,public SELF has(Condition<? super ACTUAL>) ,public SELF hasAtLeastOneElementOfType(Class<?>) ,public transient SELF hasExactlyElementsOfTypes(Class<?>[]) ,public SELF hasOnlyElementsOfType(Class<?>) ,public transient SELF hasOnlyElementsOfTypes(Class<?>[]) ,public SELF hasOnlyOneElementSatisfying(Consumer<? super ELEMENT>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasSameElementsAs(Iterable<? extends ELEMENT>) ,public SELF hasSameSizeAs(java.lang.Object) ,public SELF hasSameSizeAs(Iterable<?>) ,public SELF hasSize(int) ,public SELF hasSizeBetween(int, int) ,public SELF hasSizeGreaterThan(int) ,public SELF hasSizeGreaterThanOrEqualTo(int) ,public SELF hasSizeLessThan(int) ,public SELF hasSizeLessThanOrEqualTo(int) ,public SELF hasToString(java.lang.String) ,public SELF have(Condition<? super ELEMENT>) ,public SELF haveAtLeast(int, Condition<? super ELEMENT>) ,public SELF haveAtLeastOne(Condition<? super ELEMENT>) ,public SELF haveAtMost(int, Condition<? super ELEMENT>) ,public SELF haveExactly(int, Condition<? super ELEMENT>) ,public SELF inBinary() ,public SELF inHexadecimal() ,public SELF is(Condition<? super ACTUAL>) ,public void isEmpty() ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public SELF isIn(Iterable<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isNot(Condition<? super ACTUAL>) ,public SELF isNotEmpty() ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public SELF isNotIn(Iterable<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public void isNullOrEmpty() ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF isSubsetOf(Iterable<? extends ELEMENT>) ,public final transient SELF isSubsetOf(ELEMENT[]) ,public ELEMENT_ASSERT last() ,public ASSERT last(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(Function<? super ELEMENT,V>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(ThrowingExtractor<? super ELEMENT,V,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> map(Function<? super ELEMENT,?>[]) ,public SELF noneMatch(Predicate<? super ELEMENT>) ,public SELF noneSatisfy(Consumer<? super ELEMENT>) ,public SELF noneSatisfy(ThrowingConsumer<? super ELEMENT>) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public final transient SELF satisfiesExactly(Consumer<? super ELEMENT>[]) ,public final transient SELF satisfiesExactly(ThrowingConsumer<? super ELEMENT>[]) ,public final transient SELF satisfiesExactlyInAnyOrder(Consumer<? super ELEMENT>[]) ,public final transient SELF satisfiesExactlyInAnyOrder(ThrowingConsumer<? super ELEMENT>[]) ,public SELF satisfiesOnlyOnce(Consumer<? super ELEMENT>) ,public SELF satisfiesOnlyOnce(ThrowingConsumer<? super ELEMENT>) ,public ELEMENT_ASSERT singleElement() ,public ASSERT singleElement(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractIterableSizeAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT> size() ,public final transient SELF startsWith(ELEMENT[]) ,public SELF usingComparator(Comparator<? super ACTUAL>) ,public SELF usingComparator(Comparator<? super ACTUAL>, java.lang.String) ,public transient SELF usingComparatorForElementFieldsWithNames(Comparator<T>, java.lang.String[]) ,public SELF usingComparatorForElementFieldsWithType(Comparator<T>, Class<T>) ,public SELF usingComparatorForType(Comparator<T>, Class<T>) ,public SELF usingDefaultComparator() ,public SELF usingDefaultElementComparator() ,public SELF usingElementComparator(Comparator<? super ELEMENT>) ,public transient SELF usingElementComparatorIgnoringFields(java.lang.String[]) ,public transient SELF usingElementComparatorOnFields(java.lang.String[]) ,public SELF usingFieldByFieldElementComparator() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration) ,public RecursiveComparisonAssert<?> usingRecursiveComparison() ,public RecursiveComparisonAssert<?> usingRecursiveComparison(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) ,public SELF usingRecursiveFieldByFieldElementComparator() ,public SELF usingRecursiveFieldByFieldElementComparator(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) ,public transient SELF usingRecursiveFieldByFieldElementComparatorIgnoringFields(java.lang.String[]) ,public transient SELF usingRecursiveFieldByFieldElementComparatorOnFields(java.lang.String[]) ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withThreadDumpOnError() ,public SELF zipSatisfy(Iterable<OTHER_ELEMENT>, BiConsumer<? super ELEMENT,OTHER_ELEMENT>) <variables>private static final java.lang.String ASSERT,private org.assertj.core.internal.TypeComparators comparatorsByType,private Map<java.lang.String,Comparator<?>> comparatorsForElementPropertyOrFieldNames,private org.assertj.core.internal.TypeComparators comparatorsForElementPropertyOrFieldTypes,protected org.assertj.core.internal.Iterables iterables
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/ClassBasedNavigableListAssert.java
ClassBasedNavigableListAssert
newAbstractIterableAssert
class ClassBasedNavigableListAssert<SELF extends ClassBasedNavigableListAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>, ACTUAL extends List<? extends ELEMENT>, ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> extends AbstractListAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> { private Class<ELEMENT_ASSERT> assertClass; @SuppressWarnings({ "unchecked", "rawtypes" }) public static <ELEMENT, ACTUAL extends List<? extends ELEMENT>, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> ClassBasedNavigableListAssert<?, ACTUAL, ELEMENT, ELEMENT_ASSERT> assertThat(List<? extends ELEMENT> actual, Class<ELEMENT_ASSERT> assertClass) { return new ClassBasedNavigableListAssert(actual, assertClass); } //@format:on public ClassBasedNavigableListAssert(ACTUAL actual, Class<ELEMENT_ASSERT> assertClass) { super(actual, ClassBasedNavigableListAssert.class); this.assertClass = assertClass; } @Override public ELEMENT_ASSERT toAssert(ELEMENT value, String description) { return buildAssert(value, description, value.getClass()); } private <V> ELEMENT_ASSERT buildAssert(V value, String description, Class<?> clazz) { try { Constructor<?>[] declaredConstructors = assertClass.getDeclaredConstructors(); // find a matching Assert constructor for E or one of its subclass. for (Constructor<?> constructor : declaredConstructors) { if (constructor.getParameterCount() == 1 && constructor.getParameterTypes()[0].isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") ELEMENT_ASSERT newAssert = (ELEMENT_ASSERT) constructor.newInstance(value); return newAssert.as(description); } } throw new RuntimeException("Failed to find a constructor matching " + value + " class to build the expected Assert class"); } catch (Exception e) { throw new RuntimeException("Failed to build an assert object with " + value + ": " + e.getMessage(), e); } } @SuppressWarnings("unchecked") @Override protected SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable) {<FILL_FUNCTION_BODY>} }
checkArgument(iterable instanceof List, "Expecting %s to be a List", iterable); return (SELF) new ClassBasedNavigableListAssert<>((List<? extends ELEMENT>) iterable, assertClass);
658
59
717
<methods>public transient SELF as(java.lang.String, java.lang.Object[]) ,public SELF as(org.assertj.core.description.Description) ,public SELF contains(ELEMENT, org.assertj.core.data.Index) ,public SELF describedAs(org.assertj.core.description.Description) ,public transient SELF describedAs(java.lang.String, java.lang.Object[]) ,public SELF doesNotContain(ELEMENT, org.assertj.core.data.Index) ,public SELF doesNotHave(Condition<? super ACTUAL>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF has(Condition<? super ELEMENT>, org.assertj.core.data.Index) ,public SELF has(Condition<? super ACTUAL>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public SELF is(Condition<? super ELEMENT>, org.assertj.core.data.Index) ,public SELF is(Condition<? super ACTUAL>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public SELF isIn(Iterable<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isNot(Condition<? super ACTUAL>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public SELF isNotIn(Iterable<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF isSorted() ,public SELF isSortedAccordingTo(Comparator<? super ELEMENT>) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF satisfies(Consumer<? super ELEMENT>, org.assertj.core.data.Index) ,public SELF usingComparator(Comparator<? super ACTUAL>) ,public SELF usingComparator(Comparator<? super ACTUAL>, java.lang.String) ,public SELF usingDefaultComparator() ,public SELF usingDefaultElementComparator() ,public SELF usingElementComparator(Comparator<? super ELEMENT>) ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withThreadDumpOnError() <variables>org.assertj.core.internal.Lists lists
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/ClassLoadingStrategyFactory.java
ClassLoadingStrategyFactory
classLoadingStrategy
class ClassLoadingStrategyFactory { private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); private static final Method PRIVATE_LOOKUP_IN; // Class loader of AssertJ static final ClassLoader ASSERTJ_CLASS_LOADER = ClassLoadingStrategyFactory.class.getClassLoader(); static { Method privateLookupIn; try { privateLookupIn = MethodHandles.class.getMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class); } catch (Exception e) { privateLookupIn = null; } PRIVATE_LOOKUP_IN = privateLookupIn; } static ClassLoadingStrategyPair classLoadingStrategy(Class<?> assertClass) {<FILL_FUNCTION_BODY>} // Pair holder of class loader and class loading strategy to use // for ByteBuddy class generation. static class ClassLoadingStrategyPair { private final ClassLoader classLoader; private final ClassLoadingStrategy<ClassLoader> classLoadingStrategy; ClassLoadingStrategyPair(ClassLoader classLoader, ClassLoadingStrategy<ClassLoader> classLoadingStrategy) { this.classLoader = classLoader; this.classLoadingStrategy = classLoadingStrategy; } ClassLoader getClassLoader() { return classLoader; } ClassLoadingStrategy<ClassLoader> getClassLoadingStrategy() { return classLoadingStrategy; } } // Composite class loader for when the assert class is from a different // class loader than AssertJ. This can occur in OSGi when the assert class is // from a bundle. The composite class loader provides access to the internal, // non-exported types of AssertJ. ByteBuddy will define the proxy class in the // CompositeClassLoader rather than in the class loader of the assert class. // This means the assert class cannot assume package private access to super // types, interfaces, etc. since the proxy class is defined in a different // class loader (the CompositeClassLoader) than the assert class. static class CompositeClassLoader extends ClassLoader implements ClassLoadingStrategy<ClassLoader> { CompositeClassLoader(ClassLoader parent) { super(parent); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { return ASSERTJ_CLASS_LOADER.loadClass(name); } @Override protected URL findResource(String name) { return ASSERTJ_CLASS_LOADER.getResource(name); } @Override protected Enumeration<URL> findResources(String name) throws IOException { return ASSERTJ_CLASS_LOADER.getResources(name); } @Override public Map<TypeDescription, Class<?>> load(ClassLoader classLoader, Map<TypeDescription, byte[]> types) { Map<TypeDescription, Class<?>> result = new LinkedHashMap<>(); for (Map.Entry<TypeDescription, byte[]> entry : types.entrySet()) { TypeDescription typeDescription = entry.getKey(); String name = typeDescription.getName(); synchronized (getClassLoadingLock(name)) { Class<?> type = findLoadedClass(name); if (type != null) { throw new IllegalStateException("Cannot define already loaded type: " + type); } byte[] typeDefinition = entry.getValue(); type = defineClass(name, typeDefinition, 0, typeDefinition.length); result.put(typeDescription, type); } } return result; } } }
// Use ClassLoader of assertion class to allow ByteBuddy to always find it. // This is needed in an OSGi runtime when a custom assertion class is // defined in a different OSGi bundle. ClassLoader assertClassLoader = assertClass.getClassLoader(); if (assertClassLoader != ASSERTJ_CLASS_LOADER) { // Return a new CompositeClassLoader if the assertClass is from a // different class loader than AssertJ. Otherwise return the class // loader of AssertJ since there is no need to use a composite class // loader. CompositeClassLoader compositeClassLoader = new CompositeClassLoader(assertClassLoader); return new ClassLoadingStrategyPair(compositeClassLoader, compositeClassLoader); } if (ClassInjector.UsingReflection.isAvailable()) { return new ClassLoadingStrategyPair(assertClassLoader, ClassLoadingStrategy.Default.INJECTION); } else if (ClassInjector.UsingLookup.isAvailable()) { try { return new ClassLoadingStrategyPair(assertClassLoader, ClassLoadingStrategy.UsingLookup.of(PRIVATE_LOOKUP_IN.invoke(null, assertClass, LOOKUP))); } catch (Exception e) { throw new IllegalStateException("Could not access package of " + assertClass, e); } } else { throw new IllegalStateException("No code generation strategy available"); }
885
347
1,232
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/ComparatorFactory.java
ComparatorFactory
floatComparatorWithPrecision
class ComparatorFactory { public static final ComparatorFactory INSTANCE = new ComparatorFactory(); public Comparator<Double> doubleComparatorWithPrecision(double precision) { // can't use <> with anonymous class in java 8 return new Comparator<Double>() { @Override public int compare(Double double1, Double double2) { if (Doubles.instance().isNanOrInfinite(precision)) { throw new IllegalArgumentException("Precision should not be Nan or Infinity!"); } // handle NAN or Infinity cases with Java Float behavior (and not BigDecimal that are used afterwards) if (Doubles.instance().isNanOrInfinite(double1) || Doubles.instance().isNanOrInfinite(double2)) { return Double.compare(double1, double2); } // if floats are close enough they are considered equal, otherwise we compare as BigDecimal which does exact computation. return isWithinPrecision(double1, double2, precision) ? 0 : asBigDecimal(double1).compareTo(asBigDecimal(double2)); } @Override public String toString() { return "double comparator at precision " + precision + " (values are considered equal if diff == precision)"; } }; } public Comparator<Float> floatComparatorWithPrecision(float precision) {<FILL_FUNCTION_BODY>} /** * Convert to a precise BigDecimal object using an intermediate String. * * @param <T> type of expected and precision, which should be the subclass of java.lang.Number and java.lang.Comparable * @param number the Number to convert * @return the built BigDecimal */ private static <T extends Number> BigDecimal asBigDecimal(T number) { return new BigDecimal(String.valueOf(number)); } /** * Returns true if the abs(expected - precision) is &lt;= precision, false otherwise. * @param actual the actual value * @param expected the expected value * @param precision the acceptable precision * * @param <T> type of number to compare including the precision * @return whether true if the abs(expected - precision) is &lt;= precision, false otherwise. */ private static <T extends Number> boolean isWithinPrecision(T actual, T expected, T precision) { BigDecimal expectedBigDecimal = asBigDecimal(expected); BigDecimal actualBigDecimal = asBigDecimal(actual); BigDecimal absDifference = expectedBigDecimal.subtract(actualBigDecimal).abs(); BigDecimal precisionAsBigDecimal = asBigDecimal(precision); return absDifference.compareTo(precisionAsBigDecimal) <= 0; } }
// can't use <> with anonymous class in java 8 return new Comparator<Float>() { @Override public int compare(Float float1, Float float2) { Floats floats = Floats.instance(); if (floats.isNanOrInfinite(precision)) { throw new IllegalArgumentException("Precision should not be Nan or Infinity!"); } // handle NAN or Infinity cases with Java Float behavior (and not BigDecimal that are used afterwards) if (floats.isNanOrInfinite(float1) || floats.isNanOrInfinite(float2)) { return Float.compare(float1, float2); } // if floats are close enough they are considered equal, otherwise we compare as BigDecimal which does exact computation. return isWithinPrecision(float1, float2, precision) ? 0 : asBigDecimal(float1).compareTo(asBigDecimal(float2)); } @Override public String toString() { return "float comparator at precision " + precision + " (values are considered equal if diff == precision)"; } };
722
293
1,015
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/Condition.java
Condition
toString
class Condition<T> implements Descriptable<Condition<T>> { /** * Describes the condition status after being evaluated. */ public enum Status { SUCCESS("[✓]"), FAIL("[✗]"); public final String label; Status(String label) { this.label = label; } @Override public String toString() { return this.label; } } @VisibleForTesting Description description; // might not be used private Predicate<T> predicate; /** * Creates a new <code>{@link Condition}</code>. The default description of this condition will the simple name of the * condition's class. */ public Condition() { as(getClass().getSimpleName()); } /** * Creates a new <code>{@link Condition}</code>. * * @param description the description of this condition. * @throws NullPointerException if the given description is {@code null}. */ public Condition(String description) { as(description); } /** * Creates a new <code>{@link Condition}</code> with the given {@link Predicate}, the built Condition will be met if * the Predicate is. * * <p> * You must give a description, it will be used to build a nice error message when the condition fails, you can pass * args to build the description as in {@link String#format(String, Object...)}. * <p> * Example: * <pre><code class='java'> // build condition with Predicate&lt;String&gt; and set description using String#format pattern. * Condition&lt;String&gt; fairyTale = new Condition&lt;String&gt;(s -&gt; s.startsWith("Once upon a time"), "a %s tale", "fairy"); * * String littleRedCap = "Once upon a time there was a dear little girl ..."; * assertThat(littleRedCap).is(fairyTale);</code></pre> * * Error message example: * <pre><code class='java'> // unfortunately this assertion fails ... but contact me if you can make it pass :) * assertThat("life").is(fairyTale); * // error message * Expecting: * &lt;"life"&gt; * to be &lt;a fairy tale&gt;</code></pre> * * @param predicate the {@link Predicate} used to build the condition. * @param description the description of this condition. * @param args optional parameter if description is a format String. * @throws NullPointerException if the given {@link Predicate} is {@code null}. * @throws NullPointerException if the given description is {@code null}. */ public Condition(Predicate<T> predicate, String description, Object... args) { checkPredicate(predicate); this.predicate = predicate; this.description = new TextDescription(description, args); } /** * Creates a new <code>{@link Condition}</code>. * * @param description the description of this condition. * @throws NullPointerException if the given description is {@code null}. */ public Condition(Description description) { as(description); } /** {@inheritDoc} */ @Override public Condition<T> describedAs(Description newDescription) { description = Description.emptyIfNull(newDescription); return this; } /** * Returns the description of this condition. * * @return the description of this condition. */ public Description description() { return description; } /** * Returns the description of this condition with its status failed or success. * * @param actual the instance to evaluate the condition status against. * @return the description of this condition with its status. */ public Description conditionDescriptionWithStatus(T actual) { Status status = status(actual); return new TextDescription(status.label + " " + description().value()); } protected Status status(T actual) { return matches(actual) ? SUCCESS : FAIL; } /** * Verifies that the given value satisfies this condition. * * @param value the value to verify. * @return {@code true} if the given value satisfies this condition; {@code false} otherwise. */ public boolean matches(T value) { checkPredicate(predicate); return predicate.test(value); } private void checkPredicate(Predicate<T> predicate) { requireNonNull(predicate, "Unless you subclass Condition and override matches, you need to pass a non null Predicate to build a Condition."); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
// call description() as Condition description could be dynamic and shoud be reevaluated return description().value();
1,253
29
1,282
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/DefaultAssertionErrorCollector.java
DefaultAssertionErrorCollector
collectAssertionError
class DefaultAssertionErrorCollector implements AssertionErrorCollector { // Marking this field as volatile doesn't ensure complete thread safety // (mutual exclusion, race-free behavior), but guarantees eventual visibility private volatile boolean wasSuccess = true; private final List<AssertionError> collectedAssertionErrors = synchronizedList(new ArrayList<>()); private final List<AfterAssertionErrorCollected> callbacks = synchronizedList(new ArrayList<>()); private AssertionErrorCollector delegate = null; public DefaultAssertionErrorCollector() { super(); callbacks.add(this); } // I think ideally, this would be set in the constructor and made final; // however, that would require a new constructor that would not make it // backward compatible with existing SoftAssertionProvider implementations. @Override public void setDelegate(AssertionErrorCollector delegate) { this.delegate = delegate; } @Override public Optional<AssertionErrorCollector> getDelegate() { return Optional.ofNullable(delegate); } @Override public void collectAssertionError(AssertionError error) {<FILL_FUNCTION_BODY>} /** * Returns a list of soft assertions collected errors. If a delegate * has been set (see {@link #setDelegate(AssertionErrorCollector) setDelegate()}, * then this method will return the result of the delegate's {@code assertErrorsCollected()}. * * @return A list of soft assertions collected errors. */ @Override public List<AssertionError> assertionErrorsCollected() { List<AssertionError> errors = delegate != null ? delegate.assertionErrorsCollected() : unmodifiableList(collectedAssertionErrors); return decorateErrorsCollected(errors); } /** * Same as {@link DefaultAssertionErrorCollector#addAfterAssertionErrorCollected(AfterAssertionErrorCollected)}, but * also removes all previously added callbacks. * * @param afterAssertionErrorCollected the callback. * * @since 3.17.0 */ public void setAfterAssertionErrorCollected(AfterAssertionErrorCollected afterAssertionErrorCollected) { callbacks.clear(); addAfterAssertionErrorCollected(afterAssertionErrorCollected); } /** * Register a callback allowing to react after an {@link AssertionError} is collected by the current soft assertions. * <p> * The callback is an instance of {@link AfterAssertionErrorCollected} which can be expressed as a lambda. * <p> * Example: * <pre><code class='java'> SoftAssertions softly = new SoftAssertions(); * StringBuilder reportBuilder = new StringBuilder(String.format("Assertion errors report:%n")); * * // register a single callback with: * softly.setAfterAssertionErrorCollected(error -&gt; reportBuilder.append(String.format("------------------%n%s%n", error.getMessage()))); * // or as many as needed with: * // softly.addAfterAssertionErrorCollected(error -&gt; reportBuilder.append(String.format("------------------%n%s%n", error.getMessage()))); * * // the AssertionErrors corresponding to the failing assertions are registered in the report * softly.assertThat("The Beatles").isEqualTo("The Rolling Stones"); * softly.assertThat(123).isEqualTo(123) * .isEqualTo(456);</code></pre> * <p> * Resulting {@code reportBuilder}: * <pre><code class='java'> Assertion errors report: * ------------------ * Expecting: * &lt;"The Beatles"&gt; * to be equal to: * &lt;"The Rolling Stones"&gt; * but was not. * ------------------ * Expecting: * &lt;123&gt; * to be equal to: * &lt;456&gt; * but was not.</code></pre> * <p> * Alternatively, if you have defined your own SoftAssertions subclass and inherited from {@link AbstractSoftAssertions}, * the only thing you have to do is to override {@link AfterAssertionErrorCollected#onAssertionErrorCollected(AssertionError)}. * * @param afterAssertionErrorCollected the callback. * * @since 3.26.0 */ public void addAfterAssertionErrorCollected(AfterAssertionErrorCollected afterAssertionErrorCollected) { callbacks.add(afterAssertionErrorCollected); } @Override public void succeeded() { if (delegate == null) { wasSuccess = true; } else { delegate.succeeded(); } } @Override public boolean wasSuccess() { return delegate == null ? wasSuccess : delegate.wasSuccess(); } /** * Modifies collected errors. Override to customize modification. * @param <T> the supertype to use in the list return value * @param errors list of errors to decorate * @return decorated list */ protected <T extends Throwable> List<T> decorateErrorsCollected(List<? extends T> errors) { return Throwables.addLineNumberToErrorMessages(errors); } }
if (delegate == null) { collectedAssertionErrors.add(error); wasSuccess = false; } else { delegate.collectAssertionError(error); } callbacks.forEach(callback -> callback.onAssertionErrorCollected(error));
1,391
72
1,463
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/ErrorCollector.java
ErrorCollector
intercept
class ErrorCollector { public static final String FIELD_NAME = "errorCollector"; private static final String INTERCEPT_METHOD_NAME = "intercept"; private static final String CLASS_NAME = ErrorCollector.class.getName(); private AssertionErrorCollector assertionErrorCollector; ErrorCollector(AssertionErrorCollector collector) { this.assertionErrorCollector = collector; } /** * @param errorCollector the {@link ErrorCollector} to gather assertions error for the assertion instance * @param assertion The instance of the method, the this reference. * @param proxy A proxy to invoke the original method. * @param method A reference to the original method. * @param stub A default value for the return type. null for reference type and 0 for the corresponding primitive types. * @return the assertion result * @throws Exception may be thrown from the assertion proxy call */ @RuntimeType public static Object intercept(@FieldValue(FIELD_NAME) ErrorCollector errorCollector, @This Object assertion, @SuperCall Callable<?> proxy, @SuperMethod(nullIfImpossible = true) Method method, @StubValue Object stub) throws Exception {<FILL_FUNCTION_BODY>} private void addError(AssertionError error) { assertionErrorCollector.collectAssertionError(error); } private void succeeded() { assertionErrorCollector.succeeded(); } private static boolean isNestedErrorCollectorProxyCall() { return countErrorCollectorProxyCalls() > 1; } private static long countErrorCollectorProxyCalls() { return Arrays.stream(Thread.currentThread().getStackTrace()) .filter(stackTraceElement -> CLASS_NAME.equals(stackTraceElement.getClassName()) && stackTraceElement.getMethodName().startsWith(INTERCEPT_METHOD_NAME)) .count(); } }
try { Object result = proxy.call(); errorCollector.succeeded(); return result; } catch (AssertionError assertionError) { if (isNestedErrorCollectorProxyCall()) { // let the most outer call handle the assertion error throw assertionError; } errorCollector.addError(assertionError); } if (method != null && !method.getReturnType().isInstance(assertion)) { // In case the object is not an instance of the return type, just default value for the return type: // null for reference type and 0 for the corresponding primitive types. return stub; } return assertion;
489
171
660
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/FactoryBasedNavigableListAssert.java
FactoryBasedNavigableListAssert
newAbstractIterableAssert
class FactoryBasedNavigableListAssert<SELF extends FactoryBasedNavigableListAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>, ACTUAL extends List<? extends ELEMENT>, ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> extends AbstractListAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> { private AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory; @SuppressWarnings({ "unchecked", "rawtypes" }) public static <ACTUAL extends List<? extends ELEMENT>, ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> FactoryBasedNavigableListAssert<?, ACTUAL, ELEMENT, ELEMENT_ASSERT> assertThat(List<? extends ELEMENT> actual, AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory) { return new FactoryBasedNavigableListAssert(actual, FactoryBasedNavigableListAssert.class, assertFactory); } // @format:on public FactoryBasedNavigableListAssert(ACTUAL actual, Class<?> selfType, AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory) { super(actual, selfType); this.assertFactory = assertFactory; } @Override public ELEMENT_ASSERT toAssert(ELEMENT value, String description) { return assertFactory.createAssert(value).as(description); } @SuppressWarnings("unchecked") @Override protected SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable) {<FILL_FUNCTION_BODY>} }
checkArgument(iterable instanceof List, "Expecting %s to be a List", iterable); return (SELF) new FactoryBasedNavigableListAssert<>((List<? extends ELEMENT>) iterable, FactoryBasedNavigableListAssert.class, assertFactory);
438
75
513
<methods>public transient SELF as(java.lang.String, java.lang.Object[]) ,public SELF as(org.assertj.core.description.Description) ,public SELF contains(ELEMENT, org.assertj.core.data.Index) ,public SELF describedAs(org.assertj.core.description.Description) ,public transient SELF describedAs(java.lang.String, java.lang.Object[]) ,public SELF doesNotContain(ELEMENT, org.assertj.core.data.Index) ,public SELF doesNotHave(Condition<? super ACTUAL>) ,public SELF doesNotHaveSameClassAs(java.lang.Object) ,public SELF has(Condition<? super ELEMENT>, org.assertj.core.data.Index) ,public SELF has(Condition<? super ACTUAL>) ,public SELF hasSameClassAs(java.lang.Object) ,public SELF hasToString(java.lang.String) ,public SELF is(Condition<? super ELEMENT>, org.assertj.core.data.Index) ,public SELF is(Condition<? super ACTUAL>) ,public SELF isEqualTo(java.lang.Object) ,public SELF isExactlyInstanceOf(Class<?>) ,public SELF isIn(Iterable<?>) ,public transient SELF isIn(java.lang.Object[]) ,public SELF isInstanceOf(Class<?>) ,public transient SELF isInstanceOfAny(Class<?>[]) ,public SELF isNot(Condition<? super ACTUAL>) ,public SELF isNotEqualTo(java.lang.Object) ,public SELF isNotExactlyInstanceOf(Class<?>) ,public SELF isNotIn(Iterable<?>) ,public transient SELF isNotIn(java.lang.Object[]) ,public SELF isNotInstanceOf(Class<?>) ,public transient SELF isNotInstanceOfAny(Class<?>[]) ,public SELF isNotNull() ,public transient SELF isNotOfAnyClassIn(Class<?>[]) ,public SELF isNotSameAs(java.lang.Object) ,public transient SELF isOfAnyClassIn(Class<?>[]) ,public SELF isSameAs(java.lang.Object) ,public SELF isSorted() ,public SELF isSortedAccordingTo(Comparator<? super ELEMENT>) ,public transient SELF overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public SELF satisfies(Consumer<? super ELEMENT>, org.assertj.core.data.Index) ,public SELF usingComparator(Comparator<? super ACTUAL>) ,public SELF usingComparator(Comparator<? super ACTUAL>, java.lang.String) ,public SELF usingDefaultComparator() ,public SELF usingDefaultElementComparator() ,public SELF usingElementComparator(Comparator<? super ELEMENT>) ,public transient SELF withFailMessage(java.lang.String, java.lang.Object[]) ,public SELF withThreadDumpOnError() <variables>org.assertj.core.internal.Lists lists
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/Fail.java
Fail
fail
class Fail { /** * Sets whether we remove elements related to AssertJ from assertion error stack trace. * * @param removeAssertJRelatedElementsFromStackTrace flag. */ public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace) { Failures.instance().setRemoveAssertJRelatedElementsFromStackTrace(removeAssertJRelatedElementsFromStackTrace); } /** * Throws an {@link AssertionError} with the given message. * * @param <T> dummy return value type * @param failureMessage error message. * @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> fail("boom")));}. * @throws AssertionError with the given message. */ @CanIgnoreReturnValue public static <T> T fail(String failureMessage) { throw Failures.instance().failure(failureMessage); } /** * Throws an {@link AssertionError} with an empty message to be used in code like: * <pre><code class='java'> doSomething(optional.orElseGet(() -> fail()));</code></pre> * * @param <T> dummy return value type * @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> fail()));}. * @throws AssertionError with an empty message. * @since 3.26.0 */ @CanIgnoreReturnValue public static <T> T fail() {<FILL_FUNCTION_BODY>} /** * Throws an {@link AssertionError} with the given message built as {@link String#format(String, Object...)}. * * @param <T> dummy return value type * @param failureMessage error message. * @param args Arguments referenced by the format specifiers in the format string. * @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> fail("b%s", ""oom)));}. * @throws AssertionError with the given built message. */ @CanIgnoreReturnValue public static <T> T fail(String failureMessage, Object... args) { return fail(String.format(failureMessage, args)); } /** * Throws an {@link AssertionError} with the given message and with the {@link Throwable} that caused the failure. * * @param <T> dummy return value type * @param failureMessage the description of the failed assertion. It can be {@code null}. * @param realCause cause of the error. * @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> fail("boom", cause)));}. * @throws AssertionError with the given message and with the {@link Throwable} that caused the failure. */ @CanIgnoreReturnValue public static <T> T fail(String failureMessage, Throwable realCause) { AssertionError error = Failures.instance().failure(failureMessage); error.initCause(realCause); throw error; } /** * Throws an {@link AssertionError} with the {@link Throwable} that caused the failure. * * @param <T> dummy return value type * @param realCause cause of the error. * @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> fail(cause)));}. * @throws AssertionError with the {@link Throwable} that caused the failure. */ @CanIgnoreReturnValue public static <T> T fail(Throwable realCause) { return fail(null, realCause); } /** * Throws an {@link AssertionError} with a message explaining that a {@link Throwable} of given class was expected to be thrown * but had not been. * * @param <T> dummy return value type * @param throwableClass the Throwable class that was expected to be thrown. * @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> failBecauseExceptionWasNotThrown(IOException.class)));}. * @throws AssertionError with a message explaining that a {@link Throwable} of given class was expected to be thrown but had * not been. * * {@link Fail#shouldHaveThrown(Class)} can be used as a replacement. */ @CanIgnoreReturnValue public static <T> T failBecauseExceptionWasNotThrown(Class<? extends Throwable> throwableClass) { return shouldHaveThrown(throwableClass); } /** * Throws an {@link AssertionError} with a message explaining that a {@link Throwable} of given class was expected to be thrown * but had not been. * * @param <T> dummy return value type * @param throwableClass the Throwable class that was expected to be thrown. * @return nothing, it's just to be used in {@code doSomething(optional.orElseGet(() -> shouldHaveThrown(IOException.class)));}. * @throws AssertionError with a message explaining that a {@link Throwable} of given class was expected to be thrown but had * not been. */ @CanIgnoreReturnValue public static <T> T shouldHaveThrown(Class<? extends Throwable> throwableClass) { throw Failures.instance().expectedThrowableNotThrown(throwableClass); } /** * Since all its methods are static and the class is final, there is no point on creating a new instance of it. */ private Fail() {} }
// pass an empty string because passing null results in a "null" error message. return fail("");
1,458
28
1,486
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/SoftAssertionsStatement.java
SoftAssertionsStatement
build
class SoftAssertionsStatement { private SoftAssertionsProvider soft; private AssertionErrorCreator assertionErrorCreator = new AssertionErrorCreator(); private SoftAssertionsStatement(SoftAssertionsProvider soft) { this.soft = soft; } public static Statement softAssertionsStatement(SoftAssertionsProvider softAssertions, final Statement baseStatement) { return new SoftAssertionsStatement(softAssertions).build(baseStatement); } private Statement build(final Statement baseStatement) {<FILL_FUNCTION_BODY>} }
// no lambda to keep java 6 compatibility return new Statement() { @Override public void evaluate() throws Throwable { baseStatement.evaluate(); List<AssertionError> errors = soft.assertionErrorsCollected(); if (errors.isEmpty()) return; // tests assertions raised some errors assertionErrorCreator.tryThrowingMultipleFailuresError(errors); // failed to throw MultipleFailuresError -> throw MultipleFailureException instead // This new ArrayList() is necessary due to the incompatible type signatures between // MultipleFailureException.assertEmpty() (takes a List<Throwable>) and errors // (which is a List<AssertionError>). Ideally assertEmpty() should have been a // List<? extends Throwable>. MultipleFailureException.assertEmpty(new ArrayList<>(errors)); } };
141
217
358
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/SoftThrowableTypeAssert.java
SoftThrowableTypeAssert
checkThrowableType
class SoftThrowableTypeAssert<T extends Throwable> extends ThrowableTypeAssert<T> { private final SoftAssertionsProvider softAssertionsProvider; /** * Default constructor. * * @param throwableType class representing the target (expected) exception * @param softAssertionsProvider the soft assertion instance used later on to proxy {@link ThrowableAssert} */ public SoftThrowableTypeAssert(final Class<? extends T> throwableType, SoftAssertionsProvider softAssertionsProvider) { super(throwableType); this.softAssertionsProvider = softAssertionsProvider; } @Override protected ThrowableAssertAlternative<T> buildThrowableTypeAssert(T throwable) { return new SoftThrowableAssertAlternative<>(throwable, softAssertionsProvider); } @Override protected void checkThrowableType(Throwable throwable) {<FILL_FUNCTION_BODY>} @Override @CheckReturnValue public SoftThrowableTypeAssert<T> describedAs(Description description) { this.description = description; return this; } }
try { super.checkThrowableType(throwable); } catch (AssertionError error) { this.softAssertionsProvider.collectAssertionError(error); }
280
49
329
<methods>public void <init>(Class<? extends T>) ,public ThrowableTypeAssert<T> describedAs(org.assertj.core.description.Description) ,public ThrowableAssertAlternative<T> isThrownBy(org.assertj.core.api.ThrowableAssert.ThrowingCallable) <variables>protected org.assertj.core.description.Description description,protected final non-sealed Class<? extends T> expectedThrowableType
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/TemporalAssert.java
TemporalAssert
parse
class TemporalAssert extends AbstractTemporalAssert<TemporalAssert, Temporal> { public TemporalAssert(Temporal actual) { super(actual, TemporalAssert.class); } @Override public Temporal parse(String temporalAsString) {<FILL_FUNCTION_BODY>} @Override public TemporalAssert isCloseTo(String otherAsString, TemporalOffset<? super Temporal> offset) { throw new UnsupportedOperationException("This is not supported because there is no unique String representation of Temporal, this is available in concrete assertion temporal class like ZonedDateTimeAssert"); } }
throw new UnsupportedOperationException("This is not supported because there is no unique String representation of Temporal, this is available in concrete assertion temporal class like ZonedDateTimeAssert");
164
42
206
<methods>public org.assertj.core.api.TemporalAssert isCloseTo(java.time.temporal.Temporal, TemporalOffset<? super java.time.temporal.Temporal>) ,public org.assertj.core.api.TemporalAssert isCloseTo(java.lang.String, TemporalOffset<? super java.time.temporal.Temporal>) ,public org.assertj.core.api.TemporalAssert usingComparator(Comparator<? super java.time.temporal.Temporal>) ,public org.assertj.core.api.TemporalAssert usingComparator(Comparator<? super java.time.temporal.Temporal>, java.lang.String) ,public org.assertj.core.api.TemporalAssert usingDefaultComparator() <variables>org.assertj.core.internal.Comparables comparables
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/ThrowableAssert.java
ThrowableAssert
catchThrowable
class ThrowableAssert<ACTUAL extends Throwable> extends AbstractThrowableAssert<ThrowableAssert<ACTUAL>, ACTUAL> { public interface ThrowingCallable { void call() throws Throwable; } public ThrowableAssert(ACTUAL actual) { super(actual, ThrowableAssert.class); } public <V> ThrowableAssert(Callable<V> runnable) { super(buildThrowableAssertFromCallable(runnable), ThrowableAssert.class); } @SuppressWarnings("unchecked") private static <V, THROWABLE extends Throwable> THROWABLE buildThrowableAssertFromCallable(Callable<V> callable) throws AssertionError { try { callable.call(); // fail if the expected exception was *not* thrown Fail.fail("Expecting code to throw an exception."); // this will *never* happen... return null; } catch (AssertionError e) { // do not handle AssertionErrors in the next catch block! throw e; } catch (Throwable throwable) { // the throwable we will check return (THROWABLE) throwable; } } public static Throwable catchThrowable(ThrowingCallable shouldRaiseThrowable) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") public static <THROWABLE extends Throwable> THROWABLE catchThrowableOfType(ThrowingCallable shouldRaiseThrowable, Class<THROWABLE> type) { Throwable throwable = catchThrowable(shouldRaiseThrowable); if (throwable == null) return null; // check exception type new ThrowableAssert(throwable).overridingErrorMessage(shouldBeInstance(throwable, type).create()) .isInstanceOf(type); return (THROWABLE) throwable; } }
try { shouldRaiseThrowable.call(); } catch (Throwable throwable) { return throwable; } return null;
494
42
536
<methods>public AbstractThrowableAssert<?,?> cause() ,public void doesNotThrowAnyException() ,public AbstractThrowableAssert<?,?> getCause() ,public AbstractThrowableAssert<?,?> getRootCause() ,public ThrowableAssert<ACTUAL> hasCause(java.lang.Throwable) ,public ThrowableAssert<ACTUAL> hasCauseExactlyInstanceOf(Class<? extends java.lang.Throwable>) ,public ThrowableAssert<ACTUAL> hasCauseInstanceOf(Class<? extends java.lang.Throwable>) ,public ThrowableAssert<ACTUAL> hasCauseReference(java.lang.Throwable) ,public ThrowableAssert<ACTUAL> hasMessage(java.lang.String) ,public transient ThrowableAssert<ACTUAL> hasMessage(java.lang.String, java.lang.Object[]) ,public ThrowableAssert<ACTUAL> hasMessageContaining(java.lang.String) ,public transient ThrowableAssert<ACTUAL> hasMessageContaining(java.lang.String, java.lang.Object[]) ,public transient ThrowableAssert<ACTUAL> hasMessageContainingAll(java.lang.CharSequence[]) ,public ThrowableAssert<ACTUAL> hasMessageEndingWith(java.lang.String) ,public transient ThrowableAssert<ACTUAL> hasMessageEndingWith(java.lang.String, java.lang.Object[]) ,public ThrowableAssert<ACTUAL> hasMessageFindingMatch(java.lang.String) ,public ThrowableAssert<ACTUAL> hasMessageMatching(java.lang.String) ,public ThrowableAssert<ACTUAL> hasMessageMatching(java.util.regex.Pattern) ,public ThrowableAssert<ACTUAL> hasMessageNotContaining(java.lang.String) ,public transient ThrowableAssert<ACTUAL> hasMessageNotContainingAny(java.lang.CharSequence[]) ,public ThrowableAssert<ACTUAL> hasMessageStartingWith(java.lang.String) ,public transient ThrowableAssert<ACTUAL> hasMessageStartingWith(java.lang.String, java.lang.Object[]) ,public ThrowableAssert<ACTUAL> hasNoCause() ,public ThrowableAssert<ACTUAL> hasNoSuppressedExceptions() ,public ThrowableAssert<ACTUAL> hasRootCause(java.lang.Throwable) ,public ThrowableAssert<ACTUAL> hasRootCauseExactlyInstanceOf(Class<? extends java.lang.Throwable>) ,public ThrowableAssert<ACTUAL> hasRootCauseInstanceOf(Class<? extends java.lang.Throwable>) ,public ThrowableAssert<ACTUAL> hasRootCauseMessage(java.lang.String) ,public transient ThrowableAssert<ACTUAL> hasRootCauseMessage(java.lang.String, java.lang.Object[]) ,public ThrowableAssert<ACTUAL> hasStackTraceContaining(java.lang.String) ,public transient ThrowableAssert<ACTUAL> hasStackTraceContaining(java.lang.String, java.lang.Object[]) ,public ThrowableAssert<ACTUAL> hasSuppressedException(java.lang.Throwable) ,public AbstractStringAssert<?> message() ,public AbstractThrowableAssert<?,?> rootCause() <variables>org.assertj.core.internal.Throwables throwables
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/ThrowableTypeAssert.java
ThrowableTypeAssert
isThrownBy
class ThrowableTypeAssert<T extends Throwable> implements Descriptable<ThrowableTypeAssert<T>> { @VisibleForTesting protected final Class<? extends T> expectedThrowableType; protected Description description; /** * Default constructor. * * @param throwableType class representing the target (expected) exception. */ public ThrowableTypeAssert(final Class<? extends T> throwableType) { this.expectedThrowableType = requireNonNull(throwableType, "exceptionType"); } /** * Assert that an exception of type T is thrown by the {@code throwingCallable} * and allow to chain assertions on the thrown exception. * <p> * Example: * <pre><code class='java'> assertThatExceptionOfType(IOException.class).isThrownBy(() -&gt; { throw new IOException("boom!"); }) * .withMessage("boom!"); </code></pre> * * @param throwingCallable code throwing the exception of expected type * @return return a {@link ThrowableAssertAlternative}. */ public ThrowableAssertAlternative<T> isThrownBy(final ThrowingCallable throwingCallable) {<FILL_FUNCTION_BODY>} protected void checkThrowableType(Throwable throwable) { assertThat(throwable).as(description).hasBeenThrown().isInstanceOf(expectedThrowableType); } protected ThrowableAssertAlternative<T> buildThrowableTypeAssert(T throwable) { return new ThrowableAssertAlternative<>(throwable); } /** {@inheritDoc} */ @Override @CheckReturnValue public ThrowableTypeAssert<T> describedAs(Description description) { this.description = description; return this; } }
Throwable throwable = ThrowableAssert.catchThrowable(throwingCallable); checkThrowableType(throwable); @SuppressWarnings("unchecked") T castThrowable = (T) throwable; return buildThrowableTypeAssert(castThrowable).as(description);
463
77
540
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/WritableAssertionInfo.java
WritableAssertionInfo
overridingErrorMessage
class WritableAssertionInfo implements AssertionInfo { private static final String EMPTY_STRING = ""; private Supplier<String> overridingErrorMessageSupplier; private String overridingErrorMessage; private Description description; private Representation representation; public WritableAssertionInfo(Representation customRepresentation) { useRepresentation(customRepresentation == null ? CONFIGURATION_PROVIDER.representation() : customRepresentation); } public WritableAssertionInfo() { useRepresentation(CONFIGURATION_PROVIDER.representation()); } /** * {@inheritDoc} */ @Override public String overridingErrorMessage() { // at this point we can have only one of overridingErrorMessageSupplier or overridingErrorMessage return overridingErrorMessageSupplier != null ? overridingErrorMessageSupplier.get() : overridingErrorMessage; } /** * Sets the message that will replace the default message of an assertion failure. * * @param newErrorMessage the new message. It can be {@code null}. * @throws IllegalStateException if the message has already been overridden with {@link #overridingErrorMessage(Supplier)}. */ public void overridingErrorMessage(String newErrorMessage) { checkState(overridingErrorMessageSupplier == null, "An error message has already been set with overridingErrorMessage(Supplier<String> supplier)"); overridingErrorMessage = newErrorMessage; } /** * Sets the lazy fail message that will replace the default message of an assertion failure by using a supplier. * * @param supplier the new message by a supplier. It can be {@code null}. * @throws IllegalStateException if the message has already been overridden with {@link #overridingErrorMessage(String)}. */ public void overridingErrorMessage(Supplier<String> supplier) {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public Description description() { return description; } /** * Returns the text of this object's description, it is an empty String if no description was set. * * @return the text of this object's description. */ public String descriptionText() { return description == null ? EMPTY_STRING : description.value(); } /** * Returns whether the text of this object's description was set. * * @return whether the text of this object's description was set. */ public boolean hasDescription() { return description != null && !isNullOrEmpty(description.value()); } /** * Sets the description of an assertion, if given null an empty {@link Description} is set. * * @param newDescription the new description. * @param args if {@code newDescription} is a format String, {@code args} is argument of {@link String#format(String, Object...)} * @see #description(Description) */ public void description(String newDescription, Object... args) { description = new TextDescription(newDescription, args); } /** * Sets the description of an assertion, if given null an empty {@link Description} is set. * <p> * To remove or clear the description, pass a <code>{@link EmptyTextDescription}</code> as * argument. * * @param newDescription the new description. */ public void description(Description newDescription) { description = Description.emptyIfNull(newDescription); } /** * {@inheritDoc} */ @Override public Representation representation() { return representation; } public void useHexadecimalRepresentation() { representation = new HexadecimalRepresentation(); } public void useUnicodeRepresentation() { representation = new UnicodeRepresentation(); } public void useBinaryRepresentation() { representation = new BinaryRepresentation(); } public void useRepresentation(Representation newRepresentation) { requireNonNull(newRepresentation, "The representation to use should not be null."); representation = newRepresentation; } public static String mostRelevantDescriptionIn(WritableAssertionInfo info, String newDescription) { return info.hasDescription() ? info.descriptionText() : newDescription; } /** * {@inheritDoc} */ @Override public String toString() { String format = "%s[overridingErrorMessage=%s, description=%s, representation=%s]"; return format(format, getClass().getSimpleName(), quote(overridingErrorMessage()), quote(descriptionText()), quote(representation())); } }
checkState(overridingErrorMessage == null, "An error message has already been set with overridingErrorMessage(String newErrorMessage)"); overridingErrorMessageSupplier = supplier;
1,213
49
1,262
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/junit/jupiter/SoftAssertionsExtension.java
ThreadLocalErrorCollector
resolveParameter
class ThreadLocalErrorCollector implements AssertionErrorCollector { InheritableThreadLocal<AssertionErrorCollector> threadLocal = new InheritableThreadLocal<>(); @Override public Optional<AssertionErrorCollector> getDelegate() { return Optional.of(threadLocal.get()); } @Override public void setDelegate(AssertionErrorCollector assertionErrorCollector) { threadLocal.set(assertionErrorCollector); } public void reset() { threadLocal.remove(); } @Override public void collectAssertionError(AssertionError assertionError) { threadLocal.get().collectAssertionError(assertionError); } @Override public List<AssertionError> assertionErrorsCollected() { return threadLocal.get().assertionErrorsCollected(); } @Override public void succeeded() { threadLocal.get().succeeded(); } @Override public boolean wasSuccess() { return threadLocal.get().wasSuccess(); } } static boolean isPerClass(ExtensionContext context) { return context.getTestInstanceLifecycle().map(x -> x == Lifecycle.PER_CLASS).orElse(false); } static boolean isAnnotatedConcurrent(ExtensionContext context) { return findAnnotation(context.getRequiredTestClass(), Execution.class).map(Execution::value) .map(x -> x == ExecutionMode.CONCURRENT) .orElse(false); } static boolean isPerClassConcurrent(ExtensionContext context) { return isPerClass(context) && isAnnotatedConcurrent(context); } @Override public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { // find SoftAssertions fields in the test class hierarchy Collection<Field> softAssertionsFields = findFields(testInstance.getClass(), field -> isAnnotated(field, InjectSoftAssertions.class), HierarchyTraversalMode.BOTTOM_UP); for (Field softAssertionsField : softAssertionsFields) { checkIsNotStaticOrFinal(softAssertionsField); Class<? extends SoftAssertionsProvider> softAssertionsProviderClass = asSoftAssertionsProviderClass(softAssertionsField, softAssertionsField.getType()); checkIsNotAbstract(softAssertionsField, softAssertionsProviderClass); checkHasDefaultConstructor(softAssertionsField, softAssertionsProviderClass); SoftAssertionsProvider softAssertions = getSoftAssertionsProvider(context, softAssertionsProviderClass); setTestInstanceSoftAssertionsField(testInstance, softAssertionsField, softAssertions); } } @Override public void beforeEach(ExtensionContext context) throws Exception { AssertionErrorCollector collector = getAssertionErrorCollector(context); if (isPerClassConcurrent(context)) { // If the current context is "per class+concurrent", then getSoftAssertionsProvider() will have already set the delegate // for all the soft assertions provider to the thread-local error collector, so all we need to do is set the tlec's value // for the current thread. ThreadLocalErrorCollector tlec = getThreadLocalCollector(context); tlec.setDelegate(collector); } else { // Make sure that all of the soft assertion provider instances have their delegate initialised to the assertion error // collector for the current context. Also check enclosing contexts (in the case of nested tests). while (initialiseDelegate(context, collector) && context.getParent().isPresent()) { context = context.getParent().get(); } } } private static boolean initialiseDelegate(ExtensionContext context, AssertionErrorCollector collector) { Collection<SoftAssertionsProvider> providers = getSoftAssertionsProviders(context); if (providers == null) return false; providers.forEach(x -> x.setDelegate(collector)); return context.getParent().isPresent(); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { // Abort if parameter type is unsupported. if (isUnsupportedParameterType(parameterContext.getParameter())) return false; Executable executable = parameterContext.getDeclaringExecutable(); // @Testable is used as a meta-annotation on @Test, @TestFactory, @TestTemplate, etc. boolean isTestableMethod = executable instanceof Method && isAnnotated(executable, Testable.class); if (!isTestableMethod) { throw new ParameterResolutionException(format("Configuration error: cannot resolve SoftAssertionsProvider instances for [%s]. Only test methods are supported.", executable)); } Class<?> parameterType = parameterContext.getParameter().getType(); if (isAbstract(parameterType.getModifiers())) { throw new ParameterResolutionException(format("Configuration error: the resolved SoftAssertionsProvider implementation [%s] is abstract and cannot be instantiated.", executable)); } try { parameterType.getDeclaredConstructor(); } catch (@SuppressWarnings("unused") Exception e) { throw new ParameterResolutionException(format("Configuration error: the resolved SoftAssertionsProvider implementation [%s] has no default constructor and cannot be instantiated.", executable)); } return true; } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {<FILL_FUNCTION_BODY>
// The parameter type is guaranteed to be an instance of SoftAssertionsProvider @SuppressWarnings("unchecked") Class<? extends SoftAssertionsProvider> concreteSoftAssertionsProviderType = (Class<? extends SoftAssertionsProvider>) parameterContext.getParameter() .getType(); SoftAssertionsProvider provider = ReflectionSupport.newInstance(concreteSoftAssertionsProviderType); provider.setDelegate(getAssertionErrorCollector(extensionContext)); return provider;
1,377
120
1,497
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/junit/jupiter/SoftlyExtension.java
SoftlyExtension
afterTestExecution
class SoftlyExtension implements AfterTestExecutionCallback, TestInstancePostProcessor { private static final Namespace SOFTLY_EXTENSION_NAMESPACE = Namespace.create(SoftlyExtension.class); @Override public void postProcessTestInstance(Object testInstance, ExtensionContext extensionContext) throws Exception { if (isPerClassLifeCycle(extensionContext)) { throw new IllegalStateException("A SoftAssertions field is not permitted in test classes with PER_CLASS life cycle as the instance would be collecting all class tests errors (instead of per test errors). " + "Consider using {@link SoftAssertionsExtension} instead which does not have such limitation."); } // this is called multiple times depending on the test hierarchy // we store the field against the ExtensionContext where we found it initSoftAssertionsField(testInstance).ifPresent(softAssertions -> getStore(extensionContext).put(SoftlyExtension.class, softAssertions)); } @Override public void afterTestExecution(ExtensionContext extensionContext) throws Exception {<FILL_FUNCTION_BODY>} private static Optional<ExtensionContext> getParent(Optional<ExtensionContext> currentContext) { return currentContext.flatMap(ExtensionContext::getParent); } private static boolean isPerClassLifeCycle(ExtensionContext methodExtensionContext) { return methodExtensionContext.getTestInstanceLifecycle() .map(lifecycle -> lifecycle == PER_CLASS) .orElse(false); } private static Optional<SoftAssertions> initSoftAssertionsField(Object testInstance) throws IllegalAccessException { // find SoftAssertions fields in the test class hierarchy Collection<Field> softAssertionsFields = findFields(testInstance.getClass(), field -> field.getType() == SoftAssertions.class, HierarchyTraversalMode.BOTTOM_UP); if (softAssertionsFields.isEmpty()) return Optional.empty(); checkTooManySoftAssertionsFields(softAssertionsFields); Field softAssertionsField = softAssertionsFields.iterator().next(); softAssertionsField.setAccessible(true); SoftAssertions softAssertions = new SoftAssertions(); softAssertionsField.set(testInstance, softAssertions); return Optional.of(softAssertions); } private static void checkTooManySoftAssertionsFields(Collection<Field> softAssertionsFields) { if (softAssertionsFields.size() > 1) throw new IllegalStateException("Only one field of type " + SoftAssertions.class.getName() + " should be defined but found " + softAssertionsFields.size() + " : " + softAssertionsFields); } private static Store getStore(ExtensionContext extensionContext) { return extensionContext.getStore(SOFTLY_EXTENSION_NAMESPACE); } }
SoftAssertions softAssertions = getStore(extensionContext).remove(SoftlyExtension.class, SoftAssertions.class); Optional<ExtensionContext> currentContext = Optional.of(extensionContext); // try to find SoftAssertions in the hierarchy of ExtensionContexts starting with the current one. while (softAssertions == null && getParent(currentContext).isPresent()) { softAssertions = getParent(currentContext).map(context -> getStore(context).remove(SoftlyExtension.class, SoftAssertions.class)) .orElse(null); currentContext = getParent(currentContext); } if (softAssertions == null) throw new IllegalStateException("No SoftlyExtension field found"); softAssertions.assertAll();
702
185
887
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/assertion/DefaultRecursiveAssertionIntrospectionStrategy.java
DefaultRecursiveAssertionIntrospectionStrategy
getFieldType
class DefaultRecursiveAssertionIntrospectionStrategy implements RecursiveAssertionIntrospectionStrategy { @Override public List<RecursiveAssertionNode> getChildNodesOf(Object node) { return getDeclaredFieldsIncludingInherited(node.getClass()).stream() .map(field -> toNode(field, node)) .collect(toList()); } @Override public String getDescription() { return "DefaultRecursiveAssertionIntrospectionStrategy which introspects all fields (including inherited ones)"; } private static RecursiveAssertionNode toNode(Field field, Object node) { String fieldName = field.getName(); Object fieldValue = EXTRACTION.getSimpleValue(fieldName, node); Class<?> fieldType = getFieldType(fieldValue, fieldName, node); return new RecursiveAssertionNode(fieldValue, fieldName, fieldType); } private static Class<?> getFieldType(Object fieldValue, String fieldName, Object targetObject) { return fieldValue != null ? fieldValue.getClass() : getFieldType(fieldName, targetObject.getClass()); } private static Class<?> getFieldType(String fieldName, Class<?> objectClass) {<FILL_FUNCTION_BODY>} }
try { Optional<Field> potentialField = stream(objectClass.getDeclaredFields()).filter(field -> fieldName.equals(field.getName())) .findAny(); if (potentialField.isPresent()) return potentialField.get().getType(); Class<?> superclass = objectClass.getSuperclass(); if (superclass != null) return getFieldType(fieldName, superclass); throw new NoSuchFieldException(); } catch (NoSuchFieldException | SecurityException e) { throw new IllegalStateException(format("Could not find field %s on class %s, even though its name was retrieved from the class earlier", fieldName, objectClass.getCanonicalName()), e); }
332
181
513
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/assertion/RecursiveAssertionNode.java
RecursiveAssertionNode
equals
class RecursiveAssertionNode { public final Object value; public final String name; public final Class<?> type; public RecursiveAssertionNode(Object value, String name, Class<?> type) { this.value = value; this.name = name; this.type = type; } @Override public String toString() { return String.format("RecursiveAssertionNode[value=%s, name=%s, type=%s]", this.value, this.name, this.type); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(value, name, type); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RecursiveAssertionNode that = (RecursiveAssertionNode) o; return Objects.equals(value, that.value) && Objects.equals(name, that.name) && Objects.equals(type, that.type);
201
93
294
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/ComparingNormalizedFields.java
ComparingNormalizedFields
getChildrenNodeNamesOf
class ComparingNormalizedFields implements RecursiveComparisonIntrospectionStrategy { private static final String NO_FIELD_FOUND = "Unable to find field in %s, fields tried: %s and %s"; // original field name <-> normalized field name by node private final Map<Object, Map<String, String>> originalFieldNamesByNormalizedFieldNameByNode = new IdentityHashMap<>(); // use ConcurrentHashMap in case this strategy instance is used in a multi-thread context private final Map<Class<?>, Set<String>> fieldNamesPerClass = new ConcurrentHashMap<>(); /** * Returns the <b>normalized</b> names of the children nodes of the given object that will be used in the recursive comparison. * <p> * The names are normalized according to {@link #normalizeFieldName(String)}. * * @param node the object to get the child nodes from * @return the normalized names of the children nodes of the given object */ @Override public Set<String> getChildrenNodeNamesOf(Object node) {<FILL_FUNCTION_BODY>} /** * Returns the normalized version of the given field name to allow actual and expected fields to be matched. * <p> * For example, let's assume {@code actual} is a {@code Person} with camel case fields like {@code firstName} and * {@code expected} is a {@code PersonDto} with snake case field like {@code first_name}. * <p> * The default recursive comparison gathers all {@code actual} and {@code expected} fields to compare them but fails as it can't * know that {@code actual.firstName} must be compared to {@code expected.first_name}.<br/> By normalizing fields names first, * the recursive comparison can now operate on fields that can be matched. * <p> * In our example, we can either normalize fields to be camel case or snake case (camel case would be more natural though). * <p> * Note that {@link #getChildNodeValue(String, Object)} receives the normalized field name, it tries to get its value first and * if failing to do so, it tries the original field name.<br/> * In our example, if we normalize to camel case, getting {@code firstName} works fine for {@code actual} but not for * {@code expected}, we have to get the original field name {@code first_name} to get the value ({@code ComparingNormalizedFields} * implementation tracks which original field names resulted in a specific normalized field name). * * @param fieldName the field name to normalize * @return the normalized field name */ protected abstract String normalizeFieldName(String fieldName); /** * Normalize the field name and keep track of the normalized name -> original name * @param fieldName the field name to normalize * @return the normalized field name */ private String normalize(Object node, String fieldName) { String normalizedFieldName = normalizeFieldName(fieldName); if (!originalFieldNamesByNormalizedFieldNameByNode.containsKey(node)) { originalFieldNamesByNormalizedFieldNameByNode.put(node, new HashMap<>()); } originalFieldNamesByNormalizedFieldNameByNode.get(node).put(normalizedFieldName, fieldName); return normalizedFieldName; } /** * Returns the value of the given object field identified by the fieldName parameter. * <p> * Note that this method receives the normalized field name with (see {@link #normalizeFieldName(String)}), it tries to get * its value first and if failing to do so, it tries the original field name ({@code ComparingNormalizedFields} implementation * tracks which original field names resulted in a specific normalized field name). * <p> * For example, let's assume {@code actual} is a {@code Person} with camel case fields like {@code firstName} and {@code expected} is a * {@code PersonDto} with snake case field like {@code first_name} and we normalize all fields names to be camel case. In this * case, getting {@code firstName} works fine for {@code actual} but not for {@code expected}, for the latter it succeeds with * the original field name {@code first_name}. * * @param fieldName the field name * @param instance the object to read the field from * @return the object field value */ @Override public Object getChildNodeValue(String fieldName, Object instance) { // fieldName was normalized usually matching actual or expected field naming convention but not both, we first try // to get the value corresponding to fieldName but if that does not work it means the instance object class fields were // changed when normalized, to get the field value we then need to try the original field name. // This process is not super efficient since we might try two field names instead of one, improving this requires to change // the recursive comparison quite a bit to: // - introspect actual and expected differently // - keep a mapping of which actual field should be matched to which expected field // This is not a straightforward change and might quite a bit more complexity to an already rather complex feature. try { return COMPARISON.getSimpleValue(fieldName, instance); } catch (Exception e) { String originalFieldName = getOriginalFieldName(fieldName, instance); try { return COMPARISON.getSimpleValue(originalFieldName, instance); } catch (Exception ex) { throw new IntrospectionError(format(NO_FIELD_FOUND, instance, fieldName, originalFieldName), ex); } } } private String getOriginalFieldName(String fieldName, Object instance) { // call getChildrenNodeNamesOf to populate originalFieldNamesByNormalizedFieldNameByNode, the recursive comparison // should already do this if this is used outside then getChildNodeValue would fail if (!originalFieldNamesByNormalizedFieldNameByNode.containsKey(instance)) getChildrenNodeNamesOf(instance); return originalFieldNamesByNormalizedFieldNameByNode.get(instance).get(fieldName); } @Override public String getDescription() { return "comparing normalized fields"; } }
if (node == null) return new HashSet<>(); Set<String> fieldsNames = Objects.getFieldsNames(node.getClass()); // we normalize fields so that we can compare actual and expected, for example if actual has a firstName field and expected // a first_name field, we won't find firstName in expected unless we normalize it return fieldNamesPerClass.computeIfAbsent(node.getClass(), unused -> fieldsNames.stream() .map(fieldsName -> normalize(node, fieldsName)) .collect(toSet()));
1,548
144
1,692
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/ComparingProperties.java
ComparingProperties
gettersOf
class ComparingProperties implements RecursiveComparisonIntrospectionStrategy { public static final ComparingProperties COMPARING_PROPERTIES = new ComparingProperties(); private static final String GET_PREFIX = "get"; private static final String IS_PREFIX = "is"; // use ConcurrentHashMap in case this strategy instance is used in a multi-thread context private final Map<Class<?>, Set<String>> propertiesNamesPerClass = new ConcurrentHashMap<>(); @Override public Set<String> getChildrenNodeNamesOf(Object node) { if (node == null) return new HashSet<>(); return propertiesNamesPerClass.computeIfAbsent(node.getClass(), ComparingProperties::getPropertiesNamesOf); } @Override public Object getChildNodeValue(String childNodeName, Object instance) { return PropertySupport.instance().propertyValueOf(childNodeName, Object.class, instance); } @Override public String getDescription() { return "comparing properties"; } static Set<String> getPropertiesNamesOf(Class<?> clazz) { return gettersIncludingInheritedOf(clazz).stream() .map(Method::getName) .map(ComparingProperties::toPropertyName) .collect(toSet()); } private static String toPropertyName(String methodName) { String propertyWithCapitalLetter = methodName.startsWith(GET_PREFIX) ? methodName.substring(GET_PREFIX.length()) : methodName.substring(IS_PREFIX.length()); return propertyWithCapitalLetter.toLowerCase().charAt(0) + propertyWithCapitalLetter.substring(1); } public static Set<Method> gettersIncludingInheritedOf(Class<?> clazz) { return gettersOf(clazz); } private static Set<Method> gettersOf(Class<?> clazz) {<FILL_FUNCTION_BODY>} private static boolean isStatic(Method method) { return Modifier.isStatic(method.getModifiers()); } private static boolean isGetter(Method method) { if (hasParameters(method)) return false; return isRegularGetter(method) || isBooleanProperty(method); } private static boolean isRegularGetter(Method method) { return method.getName().startsWith(GET_PREFIX); } private static boolean hasParameters(Method method) { return method.getParameters().length > 0; } private static boolean isBooleanProperty(Method method) { Class<?> returnType = method.getReturnType(); return method.getName().startsWith(IS_PREFIX) && (returnType.equals(boolean.class) || returnType.equals(Boolean.class)); } }
return stream(clazz.getMethods()).filter(method -> !isInJavaLangPackage(method.getDeclaringClass())) .filter(method -> !isStatic(method)) .filter(ComparingProperties::isGetter) .collect(toCollection(LinkedHashSet::new));
711
76
787
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/ComparingSnakeOrCamelCaseFields.java
ComparingSnakeOrCamelCaseFields
normalizeAcronyms
class ComparingSnakeOrCamelCaseFields extends ComparingNormalizedFields { public static final ComparingSnakeOrCamelCaseFields COMPARING_SNAKE_OR_CAMEL_CASE_FIELDS = new ComparingSnakeOrCamelCaseFields(); /** * Transforms snake case field names into camel case (leave camel case fields as is). * <p> * For example, this allows to compare {@code Person} object with camel case fields like {@code firstName} to a * {@code PersonDto} object with snake case fields like {@code first_name}. * * @param name the field name to normalize * @return camel case version of the field name */ @Override public String normalizeFieldName(String name) { String camelCaseName = toCamelCase(name); return normalizeAcronyms(camelCaseName); } /** * Normalizes uppercase acronyms by keeping only the first acronym letter uppercase, ex: {@code normalizeAcronyms("URl")} gives * {@code "Url"} * * @param name the name to normalize * @return the normalized name */ private static String normalizeAcronyms(String name) {<FILL_FUNCTION_BODY>} @Override public String getDescription() { return "comparing camel case and snake case fields"; } }
for (int i = 0; i < name.length(); i++) { if (!isUpperCase(name.charAt(i))) continue; int j = i + 1; while (j < name.length() && isUpperCase(name.charAt(j))) { j++; } return name.substring(0, i + 1) + name.substring(i + 1, j).toLowerCase() + normalizeAcronyms(name.substring(j)); } return name;
367
138
505
<methods>public non-sealed void <init>() ,public java.lang.Object getChildNodeValue(java.lang.String, java.lang.Object) ,public Set<java.lang.String> getChildrenNodeNamesOf(java.lang.Object) ,public java.lang.String getDescription() <variables>private static final java.lang.String NO_FIELD_FOUND,private final Map<Class<?>,Set<java.lang.String>> fieldNamesPerClass,private final Map<java.lang.Object,Map<java.lang.String,java.lang.String>> originalFieldNamesByNormalizedFieldNameByNode
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonDifference.java
ComparisonDifference
fieldPathDescription
class ComparisonDifference implements Comparable<ComparisonDifference> { // ELEMENT_WITH_INDEX_PATTERN should match [0] or [123] but not name[0] or [0].name, explanation: // - ^ represents the start of the string in a regex // - \[ represents [ in a regex, need another \ to escape it in a java string // - d+ any number // - \] represents ] in a regex // - $ represents the end of the string in a regex private static final String TOP_LEVEL_ELEMENT_PATTERN = "^\\[\\d+\\]$"; private static final String FIELD = "field/property '%s'"; private static final String TOP_LEVEL_OBJECTS = "Top level actual and expected objects"; private static final String TOP_LEVEL_ELEMENTS = "Top level actual and expected objects element at index %s"; public static final String DEFAULT_TEMPLATE = "%s differ:%n" + "- actual value : %s%n" + "- expected value: %s%s"; final List<String> decomposedPath; final String concatenatedPath; final Object actual; final Object expected; final Optional<String> additionalInformation; final String template; public ComparisonDifference(DualValue dualValue) { this(dualValue.getDecomposedPath(), dualValue.actual, dualValue.expected, null, DEFAULT_TEMPLATE); } public ComparisonDifference(DualValue dualValue, String additionalInformation) { this(dualValue.getDecomposedPath(), dualValue.actual, dualValue.expected, additionalInformation, DEFAULT_TEMPLATE); } public ComparisonDifference(DualValue dualValue, String additionalInformation, String template) { this(dualValue.getDecomposedPath(), dualValue.actual, dualValue.expected, additionalInformation, template); } private ComparisonDifference(List<String> decomposedPath, Object actual, Object other, String additionalInformation, String template) { this.decomposedPath = unmodifiableList(requireNonNull(decomposedPath, "a path can't be null")); this.concatenatedPath = toConcatenatedPath(decomposedPath); this.actual = actual; this.expected = other; this.additionalInformation = Optional.ofNullable(additionalInformation); this.template = template != null ? template : DEFAULT_TEMPLATE; } public static ComparisonDifference rootComparisonDifference(Object actual, Object other, String additionalInformation) { return new ComparisonDifference(rootDualValue(actual, other), additionalInformation); } public Object getActual() { return actual; } public Object getExpected() { return expected; } public String getTemplate() { return template; } public Optional<String> getAdditionalInformation() { return additionalInformation; } public List<String> getDecomposedPath() { return decomposedPath; } @Override public String toString() { return additionalInformation.isPresent() ? format("ComparisonDifference [path=%s, actual=%s, expected=%s, template=%s, additionalInformation=%s]", concatenatedPath, actual, expected, template, additionalInformation.get()) : format("ComparisonDifference [path=%s, actual=%s, template=%s, expected=%s]", concatenatedPath, actual, template, expected); } public String multiLineDescription() { // use the default configured representation return multiLineDescription(ConfigurationProvider.CONFIGURATION_PROVIDER.representation()); } public String multiLineDescription(Representation representation) { UnambiguousRepresentation unambiguousRepresentation = new UnambiguousRepresentation(representation, actual, expected); String additionalInfo = additionalInformation.map(ComparisonDifference::formatOnNewline).orElse(""); return format(getTemplate(), fieldPathDescription(), unambiguousRepresentation.getActual(), unambiguousRepresentation.getExpected(), additionalInfo); } // returns a user-friendly path description protected String fieldPathDescription() {<FILL_FUNCTION_BODY>} private static String extractIndex(String path) { // path looks like [12] // index = 12] String index = path.substring(1); // index = 12 return index.replaceFirst("\\]", ""); } private static String formatOnNewline(String info) { return format("%n%s", info); } private static String toConcatenatedPath(List<String> decomposedPath) { String concatenatedPath = join(".", decomposedPath); // remove the . from array/list index, so person.children.[2].name -> person.children[2].name return concatenatedPath.replaceAll("\\.\\[", "["); } @Override public boolean equals(final Object other) { if (!(other instanceof ComparisonDifference)) { return false; } ComparisonDifference castOther = (ComparisonDifference) other; return Objects.equals(concatenatedPath, castOther.concatenatedPath) && Objects.equals(actual, castOther.actual) && Objects.equals(expected, castOther.expected) && Objects.equals(template, castOther.template) && Objects.equals(additionalInformation, castOther.additionalInformation); } @Override public int hashCode() { return Objects.hash(concatenatedPath, actual, expected, template, additionalInformation); } @Override public int compareTo(final ComparisonDifference other) { // we don't use '.' to join path before comparing them as it would make a.b < aa return concat(decomposedPath).compareTo(concat(other.decomposedPath)); } private static String concat(List<String> decomposedPath) { return join("", decomposedPath); } }
if (concatenatedPath.isEmpty()) return TOP_LEVEL_OBJECTS; if (concatenatedPath.matches(TOP_LEVEL_ELEMENT_PATTERN)) return format(TOP_LEVEL_ELEMENTS, extractIndex(concatenatedPath)); return format(FIELD, concatenatedPath);
1,542
81
1,623
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/ComparisonKeyDifference.java
ComparisonKeyDifference
multiLineDescription
class ComparisonKeyDifference extends ComparisonDifference { static final String TEMPLATE_FOR_KEY_DIFFERENCE = "map key difference:%n" + "- actual key : %s%n" + "- expected key: %s"; final Object actualKey; final Object expectedKey; public ComparisonKeyDifference(DualValue dualValue, Object actualKey, Object expectedKey) { super(dualValue); this.actualKey = actualKey; this.expectedKey = expectedKey; } @Override public String toString() { return format("ComparisonDifference [path=%s, actualKey=%s, expectedKey=%s]", concatenatedPath, actualKey, expectedKey); } @Override public String multiLineDescription(Representation representation) {<FILL_FUNCTION_BODY>} }
UnambiguousRepresentation unambiguousRepresentation = new UnambiguousRepresentation(representation, actual, expected); UnambiguousRepresentation unambiguousKeyRepresentation = new UnambiguousRepresentation(representation, actualKey, expectedKey); return format(DEFAULT_TEMPLATE + "%n" + TEMPLATE_FOR_KEY_DIFFERENCE, fieldPathDescription(), unambiguousRepresentation.getActual(), unambiguousRepresentation.getExpected(), "", unambiguousKeyRepresentation.getActual(), unambiguousKeyRepresentation.getExpected());
221
167
388
<methods>public void <init>(org.assertj.core.api.recursive.comparison.DualValue) ,public void <init>(org.assertj.core.api.recursive.comparison.DualValue, java.lang.String) ,public void <init>(org.assertj.core.api.recursive.comparison.DualValue, java.lang.String, java.lang.String) ,public int compareTo(org.assertj.core.api.recursive.comparison.ComparisonDifference) ,public boolean equals(java.lang.Object) ,public java.lang.Object getActual() ,public Optional<java.lang.String> getAdditionalInformation() ,public List<java.lang.String> getDecomposedPath() ,public java.lang.Object getExpected() ,public java.lang.String getTemplate() ,public int hashCode() ,public java.lang.String multiLineDescription() ,public java.lang.String multiLineDescription(org.assertj.core.presentation.Representation) ,public static org.assertj.core.api.recursive.comparison.ComparisonDifference rootComparisonDifference(java.lang.Object, java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>public static final java.lang.String DEFAULT_TEMPLATE,private static final java.lang.String FIELD,private static final java.lang.String TOP_LEVEL_ELEMENTS,private static final java.lang.String TOP_LEVEL_ELEMENT_PATTERN,private static final java.lang.String TOP_LEVEL_OBJECTS,final non-sealed java.lang.Object actual,final non-sealed Optional<java.lang.String> additionalInformation,final non-sealed java.lang.String concatenatedPath,final non-sealed List<java.lang.String> decomposedPath,final non-sealed java.lang.Object expected,final non-sealed java.lang.String template
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/DefaultRecursiveComparisonIntrospectionStrategy.java
DefaultRecursiveComparisonIntrospectionStrategy
getChildrenNodeNamesOf
class DefaultRecursiveComparisonIntrospectionStrategy implements RecursiveComparisonIntrospectionStrategy { // use ConcurrentHashMap in case this strategy instance is used in a multi-thread context private final Map<Class<?>, Set<String>> fieldNamesPerClass = new ConcurrentHashMap<>(); @Override public Set<String> getChildrenNodeNamesOf(Object node) {<FILL_FUNCTION_BODY>} @Override public Object getChildNodeValue(String childNodeName, Object instance) { return COMPARISON.getSimpleValue(childNodeName, instance); } }
if (node == null) return new HashSet<>(); // Caches the names after getting them for efficiency, a node can be introspected multiple times for example if // it belongs to an unordered collection as all actual elements are compared to all expected elements. return fieldNamesPerClass.computeIfAbsent(node.getClass(), Objects::getFieldsNames);
150
88
238
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/FieldComparators.java
FieldComparators
getComparatorForField
class FieldComparators extends FieldHolder<Comparator<?>> { protected final LinkedList<ComparatorForPatterns> comparatorByPatterns = new LinkedList<>(); /** * Registers the {@code comparator} for the given {@code fieldLocation}. * * @param fieldLocation the location where to apply the comparator * @param comparator the comparator itself */ public void registerComparator(String fieldLocation, Comparator<?> comparator) { super.put(fieldLocation, comparator); } /** * Registers the {@code comparator} for the given regexes field location. * * @param regexes the regexes field location where to apply the comparator * @param comparator the comparator to use for the regexes */ public void registerComparatorForFieldsMatchingRegexes(String[] regexes, Comparator<?> comparator) { List<Pattern> patterns = Stream.of(regexes).map(Pattern::compile).collect(toList()); comparatorByPatterns.addFirst(new ComparatorForPatterns(patterns, comparator)); } /** * Checks, whether an any comparator is associated with the giving field location. * * @param fieldLocation the field location which association need to check * @return is field location contain a custom comparator */ public boolean hasComparatorForField(String fieldLocation) { // TODO sanitize here? boolean hasComparatorForExactFieldLocation = super.hasEntity(fieldLocation); // comparator for exact location takes precedence over the one with location matched by regexes if (hasComparatorForExactFieldLocation) return true; // no comparator for exact location, check if there is a regex that matches the field location return comparatorByPatterns.stream() .anyMatch(comparatorForPatterns -> comparatorForPatterns.hasComparatorForField(fieldLocation)); } /** * Retrieves a custom comparator, which is associated with the giving field location. If this location does not * associate with any custom comparators - this method returns null. * * @param fieldLocation the field location that has to be associated with a comparator * @return a custom comparator or null */ public Comparator<?> getComparatorForField(String fieldLocation) {<FILL_FUNCTION_BODY>} /** * Returns a sequence of associated field-comparator pairs. * * @return sequence of field-comparator pairs */ public Stream<Entry<String, Comparator<?>>> comparatorByFields() { return super.entryByField(); } public Stream<Entry<List<Pattern>, Comparator<?>>> comparatorByRegexFields() { return comparatorByPatterns.stream().map(comparatorForPatterns -> entry(comparatorForPatterns.fieldPatterns, comparatorForPatterns.comparator)); } @Override public boolean isEmpty() { return super.isEmpty() && comparatorByPatterns.isEmpty(); } public boolean hasFieldComparators() { return !super.isEmpty(); } public boolean hasRegexFieldComparators() { return !comparatorByPatterns.isEmpty(); } }
Comparator<?> exactFieldLocationComparator = super.get(fieldLocation); if (exactFieldLocationComparator != null) return exactFieldLocationComparator; // no comparator for exact location, check if there is a regex that matches the field location return comparatorByPatterns.stream() .map(comparatorForPatterns -> comparatorForPatterns.getComparatorForField(fieldLocation)) .filter(comparator -> comparator != null) .findFirst() .orElse(null);
837
139
976
<methods>public void <init>() ,public Stream<Entry<java.lang.String,Comparator<?>>> entryByField() ,public boolean equals(java.lang.Object) ,public Comparator<?> get(java.lang.String) ,public boolean hasEntity(java.lang.String) ,public int hashCode() ,public boolean isEmpty() ,public void put(java.lang.String, Comparator<?>) ,public java.lang.String toString() <variables>protected final non-sealed Map<java.lang.String,Comparator<?>> fieldHolder
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/FieldHolder.java
FieldHolder
toString
class FieldHolder<T> { protected final Map<String, T> fieldHolder; public FieldHolder() { fieldHolder = new TreeMap<>(); } /** * Pairs the giving {@code entity} with the {@code fieldLocation}. * * @param fieldLocation the field location where to apply the giving entity * @param entity the entity to pair */ public void put(String fieldLocation, T entity) { fieldHolder.put(fieldLocation, entity); } /** * Retrieves a specific entity which is associated with the giving {@code filedLocation} from the field holder, if it * presents. Otherwise, this method returns {@code null}. * * @param fieldLocation the field location which has to be associated with an entity * @return entity or null */ public T get(String fieldLocation) { return fieldHolder.get(fieldLocation); } /** * Checks, whether an any entity associated with the giving field location. * * @param fieldLocation the field location which association need to check * @return is entity associated with field location */ public boolean hasEntity(String fieldLocation) { return fieldHolder.containsKey(fieldLocation); } /** * @return {@code true} is there are registered entities, {@code false} otherwise */ public boolean isEmpty() { return fieldHolder.isEmpty(); } /** * Returns a sequence of all field-entry pairs which the current holder supplies. * * @return sequence of field-entry pairs */ public Stream<Entry<String, T>> entryByField() { return fieldHolder.entrySet().stream(); } @Override public String toString() {<FILL_FUNCTION_BODY>} private static <T> String formatRegisteredEntity(Entry<String, T> entry) { return format("%s -> %s", entry.getKey(), entry.getValue()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FieldHolder<?> that = (FieldHolder<?>) o; return fieldHolder.equals(that.fieldHolder); } @Override public int hashCode() { return Objects.hash(fieldHolder); } }
List<String> registeredEntitiesDescription = fieldHolder.entrySet().stream() .map(FieldHolder::formatRegisteredEntity) .collect(toList()); return format("{%s}", join(registeredEntitiesDescription).with(", "));
604
67
671
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/VisitedDualValues.java
VisitedDualValues
registeredComparisonDifferencesOf
class VisitedDualValues { private List<VisitedDualValue> dualValues; VisitedDualValues() { this.dualValues = new ArrayList<>(); } void registerVisitedDualValue(DualValue dualValue) { this.dualValues.add(new VisitedDualValue(dualValue)); } void registerComparisonDifference(DualValue dualValue, ComparisonDifference comparisonDifference) { this.dualValues.stream() // register difference on dual values agnostic of location, to take care of values visited several times .filter(visitedDualValue -> visitedDualValue.dualValue.sameValues(dualValue)) .findFirst() .ifPresent(visitedDualValue -> visitedDualValue.comparisonDifferences.add(comparisonDifference)); } Optional<List<ComparisonDifference>> registeredComparisonDifferencesOf(DualValue dualValue) {<FILL_FUNCTION_BODY>} private static class VisitedDualValue { DualValue dualValue; List<ComparisonDifference> comparisonDifferences; VisitedDualValue(DualValue dualValue) { this.dualValue = dualValue; this.comparisonDifferences = new ArrayList<>(); } @Override public String toString() { return format("VisitedDualValue[dualValue=%s, comparisonDifferences=%s]", this.dualValue, this.comparisonDifferences); } } }
return this.dualValues.stream() // use sameValues to get already visited dual values with different location .filter(visitedDualValue -> visitedDualValue.dualValue.sameValues(dualValue)) .findFirst() .map(visitedDualValue -> visitedDualValue.comparisonDifferences);
374
82
456
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/condition/Join.java
Join
checkNotNullConditions
class Join<T> extends Condition<T> { protected static final String SUFFIX_DELIMITER = "]"; protected static final String PREFIX_DELIMITER = ":["; @VisibleForTesting Collection<Condition<? super T>> conditions; /** * Creates a new <code>{@link Join}</code>. * @param conditions the conditions to join. * @throws NullPointerException if the given array is {@code null}. * @throws NullPointerException if any of the elements in the given array is {@code null}. */ @SafeVarargs protected Join(Condition<? super T>... conditions) { this(Arrays.stream(checkNotNullConditions(conditions))); } /** * Creates a new <code>{@link Join}</code>. * @param conditions the conditions to join. * @throws NullPointerException if the given iterable is {@code null}. * @throws NullPointerException if any of the elements in the given iterable is {@code null}. */ protected Join(Iterable<? extends Condition<? super T>> conditions) { this(Streams.stream(checkNotNullConditions(conditions))); } private Join(Stream<? extends Condition<? super T>> stream) { conditions = stream.map(Join::notNull).collect(toList()); calculateDescription(); } private static <T> T checkNotNullConditions(T conditions) {<FILL_FUNCTION_BODY>} /** * method used to prefix the subclass join description, ex: "all of" * @return the prefix to use to build the description. */ public abstract String descriptionPrefix(); /** * method used to calculate the subclass join description */ private void calculateDescription() { List<Description> conditionsDescriptions = conditions.stream() .map(Condition::description) .collect(toList()); String prefix = descriptionPrefix() + PREFIX_DELIMITER; describedAs(new JoinDescription(prefix, SUFFIX_DELIMITER, conditionsDescriptions)); } @Override public Description description() { calculateDescription(); return super.description(); } @Override public Description conditionDescriptionWithStatus(T actual) { List<Description> descriptionsWithStatus = conditions.stream() .map(condition -> condition.conditionDescriptionWithStatus(actual)) .collect(toList()); String prefix = status(actual).label + " " + descriptionPrefix() + PREFIX_DELIMITER; return new JoinDescription(prefix, SUFFIX_DELIMITER, descriptionsWithStatus); } private static <T> T notNull(T condition) { return requireNonNull(condition, "The given conditions should not have null entries"); } /** * Returns the conditions to join. * @return the conditions to join. */ public final Collection<Condition<? super T>> conditions() { return unmodifiableCollection(conditions); } }
return requireNonNull(conditions, "The given conditions should not be null");
765
21
786
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient void <init>(Predicate<T>, java.lang.String, java.lang.Object[]) ,public void <init>(org.assertj.core.description.Description) ,public org.assertj.core.description.Description conditionDescriptionWithStatus(T) ,public Condition<T> describedAs(org.assertj.core.description.Description) ,public org.assertj.core.description.Description description() ,public boolean matches(T) ,public java.lang.String toString() <variables>org.assertj.core.description.Description description,private Predicate<T> predicate
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/condition/MappedCondition.java
MappedCondition
buildMappingDescription
class MappedCondition<FROM, TO> extends Condition<FROM> { private Condition<TO> condition; private Function<FROM, TO> mapping; private String mappingDescription; /** * Creates a new <code>{@link MappedCondition}</code>. * <p> * Example: * <pre><code class='java'> Condition&lt;String&gt; hasLineSeparator = new Condition&lt;&gt;(t -&gt; t.contains(System.lineSeparator()), "has lineSeparator"); * * Condition&lt;Optional&lt;String&gt;&gt; optionalWithLineSeparator = MappedCondition.mappedCondition(Optional::get, hasLineSeparator, "optional value has lineSeparator"); * * // assertion succeeds * assertThat(Optional.of("a" + System.lineSeparator())).is(optionalWithLineSeparator); * // returns true * optionalWithLineSeparator.matches(Optional.of("a" + System.lineSeparator())); * * // assertion fails * assertThat(Optional.of("a")).is(optionalWithLineSeparator); * // returns false * optionalWithLineSeparator.matches(Optional.of("a"));</code></pre> * <p> * Note that the mappingDescription argument follows {@link String#format(String, Object...)} syntax. * * @param <FROM> the type of object the given condition accept. * @param <TO> the type of object the nested condition accept. * @param mapping the Function that maps the value to test to the a value for the nested condition. * @param condition the nested condition to evaluate. * @param mappingDescription describes the mapping, follows {@link String#format(String, Object...)} syntax. * @param args for describing the mapping as in {@link String#format(String, Object...)} syntax. * @return the created {@code MappedCondition}. * @throws NullPointerException if the given condition is {@code null}. * @throws NullPointerException if the given mapping is {@code null}. */ public static <FROM, TO> MappedCondition<FROM, TO> mappedCondition(Function<FROM, TO> mapping, Condition<TO> condition, String mappingDescription, Object... args) { requireNonNull(mappingDescription, "The given mappingDescription should not be null"); return new MappedCondition<>(mapping, condition, format(mappingDescription, args)); } /** * Creates a new <code>{@link MappedCondition}</code> * * @param <FROM> the type of object the given condition accept. * @param <TO> the type of object the nested condition accept. * @param mapping the Function that maps the value to test to the a value for the nested condition. * @param condition the nested condition to evaluate. * @return the created {@code MappedCondition}. * @throws NullPointerException if the given condition is {@code null}. * @throws NullPointerException if the given mapping is {@code null}. */ public static <FROM, TO> MappedCondition<FROM, TO> mappedCondition(Function<FROM, TO> mapping, Condition<TO> condition) { return mappedCondition(mapping, condition, ""); } private MappedCondition(Function<FROM, TO> mapping, Condition<TO> condition, String mappingDescription) { requireNonNull(condition, "The given condition should not be null"); requireNonNull(mapping, "The given mapping function should not be null"); this.mapping = mapping; this.mappingDescription = mappingDescription; this.condition = condition; } /** * Maps the value with the given function and verifies that it satisfies the nested <code>{@link Condition}</code>. * * @param value the value to map * @return {@code true} if the given mapped value satisfies the nested condition; {@code false} otherwise. */ @Override public boolean matches(FROM value) { TO mappedObject = mapping.apply(value); String desc = buildMappingDescription(value, mappedObject); describedAs(desc); return condition.matches(mappedObject); } /** * Build the mapped condition description when applied with the FROM and TO values. * * @param from the value to map * @param to the mapped value * @return the mapped condition description . */ protected String buildMappingDescription(FROM from, TO to) { return buildMappingDescription(from, to, true); } private String buildMappingDescription(FROM from, TO to, boolean withNested) {<FILL_FUNCTION_BODY>} @Override public Description conditionDescriptionWithStatus(FROM actual) { TO mappedObject = mapping.apply(actual); Description descriptionsWithStatus = condition.conditionDescriptionWithStatus(mappedObject); Status status = status(actual); String descriptionStart = format("%s %s", status, buildMappingDescription(actual, mappedObject, false)); return new JoinDescription(descriptionStart, "", list(descriptionsWithStatus)); } private static String className(Object object) { return object.getClass().getSimpleName(); } }
StringBuilder sb = new StringBuilder("mapped"); if (!mappingDescription.isEmpty()) sb.append(format("%n using: %s", mappingDescription)); if (from == null) sb.append(format("%n from: %s%n", from)); else sb.append(format("%n from: <%s> %s%n", className(from), from)); if (to == null) sb.append(format(" to: %s%n", to)); else sb.append(format(" to: <%s> %s%n", className(to), to)); sb.append(" then checked:"); if (withNested) sb.append(format("%n %-10s", condition)); return sb.toString();
1,285
192
1,477
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient void <init>(Predicate<FROM>, java.lang.String, java.lang.Object[]) ,public void <init>(org.assertj.core.description.Description) ,public org.assertj.core.description.Description conditionDescriptionWithStatus(FROM) ,public Condition<FROM> describedAs(org.assertj.core.description.Description) ,public org.assertj.core.description.Description description() ,public boolean matches(FROM) ,public java.lang.String toString() <variables>org.assertj.core.description.Description description,private Predicate<FROM> predicate
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/condition/NestableCondition.java
NestableCondition
compose
class NestableCondition<ACTUAL, NESTED> extends Join<ACTUAL> { private final String descriptionPrefix; /** * Creates a new <code>{@link NestableCondition}</code> * @param descriptionPrefix the prefix to use to build the description * @param extractor a function to extract the nested object of type {@literal T} from an object fo type {@literal K} * @param conditions conditions to be checked * @return the nestable condition * @param <ACTUAL> the type of object the resulting condition accepts * @param <NESTED> the type of object nested into {@literal K} */ @SafeVarargs public static <ACTUAL, NESTED> Condition<ACTUAL> nestable(String descriptionPrefix, Function<? super ACTUAL, ? extends NESTED> extractor, Condition<? super NESTED>... conditions) { return new NestableCondition<>(descriptionPrefix, stream(conditions), extractor); } /** * Creates a new <code>{@link NestableCondition}</code> * @param descriptionPrefix the prefix to use to build the description * @param conditions conditions to be checked * @return the nestable condition * @param <ACTUAL> the type of object the resulting condition accepts */ @SafeVarargs public static <ACTUAL> Condition<ACTUAL> nestable(String descriptionPrefix, Condition<? super ACTUAL>... conditions) { return new NestableCondition<ACTUAL, ACTUAL>(descriptionPrefix, stream(conditions)); } private NestableCondition(String descriptionPrefix, Stream<? extends Condition<? super NESTED>> conditions, Function<? super ACTUAL, ? extends NESTED> extractor) { super(compose(conditions, extractor)); this.descriptionPrefix = descriptionPrefix; } private NestableCondition(String descriptionPrefix, Stream<? extends Condition<? super ACTUAL>> conditions) { super(conditions.collect(toList())); this.descriptionPrefix = descriptionPrefix; } @Override public boolean matches(ACTUAL value) { return conditions.stream().allMatch(condition -> condition.matches(value)); } @Override public String descriptionPrefix() { return descriptionPrefix; } private static <ACTUAL, NESTED> List<Condition<? super ACTUAL>> compose(Stream<? extends Condition<? super NESTED>> conditions, Function<? super ACTUAL, ? extends NESTED> extractor) { return conditions.map(condition -> compose(condition, extractor)).collect(toList()); } private static <ACTUAL, NESTED> Condition<ACTUAL> compose(Condition<? super NESTED> condition, Function<? super ACTUAL, ? extends NESTED> extractor) {<FILL_FUNCTION_BODY>} }
return new Condition<ACTUAL>(condition.description()) { @Override public boolean matches(ACTUAL value) { return condition.matches(extractor.apply(value)); } @Override public Description conditionDescriptionWithStatus(ACTUAL actual) { return condition.conditionDescriptionWithStatus(extractor.apply(actual)); } };
745
96
841
<methods>public org.assertj.core.description.Description conditionDescriptionWithStatus(ACTUAL) ,public final Collection<Condition<? super ACTUAL>> conditions() ,public org.assertj.core.description.Description description() ,public abstract java.lang.String descriptionPrefix() <variables>protected static final java.lang.String PREFIX_DELIMITER,protected static final java.lang.String SUFFIX_DELIMITER,Collection<Condition<? super ACTUAL>> conditions
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/condition/VerboseCondition.java
VerboseCondition
buildVerboseDescription
class VerboseCondition<T> extends Condition<T> { private Function<T, String> objectUnderTestDescriptor; // needed to avoid an incorrect description when matches is run multiple times. private String description; /** * Creates a new <code>{@link VerboseCondition}</code> to have better control over the condition description when the condition fails thanks * to the {@code objectUnderTestDescriptor} function parameter. * <p> * When defining the {@code objectUnderTestDescriptor} function, you should take in consideration whether the condition is going to be used * with {@link AbstractAssert#is(Condition) is(Condition)} or {@link AbstractAssert#has(Condition) has(Condition)} since the start of the error message is different between the two. * <p> * Let's see how it works with an example that works well with {@link AbstractAssert#is(Condition) is(Condition)}: * <pre><code class='java'> Condition&lt;String&gt; shorterThan4 = VerboseCondition.verboseCondition(actual -&gt; actual.length() &lt; 4, // predicate description "shorter than 4", // value under test description transformation function s -&gt; String.format(" but length was %s", s.length(), s));</code></pre> * * If we execute: * <pre><code class='java'> assertThat("foooo").is(shorterThan4);</code></pre> * it fails with the following assertion error: * <pre><code class='text'> Expecting actual: * "foooo" * to be shorter than 4 but length was 5</code></pre> * <p> * Note that the beginning of the error message looks nice with {@link AbstractAssert#is(Condition) is(Condition)}, but not so much with {@link AbstractAssert#has(Condition) has(Condition)}: * <pre><code class='text'> Expecting actual: * "foooo" * to have shorter than 4 but length was 5</code></pre> * <p> * The {@code objectUnderTestDescriptor} must not be null, if you don't need one this probably means you can simply use {@link Condition#Condition(Predicate, String, Object...)} instead of a {@code VerboseCondition}. * * @param <T> the type of object the given condition accept. * @param predicate the Predicate that tests the value to test. * @param description describes the Condition verbal. * @param objectUnderTestDescriptor Function used to describe the value to test when the actual value does not match the predicate. must not be null. * @return the created {@code VerboseCondition}. * @throws NullPointerException if the predicate is {@code null}. * @throws NullPointerException if the objectUnderTestDescriptor is {@code null}. */ public static <T> VerboseCondition<T> verboseCondition(Predicate<T> predicate, String description, Function<T, String> objectUnderTestDescriptor) { return new VerboseCondition<>(predicate, description, objectUnderTestDescriptor); } private VerboseCondition(Predicate<T> predicate, String description, Function<T, String> objectUnderTestDescriptor) { super(predicate, description); this.description = description; this.objectUnderTestDescriptor = requireNonNull(objectUnderTestDescriptor, "The objectUnderTest descriptor function must not be null, if you don't need one, consider using the basic Condition(Predicate<T> predicate, String description, Object... args) constructor"); } @Override public boolean matches(T objectUnderTest) { boolean matches = super.matches(objectUnderTest); describedAs(buildVerboseDescription(objectUnderTest, matches)); return matches; } /** * Build the verbose condition description when applied with the actual values and the match result. * * @param objectUnderTest the object to test * @param matches the result of the match operation * @return the verbose condition description. */ protected String buildVerboseDescription(T objectUnderTest, boolean matches) {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(format("%s", description)); if (!matches) sb.append(objectUnderTestDescriptor.apply(objectUnderTest)); return sb.toString();
1,065
48
1,113
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient void <init>(Predicate<T>, java.lang.String, java.lang.Object[]) ,public void <init>(org.assertj.core.description.Description) ,public org.assertj.core.description.Description conditionDescriptionWithStatus(T) ,public Condition<T> describedAs(org.assertj.core.description.Description) ,public org.assertj.core.description.Description description() ,public boolean matches(T) ,public java.lang.String toString() <variables>org.assertj.core.description.Description description,private Predicate<T> predicate
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/configuration/ConfigurationProvider.java
ConfigurationProvider
loadRegisteredConfiguration
class ConfigurationProvider { public static final ConfigurationProvider CONFIGURATION_PROVIDER = new ConfigurationProvider(); private final Configuration configuration; private CompositeRepresentation compositeRepresentation; private ConfigurationProvider() { configuration = Services.get(Configuration.class, DEFAULT_CONFIGURATION); if (configuration != DEFAULT_CONFIGURATION) { configuration.applyAndDisplay(); } List<Representation> representations = Services.getAll(Representation.class); compositeRepresentation = new CompositeRepresentation(representations); if (!configuration.hasCustomRepresentation()) { // registered representations are only used if the configuration representation if (representations.size() == 1) { System.out.println(format("AssertJ has found one registered representation: %s, AssertJ will use it first and then fall back to standard representation if it returned a null representation of the value to display.", representations.get(0))); } else if (representations.size() > 1) { System.out.println(format("AssertJ has found %s registered representations, AssertJ will use them first and then fall back to standard representation if they returned a null representation of the value to display, the order (by highest priority first) of use will be: %s", representations.size(), compositeRepresentation.getAllRepresentationsOrderedByPriority())); } } else if (!representations.isEmpty()) { System.out.println(format("AssertJ has found these representations %s in the classpath but they won't be used as the loaded configuration has specified a custom representation which takes precedence over representations loaded with the java ServiceLoader: %s", representations, representation())); } } /** * Returns the {@link Representation} that AssertJ will use, which is taken first from: * <ul> * <li>the representation returned by a custom {@link Configuration} through {@link Configuration#representation()} but only if it is different from the {@link StandardRepresentation}</li> * <li>the {@link Representation} with highest priority loaded from the classpath by the {@link ServiceLoader}</li> * </ul> * If no custom representation was registered or overridden in a specific {@link Configuration}, the {@link StandardRepresentation} is used. * <p> * @return the default {@link Representation} that needs to be used within AssertJ * @since 2.9.0 / 3.9.0 * @since 3.22.0 support for registered multiple {@link Representation}s with priority. */ public Representation representation() { return configuration.hasCustomRepresentation() ? configuration.representation() : compositeRepresentation; } /** * Returns the configuration used in for all tests. * * @return the configuration applied for all tests. * @since 3.13.0 */ public Configuration configuration() { return configuration; } /** * Triggers loading any registered {@link Configuration}. * <p> * This method should be called before any user configuration changes to make sure these are not overridden by a registered {@link Configuration} later on. */ public static void loadRegisteredConfiguration() {<FILL_FUNCTION_BODY>} }
// does nothing but results in loading any registered Configuration as CONFIGURATION_PROVIDER is initialized
800
26
826
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/configuration/Services.java
Services
get
class Services { private Services() {} public static <SERVICE> SERVICE get(Class<SERVICE> serviceType, SERVICE defaultValue) {<FILL_FUNCTION_BODY>} public static <SERVICE> List<SERVICE> getAll(Class<SERVICE> serviceType) { Iterator<SERVICE> services = ServiceLoader.load(serviceType, Services.class.getClassLoader()).iterator(); return newArrayList(services); } }
Iterator<SERVICE> services = ServiceLoader.load(serviceType, Services.class.getClassLoader()).iterator(); SERVICE result = services.hasNext() ? services.next() : defaultValue; if (services.hasNext()) { result = defaultValue; System.err.println(format("Found multiple implementations for the service provider %s. Using the default: %s", serviceType, result.getClass())); } return result;
117
116
233
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/data/Index.java
Index
equals
class Index { public final int value; /** * Creates a new {@link Index}. * * @param value the value of the index. * @return the created {@code Index}. * @throws IllegalArgumentException if the given value is negative. */ public static Index atIndex(int value) { checkArgument(value >= 0, "The value of the index should not be negative"); return new Index(value); } private Index(int value) { this.value = value; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Integer.hashCode(value); } @Override public String toString() { return String.format("%s[value=%d]", getClass().getSimpleName(), value); } }
if (this == obj) return true; if (!(obj instanceof Index)) return false; Index other = (Index) obj; return value == other.value;
230
45
275
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/data/MapEntry.java
MapEntry
equals
class MapEntry<K, V> implements Map.Entry<K, V> { public final K key; public final V value; /** * Creates a new {@link MapEntry}. * * @param <K> the type of the key of this entry. * @param <V> the type of the value of this entry. * @param key the key of the entry to create. * @param value the value of the entry to create. * @return the created {@code MapEntry}. */ public static <K, V> MapEntry<K, V> entry(K key, V value) { return new MapEntry<>(key, value); } private MapEntry(K key, V value) { this.key = key; this.value = value; } @Override public boolean equals(Object object) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } @Override public String toString() { return CONFIGURATION_PROVIDER.representation().toStringOf(this); } @Override public K getKey() { return key; } @Override public V getValue() { return value; } /** * Always throws {@link UnsupportedOperationException} as this class represents an <i>immutable</i> map entry. * * @param value ignored * @return (Does not return) * @throws UnsupportedOperationException always */ @Override public V setValue(V value) { throw new UnsupportedOperationException(); } }
if (this == object) return true; if (!(object instanceof Map.Entry)) return false; Map.Entry<?, ?> that = (Map.Entry<?, ?>) object; return Objects.equals(key, that.getKey()) && Objects.equals(value, that.getValue());
440
77
517
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/data/Offset.java
Offset
offset
class Offset<T extends Number> { public final T value; /** * When |actual-expected|=offset and strict is true the assertThat(actual).isCloseTo(expected, offset); assertion will fail. */ public final boolean strict; /** * Creates a new {@link Offset} that let {@code isCloseTo} assertions pass when {@code |actual-expected| <= offset value}. * <p> * Example: * <pre><code class='java'> // assertions succeed * assertThat(8.1).isCloseTo(8.0, offset(0.2)); * assertThat(8.1).isCloseTo(8.0, offset(0.1)); * * // assertion fails * assertThat(8.1).isCloseTo(8.0, offset(0.01));</code></pre> * * @param <T> the type of value of the {@link Offset}. * @param value the value of the offset. * @return the created {@code Offset}. * @throws NullPointerException if the given value is {@code null}. * @throws IllegalArgumentException if the given value is negative. */ public static <T extends Number> Offset<T> offset(T value) {<FILL_FUNCTION_BODY>} /** * Creates a new strict {@link Offset} that let {@code isCloseTo} assertion pass when {@code |actual-expected| < offset value}. * <p> * Examples: * <pre><code class='java'> // assertion succeeds * assertThat(8.1).isCloseTo(8.0, offset(0.2)); * * // assertions fail * assertThat(8.1).isCloseTo(8.0, offset(0.1)); * assertThat(8.1).isCloseTo(8.0, offset(0.01));</code></pre> * * @param <T> the type of value of the {@link Offset}. * @param value the value of the offset. * @return the created {@code Offset}. * @throws NullPointerException if the given value is {@code null}. * @throws IllegalArgumentException if the given value is negative. */ public static <T extends Number> Offset<T> strictOffset(T value) { requireNonNull(value); checkArgument(value.doubleValue() > 0d, "A strict offset value should be greater than zero"); return new Offset<>(value, true); } private Offset(T value, boolean strict) { this.value = value; this.strict = strict; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Offset)) return false; Offset<?> other = (Offset<?>) obj; return strict == other.strict && Objects.equals(value, other.value); } @Override public int hashCode() { return hash(value, strict); } @Override public String toString() { return format("%s%s[value=%s]", strict ? "strict " : "", getClass().getSimpleName(), value); } }
requireNonNull(value); checkArgument(value.doubleValue() >= 0d, "An offset value should be greater than or equal to zero"); return new Offset<>(value, false);
817
50
867
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/data/Percentage.java
Percentage
equals
class Percentage { public final double value; /** * Creates a new {@link org.assertj.core.data.Percentage}. * * @param value the value of the percentage. * @return the created {@code Percentage}. * @throws NullPointerException if the given value is {@code null}. * @throws IllegalArgumentException if the given value is negative. */ public static Percentage withPercentage(double value) { checkArgument(value >= 0, "The percentage value <%s> should be greater than or equal to zero", value); return new Percentage(value); } private Percentage(double value) { this.value = value; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Double.hashCode(value); } @Override public String toString() { return noFractionalPart() ? format("%s%%", (int) value) : format("%s%%", value); } private boolean noFractionalPart() { return (value % 1) == 0; } }
if (this == obj) return true; if (!(obj instanceof Percentage)) return false; Percentage other = (Percentage) obj; return Double.compare(value, other.value) == 0;
309
58
367
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/data/TemporalUnitOffset.java
TemporalUnitOffset
equals
class TemporalUnitOffset implements TemporalOffset<Temporal> { protected final TemporalUnit unit; protected final long value; /** * Creates a new temporal offset for a given temporal unit. * @param value the value of the offset. * @param unit temporal unit of the offset. * @throws NullPointerException if the given unit is {@code null}. * @throws IllegalArgumentException if the given value is negative. */ public TemporalUnitOffset(long value, TemporalUnit unit) { requireNonNull(unit); checkThatValueIsPositive(value); this.value = value; this.unit = unit; } private static void checkThatValueIsPositive(long value) { checkArgument(value >= 0, "The value of the offset should be greater than zero"); } /** * {@inheritDoc} */ @Override public String getBeyondOffsetDifferenceDescription(Temporal temporal1, Temporal temporal2) { try { return format("%s %s but difference was %s %s", value, unit, getDifference(temporal1, temporal2), unit); } catch (@SuppressWarnings("unused") ArithmeticException e) { return format("%s %s but difference was %s", value, unit, getAbsoluteDuration(temporal1, temporal2)); } } /** * Returns absolute value of the difference according to time unit. * * @param temporal1 the first {@link Temporal} * @param temporal2 the second {@link Temporal} * @return absolute value of the difference according to time unit. */ protected long getDifference(Temporal temporal1, Temporal temporal2) { return abs(unit.between(temporal1, temporal2)); } /** * Returns absolute value of the difference as Duration. * * @param temporal1 the first {@link Temporal} * @param temporal2 the second {@link Temporal} * @return absolute value of the difference as Duration. */ protected Duration getAbsoluteDuration(Temporal temporal1, Temporal temporal2) { return Duration.between(temporal1, temporal2).abs(); } public TemporalUnit getUnit() { return unit; } @Override public int hashCode() { return Objects.hash(value); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} }
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TemporalUnitOffset other = (TemporalUnitOffset) obj; return value == other.value;
647
69
716
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/data/TemporalUnitWithinOffset.java
TemporalUnitWithinOffset
isBeyondOffset
class TemporalUnitWithinOffset extends TemporalUnitOffset { public TemporalUnitWithinOffset(long value, TemporalUnit unit) { super(value, unit); } /** * Checks if difference between temporal values is less then or equal to offset. * @param temporal1 first temporal value to be validated against second temporal value. * @param temporal2 second temporal value. * @return true if difference between temporal values is more than offset value. */ @Override public boolean isBeyondOffset(Temporal temporal1, Temporal temporal2) {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public String getBeyondOffsetDifferenceDescription(Temporal temporal1, Temporal temporal2) { return "within " + super.getBeyondOffsetDifferenceDescription(temporal1, temporal2); } }
try { return getDifference(temporal1, temporal2) > value; } catch (@SuppressWarnings("unused") ArithmeticException e) { return getAbsoluteDuration(temporal1, temporal2).compareTo(Duration.of(value, unit)) > 0; }
235
78
313
<methods>public void <init>(long, java.time.temporal.TemporalUnit) ,public boolean equals(java.lang.Object) ,public java.lang.String getBeyondOffsetDifferenceDescription(java.time.temporal.Temporal, java.time.temporal.Temporal) ,public java.time.temporal.TemporalUnit getUnit() ,public int hashCode() <variables>protected final non-sealed java.time.temporal.TemporalUnit unit,protected final non-sealed long value
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/description/Description.java
Description
mostRelevantDescription
class Description { /** * @return the value of this description. */ public abstract String value(); @Override public String toString() { return value(); } public static Description emptyIfNull(Description description) { return description == null ? emptyDescription() : description; } public static String mostRelevantDescription(Description existingDescription, String newDescription) {<FILL_FUNCTION_BODY>} }
boolean isDescriptionSet = existingDescription != null && !isNullOrEmpty(existingDescription.value()); return isDescriptionSet ? existingDescription.value() : newDescription;
116
44
160
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/description/JoinDescription.java
JoinDescription
appendIndentedValueTo
class JoinDescription extends Description { private static final int DEFAULT_INDENTATION = 3; private static final String LINE_SEPARATOR = System.lineSeparator(); /** * Delimiter string between {@code descriptions}. */ private static final String DELIMITER = ',' + LINE_SEPARATOR; @VisibleForTesting final Collection<Description> descriptions; @VisibleForTesting final String prefix; @VisibleForTesting final String suffix; /** * Creates a new <code>{@link JoinDescription}</code>. * * @param prefix The beginning part of this description. * @param suffix The ending part of this description. * @param descriptions The descriptions to combine. * * @throws NullPointerException if the given prefix is {@code null}. * @throws NullPointerException if the given suffix is {@code null}. * @throws NullPointerException if the given descriptions contains {@code null} elements or descriptions itself is * {@code null}. */ public JoinDescription(String prefix, String suffix, Collection<Description> descriptions) { this.prefix = requireNonNull(prefix); this.suffix = requireNonNull(suffix); this.descriptions = requireNonNull(descriptions).stream() .map(JoinDescription::checkNotNull) .collect(toList()); } private static Description checkNotNull(Description description) { requireNonNull(description, "The descriptions should not contain null elements"); return description; } @Override public String value() { IndentedAppendable indentableBuilder = new IndentedAppendable(new StringBuilder()); return appendIndentedValueTo(indentableBuilder).toString(); } @Override public int hashCode() { return HASH_CODE_PRIME + hashCodeFor(prefix) + hashCodeFor(suffix) + hashCodeFor(descriptions); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof JoinDescription)) return false; JoinDescription that = (JoinDescription) o; return deepEquals(descriptions, that.descriptions) && deepEquals(prefix, that.prefix) && deepEquals(suffix, that.suffix); } private IndentedAppendable appendIndentedValueTo(IndentedAppendable indentableBuilder) {<FILL_FUNCTION_BODY>} /** * The wrapper for {@code StringBuilder} aware of indentation. */ private static class IndentedAppendable implements Appendable { private final StringBuilder stringBuilder; private int currentIndentation; IndentedAppendable(StringBuilder stringBuilder) { this.stringBuilder = stringBuilder; this.currentIndentation = 0; } @Override public IndentedAppendable append(CharSequence charSequence) { stringBuilder.append(charSequence); return this; } @Override public IndentedAppendable append(CharSequence charSequence, int start, int end) { stringBuilder.append(charSequence, start, end); return this; } @Override public IndentedAppendable append(char c) { stringBuilder.append(c); return this; } /** * Adjusts the indentation size by {@code indentation}. * * @param indentation The indentation adjustment. * * @return a this instance. */ IndentedAppendable changeIndentationBy(int indentation) { this.currentIndentation += indentation; return this; } /** * Appends the indentation according to current size. * * @return a this instance. */ IndentedAppendable indent() { for (int i = 0; i < currentIndentation; i++) { stringBuilder.append(' '); } return this; } /** * Shortcut method from {@link #changeIndentationBy(int)} and {@link #indent()} * * @param indentation The indentation adjustment. * * @return a this instance. */ IndentedAppendable indentBy(int indentation) { return changeIndentationBy(indentation).indent(); } @Override public String toString() { return stringBuilder.toString(); } } }
// indent and begin adding the current description starting with prefix indentableBuilder.indent().append(prefix); // special case where there is no descriptions if (descriptions.isEmpty()) return indentableBuilder.append(suffix); // no line sep // descriptions section indentableBuilder.append(LINE_SEPARATOR); // increase indention to write nested conditions indentableBuilder.changeIndentationBy(DEFAULT_INDENTATION); Iterator<? extends Description> it = descriptions.iterator(); while (it.hasNext()) { Description description = it.next(); if (description instanceof JoinDescription) { JoinDescription joinDescription = (JoinDescription) description; joinDescription.appendIndentedValueTo(indentableBuilder); } else { // we indent according to the current indentation and then we append the value indentableBuilder.indent().append(description.value()); } // avoid the trailing delimiter if (it.hasNext()) indentableBuilder.append(DELIMITER); } // suffix section return indentableBuilder.append(LINE_SEPARATOR) .indentBy(-DEFAULT_INDENTATION) // back indention to align with prefix .append(suffix);
1,130
314
1,444
<methods>public non-sealed void <init>() ,public static org.assertj.core.description.Description emptyIfNull(org.assertj.core.description.Description) ,public static java.lang.String mostRelevantDescription(org.assertj.core.description.Description, java.lang.String) ,public java.lang.String toString() ,public abstract java.lang.String value() <variables>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/description/LazyTextDescription.java
LazyTextDescription
value
class LazyTextDescription extends Description { private Supplier<String> descriptionSupplier; public LazyTextDescription(Supplier<String> descriptionSupplier) { this.descriptionSupplier = descriptionSupplier; } @Override public String value() {<FILL_FUNCTION_BODY>} }
checkState(descriptionSupplier != null, "the descriptionSupplier should not be null"); return descriptionSupplier.get();
82
34
116
<methods>public non-sealed void <init>() ,public static org.assertj.core.description.Description emptyIfNull(org.assertj.core.description.Description) ,public static java.lang.String mostRelevantDescription(org.assertj.core.description.Description, java.lang.String) ,public java.lang.String toString() ,public abstract java.lang.String value() <variables>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/description/TextDescription.java
TextDescription
equals
class TextDescription extends Description { @VisibleForTesting final String value; final Object[] args; /** * Creates a new <code>{@link TextDescription}</code>. * * @param value the value of this description. * @param args the replacements parameters of this description. * @throws NullPointerException if the given value is {@code null}. */ public TextDescription(String value, Object... args) { this.value = value == null ? "" : value; this.args = Arrays.isNullOrEmpty(args) ? null : args.clone(); } @Override public String value() { return formatIfArgs(value, args); } @Override public int hashCode() { return Objects.hash(value, args); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} }
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TextDescription other = (TextDescription) obj; return deepEquals(value, other.value) && deepEquals(args, other.args);
240
76
316
<methods>public non-sealed void <init>() ,public static org.assertj.core.description.Description emptyIfNull(org.assertj.core.description.Description) ,public static java.lang.String mostRelevantDescription(org.assertj.core.description.Description, java.lang.String) ,public java.lang.String toString() ,public abstract java.lang.String value() <variables>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/AbstractShouldHaveTextContent.java
AbstractShouldHaveTextContent
create
class AbstractShouldHaveTextContent extends BasicErrorMessageFactory { protected String diffs; public AbstractShouldHaveTextContent(String format, Object... arguments) { super(format, arguments); } @Override public String create(Description d, Representation representation) {<FILL_FUNCTION_BODY>} protected static String diffsAsString(List<Delta<String>> diffsList) { return diffsList.stream().map(Delta::toString).collect(joining(System.lineSeparator())); } }
// we append diffs here as we can't add in super constructor call, see why below. // // case 1 - append diffs to String passed in super : // super("file:<%s> and file:<%s> do not have equal content:" + diffs, actual, expected); // this leads to a MissingFormatArgumentException if diffs contains a format specifier (like %s) because the String // will finally be evaluated with String.format // // case 2 - add as format arg to the String passed in super : // super("file:<%s> and file:<%s> do not have equal content:"actual, expected, diffs); // this is better than case 1 but the diffs String will be quoted before the class to String.format as all String in // AssertJ error message. This is not what we want. // // The solution is to keep diffs as an attribute and append it after String.format has been applied on the error // message. return super.create(d, representation) + diffs;
135
260
395
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/AssertJMultipleFailuresError.java
AssertJMultipleFailuresError
getMessage
class AssertJMultipleFailuresError extends MultipleFailuresError { private static final long serialVersionUID = 1L; private static final String EOL = System.getProperty("line.separator"); private static final String ERROR_SEPARATOR = EOL + "-- failure %d --"; private String heading; public AssertJMultipleFailuresError(String heading, List<? extends Throwable> failures) { super(heading, failures); this.heading = heading; } @Override public String getMessage() {<FILL_FUNCTION_BODY>} private String errorSeparator(int errorNumber) { return format(ERROR_SEPARATOR, errorNumber); } private boolean hasDescription(String message) { return message.startsWith("["); } private static boolean isBlank(String str) { return str == null || str.trim().length() == 0; } private static String pluralize(int count, String singular, String plural) { return count == 1 ? singular : plural; } private static String nullSafeMessage(Throwable failure) { return isBlank(failure.getMessage()) ? "<no message> in " + failure.getClass().getName() : failure.getMessage(); } }
List<Throwable> failures = getFailures(); int failureCount = failures.size(); if (failureCount == 0) return super.getMessage(); heading = isBlank(heading) ? "Multiple Failures" : heading.trim(); StringBuilder builder = new StringBuilder(EOL).append(heading) .append(" (") .append(failureCount).append(" ") .append(pluralize(failureCount, "failure", "failures")) .append(")"); List<Throwable> failuresWithLineNumbers = addLineNumberToErrorMessages(failures); for (int i = 0; i < failureCount; i++) { builder.append(errorSeparator(i + 1)); String message = nullSafeMessage(failuresWithLineNumbers.get(i)); // when we have a description, we add a line before for readability if (hasDescription(message)) builder.append(EOL); builder.append(message); } return builder.toString();
323
262
585
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/AssertionErrorCreator.java
AssertionErrorCreator
assertionFailedError
class AssertionErrorCreator { private static final Class<?>[] MSG_ARG_TYPES_FOR_ASSERTION_FAILED_ERROR = array(String.class, Object.class, Object.class); private static final Class<?>[] MSG_ARG_TYPES_FOR_COMPARISON_FAILURE = array(String.class, String.class, String.class); private static final Class<?>[] MULTIPLE_FAILURES_ERROR_ARGUMENT_TYPES = array(String.class, List.class); @VisibleForTesting ConstructorInvoker constructorInvoker; public AssertionErrorCreator() { this(new ConstructorInvoker()); } public AssertionErrorCreator(ConstructorInvoker constructorInvoker) { this.constructorInvoker = constructorInvoker; } // single assertion error public AssertionError assertionError(String message, Object actual, Object expected, Representation representation) { // @format:off return assertionFailedError(message, actual,expected) .orElse(comparisonFailure(message, actual, expected, representation) .orElse(assertionError(message))); // @format:on } private Optional<AssertionError> assertionFailedError(String message, Object actual, Object expected) {<FILL_FUNCTION_BODY>} private Optional<AssertionError> comparisonFailure(String message, Object actual, Object expected, Representation representation) { try { UnambiguousRepresentation unambiguousRepresentation = new UnambiguousRepresentation(representation, actual, expected); Object o = constructorInvoker.newInstance("org.junit.ComparisonFailure", MSG_ARG_TYPES_FOR_COMPARISON_FAILURE, message, unambiguousRepresentation.getExpected(), unambiguousRepresentation.getActual()); if (o instanceof AssertionError) return Optional.of((AssertionError) o); } catch (@SuppressWarnings("unused") Throwable ignored) {} return Optional.empty(); } public AssertionError assertionError(String message) { return new AssertionError(message); } // multiple assertions error public AssertionError multipleSoftAssertionsError(List<? extends Throwable> errors) { Optional<AssertionError> multipleFailuresError = tryBuildingMultipleFailuresError(errors); return multipleFailuresError.orElse(new SoftAssertionError(describeErrors(errors))); } public AssertionError multipleAssertionsError(Description description, List<? extends AssertionError> errors) { String heading = headingFrom(description); Optional<AssertionError> multipleFailuresError = tryBuildingMultipleFailuresError(heading, errors); return multipleFailuresError.orElse(new MultipleAssertionsError(description, errors)); } public void tryThrowingMultipleFailuresError(List<? extends Throwable> errorsCollected) { tryBuildingMultipleFailuresError(errorsCollected).ifPresent(AssertionErrorCreator::throwError); } // syntactic sugar private static void throwError(AssertionError error) { throw error; } private static String headingFrom(Description description) { return description == null ? null : DescriptionFormatter.instance().format(description); } private Optional<AssertionError> tryBuildingMultipleFailuresError(List<? extends Throwable> errorsCollected) { return tryBuildingMultipleFailuresError(null, errorsCollected); } private Optional<AssertionError> tryBuildingMultipleFailuresError(String heading, List<? extends Throwable> errorsCollected) { if (errorsCollected.isEmpty()) return Optional.empty(); try { Object[] constructorArguments = array(heading, errorsCollected); Object multipleFailuresError = constructorInvoker.newInstance("org.opentest4j.MultipleFailuresError", MULTIPLE_FAILURES_ERROR_ARGUMENT_TYPES, constructorArguments); if (multipleFailuresError instanceof AssertionError) { // means that we were able to build a MultipleFailuresError List<Throwable> failures = extractFailuresOf(multipleFailuresError); // we switch to AssertJMultipleFailuresError in order to control the formatting of the error message. // we use reflection to avoid making opentest4j a required dependency AssertionError assertionError = (AssertionError) constructorInvoker.newInstance("org.assertj.core.error.AssertJMultipleFailuresError", MULTIPLE_FAILURES_ERROR_ARGUMENT_TYPES, array(heading, failures)); Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError); return Optional.of(assertionError); } } catch (@SuppressWarnings("unused") Exception e) { // do nothing, MultipleFailuresError was not in the classpath } return Optional.empty(); } @SuppressWarnings("unchecked") private static List<Throwable> extractFailuresOf(Object multipleFailuresError) { return (List<Throwable>) PropertyOrFieldSupport.EXTRACTION.getValueOf("failures", multipleFailuresError); } }
try { Object o = constructorInvoker.newInstance("org.opentest4j.AssertionFailedError", MSG_ARG_TYPES_FOR_ASSERTION_FAILED_ERROR, message, expected, actual); if (o instanceof AssertionError) return Optional.of((AssertionError) o); } catch (@SuppressWarnings("unused") Throwable ignored) {} return Optional.empty();
1,355
117
1,472
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/AssertionErrorMessagesAggregator.java
AssertionErrorMessagesAggregator
aggregateErrorMessages
class AssertionErrorMessagesAggregator { public static String aggregateErrorMessages(List<String> errors) {<FILL_FUNCTION_BODY>} private static void countAssertions(List<String> errors, StringBuilder msg) { int size = errors.size(); if (size == 1) { msg.append("assertion"); } else { msg.append(size).append(" assertions"); } } }
StringBuilder msg = new StringBuilder("%nThe following "); countAssertions(errors, msg); msg.append(" failed:%n"); for (int i = 0; i < errors.size(); i++) { msg.append(i + 1).append(") ").append(errors.get(i)).append("%n"); } return MessageFormatter.instance().format(null, null, msg.toString());
113
107
220
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/BasicErrorMessageFactory.java
UnquotedString
equals
class UnquotedString implements CharSequence { private final String string; private UnquotedString(String string) { this.string = requireNonNull(string, "string is mandatory"); } @Override public int length() { return string.length(); } @Override public char charAt(int index) { return string.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return string.subSequence(start, end); } @Override public String toString() { return string; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((string == null) ? 0 : string.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UnquotedString other = (UnquotedString) obj; return Objects.equals(string, other.string); } } /** * Creates a new <code>{@link BasicErrorMessageFactory}</code>. * * @param format the format string. * @param arguments arguments referenced by the format specifiers in the format string. */ public BasicErrorMessageFactory(String format, Object... arguments) { this.format = format; this.arguments = arguments; } /** {@inheritDoc} */ @Override public String create(Description d, Representation representation) { return formatter.format(d, representation, format, arguments); } /** {@inheritDoc} */ @Override public String create(Description d) { return formatter.format(d, CONFIGURATION_PROVIDER.representation(), format, arguments); } /** {@inheritDoc} */ @Override public String create() { return formatter.format(emptyDescription(), CONFIGURATION_PROVIDER.representation(), format, arguments); } /** * Return a string who will be unquoted in message format (without '') * * @param string the string who will be unquoted. * @return an unquoted string in message format. */ protected static CharSequence unquotedString(String string) { return new UnquotedString(string); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BasicErrorMessageFactory other = (BasicErrorMessageFactory) obj; if (!deepEquals(format, other.format)) return false; // because it does not manage array recursively, don't use : Arrays.equals(arguments, other.arguments); // example if arguments[1] and other.arguments[1] are logically same arrays but not same object, it will return // false return deepEquals(arguments, other.arguments);
664
155
819
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ClassModifierShouldBe.java
ClassModifierShouldBe
modifiers
class ClassModifierShouldBe extends BasicErrorMessageFactory { private static final String PACKAGE_PRIVATE = "package-private"; private ClassModifierShouldBe(Class<?> actual, boolean positive, String modifier) { super("%nExpecting actual:%n %s%n" + (positive ? "to" : "not to") + " be a %s class but was %s.", actual, modifier, modifiers(actual)); } /** * Creates a new instance for a positive check of the {@code final} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeFinal(Class<?> actual) { return new ClassModifierShouldBe(actual, true, Modifier.toString(Modifier.FINAL)); } /** * Creates a new instance for a negative check of the {@code final} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotBeFinal(Class<?> actual) { return new ClassModifierShouldBe(actual, false, Modifier.toString(Modifier.FINAL)); } /** * Creates a new instance for a positive check of the {@code public} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBePublic(Class<?> actual) { return new ClassModifierShouldBe(actual, true, Modifier.toString(Modifier.PUBLIC)); } /** * Creates a new instance for a positive check of the {@code protected} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeProtected(Class<?> actual) { return new ClassModifierShouldBe(actual, true, Modifier.toString(Modifier.PROTECTED)); } /** * Creates a new instance for a positive check of the {@code package-private} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBePackagePrivate(Class<?> actual) { return new ClassModifierShouldBe(actual, true, PACKAGE_PRIVATE); } /** * Creates a new instance for a positive check of the {@code private} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBePrivate(Class<?> actual) { return new ClassModifierShouldBe(actual, true, Modifier.toString(Modifier.PRIVATE)); } /** * Creates a new instance for a positive check of the {@code static} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeStatic(Class<?> actual) { return new ClassModifierShouldBe(actual, true, Modifier.toString(Modifier.STATIC)); } /** * Creates a new instance for a negative check of the {@code static} modifier. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotBeStatic(Class<?> actual) { return new ClassModifierShouldBe(actual, false, Modifier.toString(Modifier.STATIC)); } private static String modifiers(Class<?> actual) {<FILL_FUNCTION_BODY>} }
int modifiers = actual.getModifiers(); boolean isPackagePrivate = !isPublic(modifiers) && !isProtected(modifiers) && !isPrivate(modifiers); String modifiersDescription = Modifier.toString(modifiers); StringJoiner sj = new StringJoiner(" "); if (isPackagePrivate) { sj.add(PACKAGE_PRIVATE); } if (!modifiersDescription.isEmpty()) { sj.add(modifiersDescription); } return sj.toString();
987
138
1,125
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ConstructorInvoker.java
ConstructorInvoker
newInstance
class ConstructorInvoker { public Object newInstance(String className, Class<?>[] parameterTypes, Object... parameterValues) throws Exception {<FILL_FUNCTION_BODY>} }
Class<?> targetType = Class.forName(className); Constructor<?> constructor = targetType.getConstructor(parameterTypes); return constructor.newInstance(parameterValues);
48
48
96
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/DescriptionFormatter.java
DescriptionFormatter
format
class DescriptionFormatter { private static final DescriptionFormatter INSTANCE = new DescriptionFormatter(); /** * Returns the singleton instance of this class. * @return the singleton instance of this class. */ public static DescriptionFormatter instance() { return INSTANCE; } @VisibleForTesting DescriptionFormatter() {} /** * Formats the given <code>{@link Description}</code> by surrounding its text value with square brackets and adding a space at * the end. * @param d the description to format. It can be {@code null}. * @return the formatted description, or an empty {@code String} if the {@code Description} is {@code null}. */ public String format(Description d) {<FILL_FUNCTION_BODY>} }
String s = (d != null) ? d.value() : null; if (isNullOrEmpty(s)) return ""; return String.format("[%s] ", s);
207
49
256
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ElementsShouldMatch.java
ElementsShouldMatch
elementsShouldMatch
class ElementsShouldMatch extends BasicErrorMessageFactory { private static final String SINGLE_NON_MATCHING_ELEMENT = "%nExpecting all elements of:%n %s%nto match %s predicate but this element did not:%n %s"; private static final String MULTIPLE_NON_MATCHING_ELEMENT = "%nExpecting all elements of:%n %s%nto match %s predicate but these elements did not:%n %s"; public static <T> ErrorMessageFactory elementsShouldMatch(Object actual, T elementsNotMatchingPredicate, PredicateDescription predicateDescription) {<FILL_FUNCTION_BODY>} private ElementsShouldMatch(Object actual, Object notMatching, PredicateDescription predicateDescription) { super(SINGLE_NON_MATCHING_ELEMENT, actual, predicateDescription, notMatching); } private ElementsShouldMatch(Object actual, Iterable<?> notMatching, PredicateDescription predicateDescription) { super(MULTIPLE_NON_MATCHING_ELEMENT, actual, predicateDescription, notMatching); } }
return elementsNotMatchingPredicate instanceof Iterable ? new ElementsShouldMatch(actual, (Iterable<?>) elementsNotMatchingPredicate, predicateDescription) : new ElementsShouldMatch(actual, elementsNotMatchingPredicate, predicateDescription);
284
64
348
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ElementsShouldSatisfy.java
ElementsShouldSatisfy
elementsShouldSatisfy
class ElementsShouldSatisfy extends BasicErrorMessageFactory { public static ErrorMessageFactory elementsShouldSatisfyAny(Object actual, List<UnsatisfiedRequirement> elementsNotSatisfyingRequirements, AssertionInfo info) { return new ElementsShouldSatisfy("%n" + "Expecting any element of:%n" + " %s%n" + "to satisfy the given assertions requirements but none did:%n%n", actual, elementsNotSatisfyingRequirements, info); } public static ErrorMessageFactory elementsShouldSatisfy(Object actual, List<UnsatisfiedRequirement> elementsNotSatisfyingRestrictions, AssertionInfo info) {<FILL_FUNCTION_BODY>} public static ErrorMessageFactory elementsShouldSatisfyExactly(Object actual, Map<Integer, UnsatisfiedRequirement> unsatisfiedRequirements, AssertionInfo info) { return new ElementsShouldSatisfy("%n" + "Expecting each element of:%n" + " %s%n" + "to satisfy the requirements at its index, but these elements did not:%n%n", actual, unsatisfiedRequirements, info); } private ElementsShouldSatisfy(String message, Object actual, List<UnsatisfiedRequirement> elementsNotSatisfyingRequirements, AssertionInfo info) { super(message + describeErrors(elementsNotSatisfyingRequirements, info), actual); } private ElementsShouldSatisfy(String message, Object actual, Map<Integer, UnsatisfiedRequirement> unsatisfiedRequirements, AssertionInfo info) { super(message + describeErrors(unsatisfiedRequirements, info), actual); } private static String describeErrors(Map<Integer, UnsatisfiedRequirement> unsatisfiedRequirements, AssertionInfo info) { return escapePercent(unsatisfiedRequirements.entrySet().stream() .map(requirementAtIndex -> describe(requirementAtIndex, info)) .collect(joining(format("%n%n")))); } private static String describe(Entry<Integer, UnsatisfiedRequirement> requirementsAtIndex, AssertionInfo info) { int index = requirementsAtIndex.getKey(); UnsatisfiedRequirement unsatisfiedRequirement = requirementsAtIndex.getValue(); return unsatisfiedRequirement.describe(index, info); } private static String describeErrors(List<UnsatisfiedRequirement> elementsNotSatisfyingRequirements, AssertionInfo info) { return escapePercent(elementsNotSatisfyingRequirements.stream() .map(unsatisfiedRequirement -> unsatisfiedRequirement.describe(info)) .collect(joining(format("%n%n")))); } public static UnsatisfiedRequirement unsatisfiedRequirement(Object elementNotSatisfyingRequirements, String errorMessage) { return new UnsatisfiedRequirement(elementNotSatisfyingRequirements, errorMessage); } }
return new ElementsShouldSatisfy("%n" + "Expecting all elements of:%n" + " %s%n" + "to satisfy given requirements, but these elements did not:%n%n", actual, elementsNotSatisfyingRestrictions, info);
754
75
829
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/GroupTypeDescription.java
GroupTypeDescription
getGroupTypeDescription
class GroupTypeDescription { private static final int SPLITERATORS_CLASS_STACK_TRACE_NUM = 5; private String groupTypeName; private String elementTypeName; public GroupTypeDescription(String groupTypeName, String elementTypeName) { this.groupTypeName = groupTypeName; this.elementTypeName = elementTypeName; } public String getElementTypeName() { return elementTypeName; } public String getGroupTypeName() { return groupTypeName; } /** * Creates a new <code>{@link GroupTypeDescription}</code> for a group of elements. * * @param actual the group of elements. * @return the created GroupTypeDescription object */ public static GroupTypeDescription getGroupTypeDescription(Object actual) { return getGroupTypeDescription(actual.getClass()); } /** * Creates a new <code>{@link GroupTypeDescription}</code> for a group of elements. * * @param clazz the class for the group of elements. * @return the created GroupTypeDescription object */ public static GroupTypeDescription getGroupTypeDescription(Class<?> clazz) {<FILL_FUNCTION_BODY>} }
if (Thread.currentThread().getStackTrace()[SPLITERATORS_CLASS_STACK_TRACE_NUM].getClassName().contains("Spliterators")) return new GroupTypeDescription("spliterator characteristics", "characteristics"); if (Map.class.isAssignableFrom(clazz)) return new GroupTypeDescription("map", "map entries"); if (clazz.isArray()) return new GroupTypeDescription(clazz.getSimpleName(), clazz.getComponentType().getSimpleName().toLowerCase() + "(s)"); return new GroupTypeDescription(clazz.getSimpleName(), "element(s)");
323
161
484
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/MessageFormatter.java
MessageFormatter
format
class MessageFormatter { private static final MessageFormatter INSTANCE = new MessageFormatter(); public static MessageFormatter instance() { return INSTANCE; } @VisibleForTesting DescriptionFormatter descriptionFormatter = DescriptionFormatter.instance(); @VisibleForTesting MessageFormatter() {} /** * Interprets a printf-style format {@code String} for failed assertion messages. It is similar to * <code>{@link String#format(String, Object...)}</code>, except for: * <ol> * <li>the value of the given <code>{@link Description}</code> is used as the first argument referenced in the format * string</li> * <li>each of the arguments in the given array is converted to a {@code String} by invoking * <code>{@link org.assertj.core.presentation.Representation#toStringOf(Object)}</code>. * </ol> * * @param d the description of the failed assertion, may be {@code null}. * @param p the Representation used * @param format the format string. * @param args arguments referenced by the format specifiers in the format string. * @throws NullPointerException if the format string is {@code null}. * @return A formatted {@code String}. */ public String format(Description d, Representation p, String format, Object... args) { requireNonNull(format); requireNonNull(args); return descriptionFormatter.format(d) + formatIfArgs(format, format(p, args)); } private Object[] format(Representation p, Object[] args) {<FILL_FUNCTION_BODY>} private String asText(Representation p, Object o) { if (o instanceof AbstractComparisonStrategy) { return ((AbstractComparisonStrategy) o).asText(); } return p.toStringOf(o); } }
int argCount = args.length; String[] formatted = new String[argCount]; for (int i = 0; i < argCount; i++) { formatted[i] = asText(p, args[i]); } return formatted;
493
67
560
<no_super_class>
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/OptionalDoubleShouldHaveValueCloseToPercentage.java
OptionalDoubleShouldHaveValueCloseToPercentage
shouldHaveValueCloseToPercentage
class OptionalDoubleShouldHaveValueCloseToPercentage extends BasicErrorMessageFactory { private OptionalDoubleShouldHaveValueCloseToPercentage(double expected) { super("%nExpecting an OptionalDouble with value:%n" + " %s%n" + "but was empty.", expected); } private OptionalDoubleShouldHaveValueCloseToPercentage(OptionalDouble actual, double expected, Percentage percentage, double expectedPercentage) { super("%nExpecting actual:%n" + " %s%n" + "to be close to:%n" + " %s%n" + "by less than %s but difference was %s%%.%n" + "(a difference of exactly %s being considered valid)", actual, expected, percentage, expectedPercentage, percentage); } /** * Indicates that the provided {@link java.util.OptionalDouble} is empty so it doesn't have the expected value. * * @param expectedValue the value we expect to be in an {@link java.util.OptionalDouble}. * @return a error message factory. */ public static OptionalDoubleShouldHaveValueCloseToPercentage shouldHaveValueCloseToPercentage(double expectedValue) { return new OptionalDoubleShouldHaveValueCloseToPercentage(expectedValue); } /** * Indicates that the provided {@link java.util.OptionalDouble} has a value, but it is not within the given positive * percentage. * * @param optional the {@link java.util.OptionalDouble} which has a value * @param expectedValue the value we expect to be in the provided {@link java.util.OptionalDouble} * @param percentage the given positive percentage * @param difference the effective distance between actual and expected * @return an error message factory */ public static OptionalDoubleShouldHaveValueCloseToPercentage shouldHaveValueCloseToPercentage(OptionalDouble optional, double expectedValue, Percentage percentage, double difference) {<FILL_FUNCTION_BODY>} }
double actualPercentage = difference / expectedValue * 100d; return new OptionalDoubleShouldHaveValueCloseToPercentage(optional, expectedValue, percentage, actualPercentage);
521
49
570
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/OptionalShouldContain.java
OptionalShouldContain
shouldContainSame
class OptionalShouldContain extends BasicErrorMessageFactory { private static final String EXPECTING_TO_CONTAIN = "%nExpecting actual:%n %s%nto contain:%n %s%nbut did not."; private static final String EXPECTING_TO_CONTAIN_SAME = "%nExpecting actual:%n %s%nto contain the instance (i.e. compared with ==):%n %s%nbut did not."; private OptionalShouldContain(String message, Object actual, Object expected) { super(message, actual, expected); } private OptionalShouldContain(Object expected) { super("%nExpecting Optional to contain:%n %s%nbut was empty.", expected); } /** * Indicates that the provided {@link java.util.Optional} does not contain the provided argument. * * @param optional the {@link java.util.Optional} which contains a value. * @param expectedValue the value we expect to be in the provided {@link java.util.Optional}. * @param <VALUE> the type of the value contained in the {@link java.util.Optional}. * @return a error message factory */ public static <VALUE> OptionalShouldContain shouldContain(Optional<VALUE> optional, VALUE expectedValue) { return optional.isPresent() ? new OptionalShouldContain(EXPECTING_TO_CONTAIN, optional, expectedValue) : shouldContain(expectedValue); } /** * Indicates that the provided {@link java.util.OptionalDouble} does not contain the provided argument. * * @param optional the {@link java.util.OptionalDouble} which contains a value. * @param expectedValue the value we expect to be in the provided {@link java.util.OptionalDouble}. * @return a error message factory */ public static OptionalShouldContain shouldContain(OptionalDouble optional, double expectedValue) { return optional.isPresent() ? new OptionalShouldContain(EXPECTING_TO_CONTAIN, optional, expectedValue) : shouldContain(expectedValue); } /** * Indicates that the provided {@link java.util.OptionalInt} does not contain the provided argument. * * @param optional the {@link java.util.OptionalInt} which contains a value. * @param expectedValue the value we expect to be in the provided {@link java.util.OptionalInt}. * @return a error message factory */ public static OptionalShouldContain shouldContain(OptionalInt optional, int expectedValue) { return optional.isPresent() ? new OptionalShouldContain(EXPECTING_TO_CONTAIN, optional, expectedValue) : shouldContain(expectedValue); } /** * Indicates that the provided {@link java.util.OptionalLong} does not contain the provided argument. * * @param optional the {@link java.util.OptionalLong} which contains a value. * @param expectedValue the value we expect to be in the provided {@link java.util.OptionalLong}. * @return a error message factory */ public static OptionalShouldContain shouldContain(OptionalLong optional, long expectedValue) { return optional.isPresent() ? new OptionalShouldContain(EXPECTING_TO_CONTAIN, optional, expectedValue) : shouldContain(expectedValue); } /** * Indicates that the provided {@link java.util.Optional} does not contain the provided argument (judging by reference * equality). * * @param optional the {@link java.util.Optional} which contains a value. * @param expectedValue the value we expect to be in the provided {@link java.util.Optional}. * @param <VALUE> the type of the value contained in the {@link java.util.Optional}. * @return a error message factory */ public static <VALUE> OptionalShouldContain shouldContainSame(Optional<VALUE> optional, VALUE expectedValue) {<FILL_FUNCTION_BODY>} /** * Indicates that an {@link java.util.Optional} is empty so it doesn't contain the expected value. * * @param expectedValue the value we expect to be in an {@link java.util.Optional}. * @return a error message factory. */ public static OptionalShouldContain shouldContain(Object expectedValue) { return new OptionalShouldContain(expectedValue); } }
return optional.isPresent() ? new OptionalShouldContain(EXPECTING_TO_CONTAIN_SAME, optional, expectedValue) : shouldContain(expectedValue);
1,103
48
1,151
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/OptionalShouldContainInstanceOf.java
OptionalShouldContainInstanceOf
shouldContainInstanceOf
class OptionalShouldContainInstanceOf extends BasicErrorMessageFactory { private OptionalShouldContainInstanceOf(String message) { super(message); } /** * Indicates that a value should be present in an empty {@link java.util.Optional}. * * @param value Optional to be checked. * @param clazz the class to check the optional value against * @return an error message factory. * @throws java.lang.NullPointerException if optional is null. */ public static OptionalShouldContainInstanceOf shouldContainInstanceOf(Object value, Class<?> clazz) {<FILL_FUNCTION_BODY>} }
Optional<?> optional = (Optional<?>) value; if (optional.isPresent()) { return new OptionalShouldContainInstanceOf(format("%nExpecting actual:%n %s%nto contain a value that is an instance of:%n %s%nbut did contain an instance of:%n %s", optional.getClass().getSimpleName(), clazz.getName(), optional.get().getClass().getName())); } return new OptionalShouldContainInstanceOf(format("%nExpecting actual:%n %s%nto contain a value that is an instance of:%n %s%nbut was empty", optional.getClass().getSimpleName(), clazz.getName()));
165
176
341
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldAccept.java
ShouldAccept
shouldAccept
class ShouldAccept extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldAccept}</code>. * * @param <T> guarantees that the type of the value value and the generic type of the {@code Predicate} are the same. * @param predicate the {@code Predicate}. * @param value the value value in the failed assertion. * @param description predicate description to include in the error message, * @return the created {@code ErrorMessageFactory}. */ public static <T> ErrorMessageFactory shouldAccept(Predicate<? super T> predicate, T value, PredicateDescription description) {<FILL_FUNCTION_BODY>} private ShouldAccept(Object value, PredicateDescription description) { super("%nExpecting actual:%n %s predicate%nto accept %s but it did not.", description, value); } }
requireNonNull(description, "The predicate description must not be null"); return new ShouldAccept(value, description);
224
31
255
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBe.java
ShouldBe
shouldBe
class ShouldBe extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBe}</code>. * @param <T> guarantees that the type of the actual value and the generic type of the {@code Condition} are the same. * @param actual the actual value in the failed assertion. * @param condition the {@code Condition}. * @return the created {@code ErrorMessageFactory}. */ public static <T> ErrorMessageFactory shouldBe(T actual, Condition<? super T> condition) {<FILL_FUNCTION_BODY>} private ShouldBe(Object actual, Condition<?> condition) { super("%nExpecting actual:%n %s%nto be %s", actual, condition); } private <T> ShouldBe(T actual, Join<? super T> join) { super("%n" + "Expecting actual:%n" + " %s%n" + // use concatenation to avoid the string to be double quoted later on "to be:%n" + join.conditionDescriptionWithStatus(actual), actual); } }
if (condition instanceof Join) return new ShouldBe(actual, (Join<? super T>) condition); return new ShouldBe(actual, condition);
285
39
324
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeAfter.java
ShouldBeAfter
shouldBeAfter
class ShouldBeAfter extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBeAfter}</code>. * @param actual the actual value in the failed assertion. * @param other the value used in the failed assertion to compare the actual value to. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeAfter(Object actual, Object other, ComparisonStrategy comparisonStrategy) { return new ShouldBeAfter(actual, other, comparisonStrategy); } /** * Creates a new <code>{@link ShouldBeAfter}</code>. * @param actual the actual value in the failed assertion. * @param other the value used in the failed assertion to compare the actual value to. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeAfter(Object actual, Object other) { return new ShouldBeAfter(actual, other, StandardComparisonStrategy.instance()); } /** * Creates a new <code>{@link ShouldBeAfter}</code>. * @param actual the actual value in the failed assertion. * @param year the year to compare the actual date's year to. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeAfter(Date actual, int year) {<FILL_FUNCTION_BODY>} private ShouldBeAfter(Object actual, Object other, ComparisonStrategy comparisonStrategy) { super("%nExpecting actual:%n %s%nto be strictly after:%n %s%n%s", actual, other, comparisonStrategy); } }
Date januaryTheFirstOfGivenYear = parse(year + "-01-01"); return new ShouldBeAfter(actual, januaryTheFirstOfGivenYear, StandardComparisonStrategy.instance());
432
51
483
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeEmpty.java
ShouldBeEmpty
shouldBeEmpty
class ShouldBeEmpty extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBeEmpty}</code>. * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeEmpty(Object actual) { return new ShouldBeEmpty("%nExpecting empty but was: %s", actual); } /** * Creates a new <code>{@link ShouldBeEmpty}</code>. * @param actual the actual file in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeEmpty(File actual) {<FILL_FUNCTION_BODY>} /** * Creates a new <code>{@link ShouldBeEmpty}</code>. * @param actual the actual path in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeEmpty(Path actual) { return new ShouldBeEmpty("%nExpecting path %s to be empty", actual); } private ShouldBeEmpty(String format, Object... arguments) { super(format, arguments); } }
return new ShouldBeEmpty("%nExpecting file %s to be empty", actual);
313
24
337
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeEqualByComparingFieldByFieldRecursively.java
ShouldBeEqualByComparingFieldByFieldRecursively
describeDifference
class ShouldBeEqualByComparingFieldByFieldRecursively extends BasicErrorMessageFactory { public static ErrorMessageFactory shouldBeEqualByComparingFieldByFieldRecursive(Object actual, Object other, List<Difference> differences, Representation representation) { List<String> descriptionOfDifferences = differences.stream() .map(difference -> describeDifference(difference, representation)) .collect(toList()); return new ShouldBeEqualByComparingFieldByFieldRecursively("%n" + "Expecting actual:%n" + " %s%n" + "to be equal to:%n" + " %s%n" + "when recursively comparing field by field, but found the following difference(s):%n" + join(descriptionOfDifferences).with(format("%n")), actual, other); } public static ErrorMessageFactory shouldBeEqualByComparingFieldByFieldRecursively(Object actual, Object other, List<ComparisonDifference> differences, RecursiveComparisonConfiguration recursiveComparisonConfiguration, Representation representation) { String differencesDescription = join(differences.stream() .map(difference -> difference.multiLineDescription(representation)) .collect(toList())).with(format("%n%n")); String recursiveComparisonConfigurationDescription = recursiveComparisonConfiguration.multiLineDescription(representation); String differencesCount = differences.size() == 1 ? "difference:%n" : "%s differences:%n"; // @format:off return new ShouldBeEqualByComparingFieldByFieldRecursively("%n" + "Expecting actual:%n" + " %s%n" + "to be equal to:%n" + " %s%n" + "when recursively comparing field by field, but found the following " + differencesCount + "%n" + escapePercent(differencesDescription) + "%n" + "%n"+ "The recursive comparison was performed with this configuration:%n" + recursiveComparisonConfigurationDescription, // don't use %s to avoid AssertJ formatting String with "" actual, other, differences.size()); // @format:on } private ShouldBeEqualByComparingFieldByFieldRecursively(String message, Object... arguments) { super(message, arguments); } private static String describeDifference(Difference difference, Representation representation) {<FILL_FUNCTION_BODY>} }
UnambiguousRepresentation unambiguousRepresentation = new UnambiguousRepresentation(representation, difference.getActual(), difference.getOther()); String additionalInfo = difference.getDescription() .map(desc -> format("%n- reason : %s", escapePercent(desc))) .orElse(""); return format("%nPath to difference: <%s>%n" + "- actual : %s%n" + "- expected: %s" + additionalInfo, join(difference.getPath()).with("."), escapePercent(unambiguousRepresentation.getActual()), escapePercent(unambiguousRepresentation.getExpected()));
645
178
823
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeEqualByComparingOnlyGivenFields.java
ShouldBeEqualByComparingOnlyGivenFields
shouldBeEqualComparingOnlyGivenFields
class ShouldBeEqualByComparingOnlyGivenFields extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBeEqualByComparingOnlyGivenFields}</code>. * * * @param actual the actual value in the failed assertion. * @param rejectedFields fields names not matching * @param rejectedValues fields values not matching * @param expectedValues expected fields values * @param acceptedFields fields on which is based the lenient equality * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeEqualComparingOnlyGivenFields(Object actual, List<String> rejectedFields, List<Object> rejectedValues, List<Object> expectedValues, List<String> acceptedFields) {<FILL_FUNCTION_BODY>} private ShouldBeEqualByComparingOnlyGivenFields(Object actual, List<String> rejectedFields, List<Object> rejectedValues, List<Object> expectedValue, List<String> acceptedFields) { super("%nExpecting values:%n" + " %s%n" + "in fields:%n" + " %s%n" + "but were:%n" + " %s%n" + "in %s.%n" + "Comparison was performed on fields:%n %s", expectedValue, rejectedFields, rejectedValues, actual, acceptedFields); } private ShouldBeEqualByComparingOnlyGivenFields(Object actual, String rejectedField, Object rejectedValue, Object expectedValue, List<String> acceptedFields) { super("%nExpecting value %s in field %s but was %s in %s", expectedValue, rejectedField, rejectedValue, actual, acceptedFields); } }
if (rejectedFields.size() == 1) { return new ShouldBeEqualByComparingOnlyGivenFields(actual, rejectedFields.get(0), rejectedValues.get(0), expectedValues.get(0), acceptedFields); } return new ShouldBeEqualByComparingOnlyGivenFields(actual, rejectedFields, rejectedValues, expectedValues, acceptedFields);
445
97
542
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeEqualToIgnoringFields.java
ShouldBeEqualToIgnoringFields
shouldBeEqualToIgnoringGivenFields
class ShouldBeEqualToIgnoringFields extends BasicErrorMessageFactory { private static final String EXPECTED_MULTIPLE = "%nExpecting values:%n %s%nin fields:%n %s%nbut were:%n %s%nin %s.%n"; private static final String EXPECTED_SINGLE = "%nExpecting value %s in field %s but was %s in %s.%n"; private static final String COMPARISON = "Comparison was performed on all fields"; private static final String EXCLUDING = " but %s"; /** * Creates a new <code>{@link ShouldBeEqualToIgnoringFields}</code>. * * @param actual the actual value in the failed assertion. * @param rejectedFields fields name not matching * @param rejectedValues rejected fields values * @param expectedValues expected fields values * @param ignoredFields fields which are not base the lenient equality * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeEqualToIgnoringGivenFields(Object actual, List<String> rejectedFields, List<Object> rejectedValues, List<Object> expectedValues, List<String> ignoredFields) {<FILL_FUNCTION_BODY>} private ShouldBeEqualToIgnoringFields(Object actual, List<String> rejectedFields, List<Object> rejectedValues, List<Object> expectedValues, List<String> ignoredFields) { super(EXPECTED_MULTIPLE + COMPARISON + EXCLUDING, expectedValues, rejectedFields, rejectedValues, actual, ignoredFields); } private ShouldBeEqualToIgnoringFields(Object actual, String rejectedField, Object rejectedValue, Object expectedValue, List<String> ignoredFields) { super(EXPECTED_SINGLE + COMPARISON + EXCLUDING, expectedValue, rejectedField, rejectedValue, actual, ignoredFields); } private ShouldBeEqualToIgnoringFields(Object actual, List<String> rejectedFields, List<Object> rejectedValues, List<Object> expectedValue) { super(EXPECTED_MULTIPLE + COMPARISON, expectedValue, rejectedFields, rejectedValues, actual); } private ShouldBeEqualToIgnoringFields(Object actual, String rejectedField, Object rejectedValue, Object expectedValue) { super(EXPECTED_SINGLE + COMPARISON, expectedValue, rejectedField, rejectedValue, actual); } }
if (rejectedFields.size() == 1) { if (ignoredFields.isEmpty()) { return new ShouldBeEqualToIgnoringFields(actual, rejectedFields.get(0), rejectedValues.get(0), expectedValues.get(0)); } return new ShouldBeEqualToIgnoringFields(actual, rejectedFields.get(0), rejectedValues.get(0), expectedValues.get(0), ignoredFields); } if (ignoredFields.isEmpty()) { return new ShouldBeEqualToIgnoringFields(actual, rejectedFields, rejectedValues, expectedValues); } return new ShouldBeEqualToIgnoringFields(actual, rejectedFields, rejectedValues, expectedValues, ignoredFields);
620
176
796
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeEqualWithTimePrecision.java
ShouldBeEqualWithTimePrecision
buildErrorMessageTemplate
class ShouldBeEqualWithTimePrecision extends BasicErrorMessageFactory { /** * Creates a new <code>{@link org.assertj.core.error.ShouldBeEqualWithTimePrecision}</code>. * * @param actual the actual value in the failed assertion. * @param expected the expected value in the failed assertion. * @param precision the {@link TimeUnit} used to compare actual with expected. * @return the created {@code AssertionErrorFactory}. */ public static ErrorMessageFactory shouldBeEqual(Date actual, Date expected, TimeUnit precision) { return new ShouldBeEqualWithTimePrecision(actual, expected, precision); } private ShouldBeEqualWithTimePrecision(Date actual, Date expected, TimeUnit precision) { super(buildErrorMessageTemplate(precision), actual, expected); } private static String buildErrorMessageTemplate(final TimeUnit precision) {<FILL_FUNCTION_BODY>} }
String fields = ""; String lastField = ""; if (precision.equals(TimeUnit.HOURS)) { lastField = "day"; } else if (precision.equals(TimeUnit.MINUTES)) { fields = ", day"; lastField = "hour"; } else if (precision.equals(TimeUnit.SECONDS)) { fields = ", day, hour"; lastField = "minute"; } else if (precision.equals(TimeUnit.MILLISECONDS)) { fields = ", day, hour, minute"; lastField = "second"; } return "%nExpecting actual:%n" + " %s%n" + "to have same year, month" + fields + " and " + lastField + " as:%n" + " %s%n" + "but had not.";
240
223
463
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeEqualWithinPercentage.java
ShouldBeEqualWithinPercentage
shouldBeEqualWithinPercentage
class ShouldBeEqualWithinPercentage extends BasicErrorMessageFactory { /** * Creates a new <code>{@link org.assertj.core.error.ShouldBeEqualWithinPercentage}</code>. * * @param <T> the type of values to compare. * @param actual the actual value in the failed assertion. * @param expected the expected value in the failed assertion. * @param percentage the given positive percentage. * @param difference the effective difference between actual and expected. * @return the created {@code ErrorMessageFactory}. */ public static <T extends Number> ErrorMessageFactory shouldBeEqualWithinPercentage(T actual, T expected, Percentage percentage, T difference) {<FILL_FUNCTION_BODY>} private ShouldBeEqualWithinPercentage(Number actual, Number expected, Percentage percentage, double expectedPercentage) { super("%nExpecting actual:%n" + " %s%n" + "to be close to:%n" + " %s%n" + "by less than %s but difference was %s%%.%n" + "(a difference of exactly %s being considered valid)", actual, expected, percentage, expectedPercentage, percentage); } }
double expectedPercentage = difference.doubleValue() / expected.doubleValue() * 100d; return new ShouldBeEqualWithinPercentage(actual, expected, percentage, expectedPercentage);
329
53
382
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeExactlyInstanceOf.java
ShouldBeExactlyInstanceOf
shouldBeExactlyInstance
class ShouldBeExactlyInstanceOf extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBeExactlyInstanceOf}</code>. * * @param actual the actual value in the failed assertion. * @param type the type {@code actual} is expected to be. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeExactlyInstance(Object actual, Class<?> type) {<FILL_FUNCTION_BODY>} private ShouldBeExactlyInstanceOf(Object actual, Class<?> type) { super("%nExpecting actual:%n %s%nto be exactly an instance of:%n %s%nbut was an instance of:%n %s", actual, type, actual.getClass()); } private ShouldBeExactlyInstanceOf(Throwable throwable, Class<?> type) { super("%nExpecting actual throwable to be exactly an instance of:%n %s%nbut was:%n %s", type, throwable); } }
return actual instanceof Throwable ? new ShouldBeExactlyInstanceOf((Throwable) actual, type) : new ShouldBeExactlyInstanceOf(actual, type);
278
46
324
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeInstance.java
ShouldBeInstance
shouldBeInstance
class ShouldBeInstance extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBeInstance}</code>. * * @param object the object value in the failed assertion. * @param type the type {@code object} is \nExpecting:\n to belong to. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeInstance(Object object, Class<?> type) {<FILL_FUNCTION_BODY>} /** * Creates a new <code>{@link ShouldBeInstance}</code> when object we want to check type is null. * * @param objectDescription the description of the null object we wanted to check type. * @param type the \nExpecting:\n type. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeInstanceButWasNull(String objectDescription, Class<?> type) { return new ShouldBeInstance(objectDescription, type); } private ShouldBeInstance(Object object, Class<?> type) { super("%n" + "Expecting actual:%n" + " %s%n" + "to be an instance of:%n" + " %s%n" + "but was instance of:%n" + " %s", object, type, object.getClass()); } private ShouldBeInstance(Throwable throwable, Class<?> type) { super("%n" + "Expecting actual throwable to be an instance of:%n" + " %s%n" + "but was:%n" + " %s", type, throwable); } private ShouldBeInstance(String objectDescription, Class<?> type) { super("%n" + "Expecting object:%n" + " %s%n" + "to be an instance of:%n" + " <%s>%n" + "but was null", objectDescription, type); } }
return object instanceof Throwable ? new ShouldBeInstance((Throwable) object, type) : new ShouldBeInstance(object, type);
534
34
568
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeInstanceOfAny.java
ShouldBeInstanceOfAny
shouldBeInstanceOfAny
class ShouldBeInstanceOfAny extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBeInstanceOfAny}</code>. * * @param actual the actual value in the failed assertion. * @param types contains the type or types {@code actual} is expected to belong to. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeInstanceOfAny(Object actual, Class<?>[] types) {<FILL_FUNCTION_BODY>} private ShouldBeInstanceOfAny(Object actual, Class<?>[] types) { super("%nExpecting actual:%n %s%nto be an instance of any of:%n %s%nbut was instance of:%n %s", actual, types, actual.getClass()); } private ShouldBeInstanceOfAny(Throwable throwable, Class<?>[] types) { super("%nExpecting actual throwable to be an instance of any of the following types:%n %s%nbut was:%n %s", types, throwable); } }
return actual instanceof Throwable ? new ShouldBeInstanceOfAny((Throwable) actual, types) : new ShouldBeInstanceOfAny(actual, types);
282
40
322
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldBeSorted.java
ShouldBeSorted
shouldBeSorted
class ShouldBeSorted extends BasicErrorMessageFactory { private ShouldBeSorted(String format, Object... arguments) { super(format, arguments); } /** * Creates a new <code>{@link ShouldBeSorted}</code>. * * @param i the index of elements whose not naturally ordered with the next. * @param group the actual group in the failed assertion (either collection or an array). * @return an instance of {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeSorted(int i, Object group) {<FILL_FUNCTION_BODY>} public static ErrorMessageFactory shouldBeSortedAccordingToGivenComparator(int i, Object group, Comparator<?> comparator) { List<?> arrayWrapper = groupAsList(group); return new ShouldBeSorted( "%ngroup is not sorted according to %s comparator because element %s:%n %s%nis not less or equal than element %s:%n %s%ngroup was:%n %s", comparator, i, arrayWrapper.get(i), i + 1, arrayWrapper.get(i + 1), arrayWrapper); } public static ErrorMessageFactory shouldHaveMutuallyComparableElements(Object actual) { return new ShouldBeSorted("%nsome elements are not mutually comparable in group:%n %s", actual); } public static ErrorMessageFactory shouldHaveComparableElementsAccordingToGivenComparator(Object actual, Comparator<?> comparator) { return new ShouldBeSorted("%nsome elements are not mutually comparable according to %s comparator in group:%n<%s>", comparator, actual); } /** * Convert the given group (which is either an array or a Collection) to a List. * * @param group the group to convert * @return the corresponding List * @throws IllegalArgumentException if group can't be converted to a List */ @SuppressWarnings("unchecked") private static List<?> groupAsList(Object group) { if (group.getClass().isArray()) { return wrap(group); } else if (group instanceof Collection<?>) { return new ArrayList<>((Collection<Object>) group); } throw new IllegalArgumentException("Parameter should be an array or a collection but was " + group); } }
List<?> groupAsList = groupAsList(group); return new ShouldBeSorted( "%ngroup is not sorted because element %s:%n %s%nis not less or equal than element %s:%n %s%ngroup was:%n %s", i, groupAsList.get(i), i + 1, groupAsList.get(i + 1), groupAsList);
608
103
711
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContain.java
ShouldContain
shouldContain
class ShouldContain extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContain}</code>. * @param actual the actual value in the failed assertion. * @param expected values expected to be in {@code actual}. * @param notFound the values in {@code expected} not found in {@code actual}. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(Object actual, Object expected, Object notFound, ComparisonStrategy comparisonStrategy) { return shouldContain(actual.getClass(), actual, expected, notFound, comparisonStrategy); } /** * Creates a new <code>{@link ShouldContain}</code>. * @param clazz the actual value class in the failed assertion. * @param actual the actual value in the failed assertion. * @param expected values expected to be in {@code actual}. * @param notFound the values in {@code expected} not found in {@code actual}. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(Class<?> clazz, Object actual, Object expected, Object notFound, ComparisonStrategy comparisonStrategy) {<FILL_FUNCTION_BODY>} /** * Creates a new <code>{@link ShouldContain}</code>. * @param actual the actual value in the failed assertion. * @param expected values expected to be in {@code actual}. * @param notFound the values in {@code expected} not found in {@code actual}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContain(Object actual, Object expected, Object notFound) { return shouldContain(actual, expected, notFound, StandardComparisonStrategy.instance()); } public static ErrorMessageFactory directoryShouldContain(File actual, List<File> directoryContent, String filterDescription) { return new ShouldContain(actual, toFileNames(directoryContent), filterDescription); } private static List<String> toFileNames(List<File> files) { return files.stream() .map(File::getName) .collect(toList()); } public static ErrorMessageFactory directoryShouldContain(Path actual, List<Path> directoryContent, String filterDescription) { return new ShouldContain(actual, toPathNames(directoryContent), filterDescription); } private static List<String> toPathNames(List<Path> files) { return files.stream() .map(Path::toString) .collect(toList()); } private ShouldContain(Object actual, Object expected, Object notFound, ComparisonStrategy comparisonStrategy, GroupTypeDescription groupTypeDescription) { super("%nExpecting " + groupTypeDescription.getGroupTypeName() + ":%n %s%nto contain:%n %s%nbut could not find the following " + groupTypeDescription.getElementTypeName() + ":%n %s%n%s", actual, expected, notFound, comparisonStrategy); } private ShouldContain(Object actual, List<String> directoryContent, String filterDescription) { // not passing directoryContent and filterDescription as parameter to avoid AssertJ default String formatting super("%nExpecting directory:%n" + " %s%n" + "to contain at least one file matching " + escapePercent(filterDescription) + " but there was none.%n" + "The directory content was:%n " + escapePercent(directoryContent.toString()), actual); } }
GroupTypeDescription groupTypeDescription = getGroupTypeDescription(clazz); return new ShouldContain(actual, expected, notFound, comparisonStrategy, groupTypeDescription);
938
42
980
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce.java
ShouldContainCharSequenceOnlyOnce
shouldContainOnlyOnce
class ShouldContainCharSequenceOnlyOnce extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainCharSequenceOnlyOnce}</code>. * * @param actual the actual value in the failed assertion. * @param sequence the String expected to be in {@code actual} only once. * @param occurrences the number of occurrences of sequence in actual. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainOnlyOnce(CharSequence actual, CharSequence sequence, int occurrences, ComparisonStrategy comparisonStrategy) {<FILL_FUNCTION_BODY>} /** * Creates a new <code>{@link ShouldContainCharSequenceOnlyOnce}</code>. * * @param actual the actual value in the failed assertion. * @param sequence the String expected to be in {@code actual} only once. * @param occurrences the number of occurrences of sequence in actual. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainOnlyOnce(CharSequence actual, CharSequence sequence, int occurrences) { return shouldContainOnlyOnce(actual, sequence, occurrences, StandardComparisonStrategy.instance()); } private ShouldContainCharSequenceOnlyOnce(CharSequence actual, CharSequence expected, int occurrences, ComparisonStrategy comparisonStrategy) { super("%nExpecting actual:%n %s%nto appear only once in:%n %s%nbut it appeared %s times %s", expected, actual, occurrences, comparisonStrategy); } private ShouldContainCharSequenceOnlyOnce(CharSequence actual, CharSequence expected, ComparisonStrategy comparisonStrategy) { super("%nExpecting actual:%n %s%nto appear only once in:%n %s%nbut it did not appear %s", expected, actual, comparisonStrategy); } }
if (occurrences == 0) return new ShouldContainCharSequenceOnlyOnce(actual, sequence, comparisonStrategy); return new ShouldContainCharSequenceOnlyOnce(actual, sequence, occurrences, comparisonStrategy);
509
54
563
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainEntries.java
ShouldContainEntries
shouldContainEntries
class ShouldContainEntries extends BasicErrorMessageFactory { public static <K, V> ErrorMessageFactory shouldContainEntries(Map<? extends K, ? extends V> actual, Entry<? extends K, ? extends V>[] expectedEntries, Set<Entry<? extends K, ? extends V>> entriesWithWrongValue, Set<Entry<? extends K, ? extends V>> entriesWithKeyNotFound, Representation representation) {<FILL_FUNCTION_BODY>} private static <K, V> List<String> buildValueDifferences(Map<? extends K, ? extends V> actual, Set<Entry<? extends K, ? extends V>> entriesWithWrongValues, Representation representation) { return entriesWithWrongValues.stream() .map(entryWithWrongValue -> valueDifference(actual, entryWithWrongValue, representation)) .collect(toList()); } private static <K, V> String valueDifference(Map<? extends K, ? extends V> actual, Entry<? extends K, ? extends V> entryWithWrongValue, Representation representation) { K key = entryWithWrongValue.getKey(); MapEntry<K, ? extends V> actualEntry = entry(key, actual.get(key)); V expectedValue = entryWithWrongValue.getValue(); return escapePercent(format("%s (expected: %s)", representation.toStringOf(actualEntry), representation.toStringOf(expectedValue))); } private <K, V> ShouldContainEntries(Map<? extends K, ? extends V> actual, Entry<? extends K, ? extends V>[] expectedEntries, Set<Entry<? extends K, ? extends V>> notFound) { super("%nExpecting map:%n" + " %s%n" + "to contain entries:%n" + " %s%n" + "but could not find the following map entries:%n" + " %s", actual, expectedEntries, notFound); } private <K, V> ShouldContainEntries(Map<? extends K, ? extends V> actual, Entry<? extends K, ? extends V>[] expectedEntries, List<String> valueDifferences) { super("%nExpecting map:%n" + " %s%n" + "to contain entries:%n" + " %s%n" + "but the following map entries had different values:%n" + " " + valueDifferences, actual, expectedEntries, valueDifferences); } private <K, V> ShouldContainEntries(Map<? extends K, ? extends V> actual, Entry<? extends K, ? extends V>[] expectedEntries, Set<Entry<? extends K, ? extends V>> keysNotFound, List<String> valueDifferences) { super("%nExpecting map:%n" + " %s%n" + "to contain entries:%n" + " %s%n" + "but could not find the following map entries:%n" + " %s%n" + "and the following map entries had different values:%n" + " " + valueDifferences, actual, expectedEntries, keysNotFound); } }
if (entriesWithWrongValue.isEmpty()) return new ShouldContainEntries(actual, expectedEntries, entriesWithKeyNotFound); if (entriesWithKeyNotFound.isEmpty()) return new ShouldContainEntries(actual, expectedEntries, buildValueDifferences(actual, entriesWithWrongValue, representation)); // mix of missing keys and keys with different values return new ShouldContainEntries(actual, expectedEntries, entriesWithKeyNotFound, buildValueDifferences(actual, entriesWithWrongValue, representation));
845
130
975
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainExactlyInAnyOrder.java
ShouldContainExactlyInAnyOrder
shouldContainExactlyInAnyOrder
class ShouldContainExactlyInAnyOrder extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainExactlyInAnyOrder}</code>. * * @param actual the actual value in the failed assertion. * @param expected values expected to be contained in {@code actual}. * @param notFound values in {@code expected} not found in {@code actual}. * @param notExpected values in {@code actual} that were not in {@code expected}. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainExactlyInAnyOrder(Object actual, Object expected, Iterable<?> notFound, Iterable<?> notExpected, ComparisonStrategy comparisonStrategy) {<FILL_FUNCTION_BODY>} private ShouldContainExactlyInAnyOrder(Object actual, Object expected, Iterable<?> notFound, Iterable<?> notExpected, ComparisonStrategy comparisonStrategy) { super("%n" + "Expecting actual:%n" + " %s%n" + "to contain exactly in any order:%n" + " %s%n" + "elements not found:%n" + " %s%n" + "and elements not expected:%n" + " %s%n%s", actual, expected, notFound, notExpected, comparisonStrategy); } private ShouldContainExactlyInAnyOrder(Object actual, Object expected, Iterable<?> notFoundOrNotExpected, ErrorType errorType, ComparisonStrategy comparisonStrategy) { // @format:off super("%n" + "Expecting actual:%n" + " %s%n" + "to contain exactly in any order:%n" + " %s%n" + (errorType == NOT_FOUND_ONLY ? "but could not find the following elements:%n" : "but the following elements were unexpected:%n") + " %s%n%s", actual, expected, notFoundOrNotExpected, comparisonStrategy); // @format:on } public enum ErrorType { NOT_FOUND_ONLY, NOT_EXPECTED_ONLY } }
if (isNullOrEmpty(notExpected)) { return new ShouldContainExactlyInAnyOrder(actual, expected, notFound, NOT_FOUND_ONLY, comparisonStrategy); } if (isNullOrEmpty(notFound)) { return new ShouldContainExactlyInAnyOrder(actual, expected, notExpected, NOT_EXPECTED_ONLY, comparisonStrategy); } return new ShouldContainExactlyInAnyOrder(actual, expected, notFound, notExpected, comparisonStrategy);
593
129
722
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainKeys.java
ShouldContainKeys
shouldContainKeys
class ShouldContainKeys extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainKeys}</code>. * * @param <K> key type * @param actual the actual value in the failed assertion. * @param keys the expected keys * @return the created {@code ErrorMessageFactory}. */ public static <K> ErrorMessageFactory shouldContainKeys(Object actual, Set<K> keys) {<FILL_FUNCTION_BODY>} private <K> ShouldContainKeys(Object actual, Set<K> key) { super("%nExpecting actual:%n %s%nto contain keys:%n %s", actual, key); } private <K> ShouldContainKeys(Object actual, K key) { super("%nExpecting actual:%n %s%nto contain key:%n %s", actual, key); } }
if (keys.size() == 1) return new ShouldContainKeys(actual, keys.iterator().next()); return new ShouldContainKeys(actual, keys);
240
42
282
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainOnly.java
ShouldContainOnly
shouldContainOnly
class ShouldContainOnly extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainOnly}</code>. * * @param actual the actual value in the failed assertion. * @param expected values expected to be contained in {@code actual}. * @param notFound values in {@code expected} not found in {@code actual}. * @param notExpected values in {@code actual} that were not in {@code expected}. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainOnly(Object actual, Object expected, Iterable<?> notFound, Iterable<?> notExpected, ComparisonStrategy comparisonStrategy) {<FILL_FUNCTION_BODY>} public static ErrorMessageFactory shouldContainOnly(Object actual, Object expected, Iterable<?> notFound, Iterable<?> notExpected, GroupTypeDescription groupTypeDescription) { return shouldContainOnly(actual, expected, notFound, notExpected, StandardComparisonStrategy.instance(), groupTypeDescription); } private static ErrorMessageFactory shouldContainOnly(Object actual, Object expected, Iterable<?> notFound, Iterable<?> notExpected, ComparisonStrategy comparisonStrategy, GroupTypeDescription groupTypeDescription) { if (isNullOrEmpty(notExpected)) return new ShouldContainOnly(actual, expected, notFound, NOT_FOUND_ONLY, comparisonStrategy, groupTypeDescription); if (isNullOrEmpty(notFound)) return new ShouldContainOnly(actual, expected, notExpected, NOT_EXPECTED_ONLY, comparisonStrategy, groupTypeDescription); return new ShouldContainOnly(actual, expected, notFound, notExpected, comparisonStrategy, groupTypeDescription); } /** * Creates a new <code>{@link ShouldContainOnly}</code>. * * @param actual the actual value in the failed assertion. * @param expected values expected to be contained in {@code actual}. * @param notFound values in {@code expected} not found in {@code actual}. * @param notExpected values in {@code actual} that were not in {@code expected}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainOnly(Object actual, Object expected, Iterable<?> notFound, Iterable<?> notExpected) { return shouldContainOnly(actual, expected, notFound, notExpected, StandardComparisonStrategy.instance()); } private ShouldContainOnly(Object actual, Object expected, Iterable<?> notFound, Iterable<?> notExpected, ComparisonStrategy comparisonStrategy, GroupTypeDescription groupTypeDescription) { super("%n" + "Expecting " + groupTypeDescription.getGroupTypeName() + ":%n" + " %s%n" + "to contain only:%n" + " %s%n" + groupTypeDescription.getElementTypeName() + " not found:%n" + " %s%n" + "and " + groupTypeDescription.getElementTypeName() + " not expected:%n" + " %s%n%s", actual, expected, notFound, notExpected, comparisonStrategy); } private ShouldContainOnly(Object actual, Object expected, Iterable<?> notFoundOrNotExpected, ErrorType errorType, ComparisonStrategy comparisonStrategy, GroupTypeDescription groupTypeDescription) { // @format:off super("%n" + "Expecting "+groupTypeDescription.getGroupTypeName()+":%n" + " %s%n" + "to contain only:%n" + " %s%n" + (errorType == NOT_FOUND_ONLY ? "but could not find the following "+groupTypeDescription.getElementTypeName()+":%n" : "but the following "+groupTypeDescription.getElementTypeName()+" were unexpected:%n") + " %s%n%s", actual, expected, notFoundOrNotExpected, comparisonStrategy); // @format:on } public enum ErrorType { NOT_FOUND_ONLY, NOT_EXPECTED_ONLY } }
GroupTypeDescription groupTypeDescription = getGroupTypeDescription(actual); return shouldContainOnly(actual, expected, notFound, notExpected, comparisonStrategy, groupTypeDescription);
1,069
44
1,113
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainOnlyKeys.java
ShouldContainOnlyKeys
shouldContainOnlyKeys
class ShouldContainOnlyKeys extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainOnlyKeys}</code>. * * @param actual the actual value in the failed assertion. * @param expected values expected to be contained in {@code actual}. * @param notFound values in {@code expected} not found in {@code actual}. * @param notExpected values in {@code actual} that were not in {@code expected}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainOnlyKeys(Object actual, Object expected, Object notFound, Object notExpected) { return new ShouldContainOnlyKeys(actual, expected, notFound, notExpected, StandardComparisonStrategy.instance()); } /** * Creates a new <code>{@link ShouldContainOnlyKeys}</code>. * * @param actual the actual value in the failed assertion. * @param expected values expected to be contained in {@code actual}. * @param notFound values in {@code expected} not found in {@code actual}. * @param notExpected values in {@code actual} that were not in {@code expected}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainOnlyKeys(Object actual, Object expected, Object notFound, Iterable<?> notExpected) {<FILL_FUNCTION_BODY>} private ShouldContainOnlyKeys(Object actual, Object expected, Object notFound, Object notExpected, ComparisonStrategy comparisonStrategy) { super("%n" + "Expecting actual:%n" + " %s%n" + "to contain only following keys:%n" + " %s%n" + "keys not found:%n" + " %s%n" + "and keys not expected:%n" + " %s%n%s", actual, expected, notFound, notExpected, comparisonStrategy); } private ShouldContainOnlyKeys(Object actual, Object expected, Object notFound, ComparisonStrategy comparisonStrategy) { super("%n" + "Expecting actual:%n" + " %s%n" + "to contain only following keys:%n" + " %s%n" + "but could not find the following keys:%n" + " %s%n%s", actual, expected, notFound, comparisonStrategy); } }
if (isNullOrEmpty(notExpected)) { return new ShouldContainOnlyKeys(actual, expected, notFound, StandardComparisonStrategy.instance()); } return new ShouldContainOnlyKeys(actual, expected, notFound, notExpected, StandardComparisonStrategy.instance());
628
68
696
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainOnlyNulls.java
ShouldContainOnlyNulls
describe
class ShouldContainOnlyNulls extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainOnlyNulls}</code>. * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainOnlyNulls(Object actual) { return new ShouldContainOnlyNulls(actual, EMPTY, null); } public static ErrorMessageFactory shouldContainOnlyNulls(Object actual, Iterable<?> nonNullElements) { return new ShouldContainOnlyNulls(actual, NON_NULL_ELEMENTS, nonNullElements); } private ShouldContainOnlyNulls(Object actual, ErrorType errorType, Iterable<?> notExpected) { super("%n" + "Expecting actual:%n" + " %s%n" + "to contain only null elements but " + describe(errorType), actual, notExpected); } private static String describe(ErrorType errorType) {<FILL_FUNCTION_BODY>} public enum ErrorType { EMPTY, NON_NULL_ELEMENTS } }
switch (errorType) { case EMPTY: return "it was empty"; case NON_NULL_ELEMENTS: default: return "some elements were not:%n %s"; }
306
60
366
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainSubsequence.java
ShouldContainSubsequence
describeComparisonStrategy
class ShouldContainSubsequence extends BasicErrorMessageFactory { public static ShouldContainSubsequence actualDoesNotHaveEnoughElementsToContainSubsequence(Object actual, Object subsequence) { return new ShouldContainSubsequence(actual, subsequence); } private ShouldContainSubsequence(Object actual, Object subsequence) { super("%nExpecting actual to contain the specified subsequence but actual does not have enough elements to contain it, actual size is %s when subsequence size is %s%nactual:%n %s%nsubsequence:%n %s", sizeOfArrayOrIterable(actual), sizeOf(subsequence), actual, subsequence); } public static ShouldContainSubsequence actualDoesNotHaveEnoughElementsLeftToContainSubsequence(Object actual, Object subsequence, int actualIndex, int subsequenceIndex) { return new ShouldContainSubsequence(actual, subsequence, actualIndex, subsequenceIndex); } private ShouldContainSubsequence(Object actual, Object subsequence, int actualIndex, int subsequenceIndex) { super("%nExpecting actual to contain the specified subsequence but actual does not have enough elements left to compare after reaching element %s out of %s with %s subsequence element(s) still to find." + "%nactual:%n %s%nsubsequence:%n %s", actualIndex + 1, sizeOfArrayOrIterable(actual), sizeOf(subsequence) - subsequenceIndex, actual, subsequence); } private static Object sizeOfArrayOrIterable(Object actual) { return isArray(actual) ? Arrays.sizeOf(actual) : IterableUtil.sizeOf((Iterable<?>) actual); } /** * Creates a new <code>{@link ShouldContainSubsequence}</code>. * * @param actual the actual value in the failed assertion. * @param subsequence the subsequence of values expected to be in {@code actual}. * @param subsequenceIndex the index of the first token in {@code subsequence} that was not found in {@code actual}. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ShouldContainSubsequence shouldContainSubsequence(Object actual, Object subsequence, int subsequenceIndex, ComparisonStrategy comparisonStrategy) { return new ShouldContainSubsequence(actual, subsequence, subsequenceIndex, comparisonStrategy); } private ShouldContainSubsequence(Object actual, Object subsequence, int subsequenceIndex, ComparisonStrategy comparisonStrategy) { // Failed to find token at subsequence index %s in actual:%n %s super("%nExpecting actual to contain the specified subsequence but failed to find the element at subsequence index %s in actual" + describeComparisonStrategy(comparisonStrategy) + ":%n" + "subsequence element not found in actual:%n" + " %s%n" + "actual:%n" + " %s%n" + "subsequence:%n %s", subsequenceIndex, Array.get(subsequence, subsequenceIndex), actual, subsequence); } private static String describeComparisonStrategy(ComparisonStrategy comparisonStrategy) {<FILL_FUNCTION_BODY>} }
return comparisonStrategy == StandardComparisonStrategy.instance() ? "" : " when comparing elements using " + comparisonStrategy;
825
30
855
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainSubsequenceOfCharSequence.java
ShouldContainSubsequenceOfCharSequence
shouldContainSubsequence
class ShouldContainSubsequenceOfCharSequence extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainSubsequenceOfCharSequence}</code>. * * @param actual the actual value in the failed assertion. * @param strings the sequence of values expected to be in {@code actual}. * @param firstBadOrderIndex first index failing the subsequence. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainSubsequence(CharSequence actual, CharSequence[] strings, int firstBadOrderIndex) { return shouldContainSubsequence(actual, strings, firstBadOrderIndex, StandardComparisonStrategy.instance()); } /** * Creates a new <code>{@link ShouldContainSubsequenceOfCharSequence}</code>. * * @param actual the actual value in the failed assertion. * @param strings the sequence of values expected to be in {@code actual}. * @param badOrderIndex index failing the subsequence. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainSubsequence(CharSequence actual, CharSequence[] strings, int badOrderIndex, ComparisonStrategy comparisonStrategy) { return new ShouldContainSubsequenceOfCharSequence("%nExpecting actual:%n" + " %s%n" + "to contain the following CharSequences in this order (possibly with other values between them):%n" + " %s%n" + "but %s was found before %s%n%s", actual, strings, strings[badOrderIndex + 1], strings[badOrderIndex], comparisonStrategy); } /** * Creates a new <code>{@link ShouldContainSubsequenceOfCharSequence}</code> with detailed error messages about missing subsequences. * * @param actual the actual value in the failed assertion. * @param strings the sequence of values expected to be in {@code actual}. * @param notFoundRepeatedSubsequence a map where each key is a subsequence of {@code strings} * that was expected to be found in {@code actual} and the corresponding value is * the number of times it was expected but not found. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainSubsequence(CharSequence actual, CharSequence[] strings, Map<CharSequence, Integer> notFoundRepeatedSubsequence, ComparisonStrategy comparisonStrategy) {<FILL_FUNCTION_BODY>} /** * Returns the ordinal representation of a given integer. * <p> * This method converts integers to their ordinal form (e.g., 1 to "1st", 2 to "2nd", etc.). * Special cases for numbers ending in 11, 12, and 13 are handled to return "th" instead of * "st", "nd", or "rd". * </p> * * @param i the integer to convert * @return the ordinal representation of {@code i} */ private static String ordinal(int i) { int mod100 = i % 100; int mod10 = i % 10; if (mod10 == 1 && mod100 != 11) return i + "st"; if (mod10 == 2 && mod100 != 12) return i + "nd"; if (mod10 == 3 && mod100 != 13) return i + "rd"; return i + "th"; } private ShouldContainSubsequenceOfCharSequence(String format, CharSequence actual, CharSequence[] strings, CharSequence foundButBadOrder, CharSequence foundButBadOrder2, ComparisonStrategy comparisonStrategy) { super(format, actual, strings, foundButBadOrder, foundButBadOrder2, comparisonStrategy); } private ShouldContainSubsequenceOfCharSequence(String format, CharSequence actual, CharSequence[] strings, ComparisonStrategy comparisonStrategy) { super(format, actual, strings, comparisonStrategy); } }
String detailedErrorMessage; if (notFoundRepeatedSubsequence.size() == 1) { Map.Entry<CharSequence, Integer> singleEntry = notFoundRepeatedSubsequence.entrySet().iterator().next(); detailedErrorMessage = format("But the %s occurrence of \"%s\" was not found", ordinal(singleEntry.getValue() + 1), singleEntry.getKey()); } else { detailedErrorMessage = notFoundRepeatedSubsequence.entrySet().stream() .map(entry -> format("- the %s occurrence of \"%s\" was not found", ordinal(entry.getValue() + 1), entry.getKey())) .collect(joining("%n")); detailedErrorMessage = "But:%n" + detailedErrorMessage; } return new ShouldContainSubsequenceOfCharSequence("%nExpecting actual:%n" + " %s%n" + "to contain the following CharSequences in this order (possibly with other values between them):%n" + " %s%n" + detailedErrorMessage + "%n%s", actual, strings, comparisonStrategy);
1,085
296
1,381
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainValues.java
ShouldContainValues
shouldContainValues
class ShouldContainValues extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainValues}</code>. * * @param <V> value type * @param actual the actual value in the failed assertion. * @param values the expected values. * @return the created {@code ErrorMessageFactory}. */ public static <V> ErrorMessageFactory shouldContainValues(Object actual, Set<V> values) {<FILL_FUNCTION_BODY>} private <V> ShouldContainValues(Object actual, Set<V> values) { super("%nExpecting actual:%n %s%nto contain values:%n %s", actual, values); } }
if (values.size() == 1) return shouldContainValue(actual, values.iterator().next()); return new ShouldContainValues(actual, values);
187
41
228
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldContainsOnlyOnce.java
ShouldContainsOnlyOnce
shouldContainsOnlyOnce
class ShouldContainsOnlyOnce extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainsOnlyOnce}</code>. * * @param actual the actual value in the failed assertion. * @param expected values expected to be contained in {@code actual}. * @param notFound values in {@code expected} not found in {@code actual}. * @param notOnlyOnce values in {@code actual} that were not only once in {@code expected}. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainsOnlyOnce(Object actual, Object expected, Set<?> notFound, Set<?> notOnlyOnce, ComparisonStrategy comparisonStrategy) {<FILL_FUNCTION_BODY>} /** * Creates a new <code>{@link ShouldContainsOnlyOnce}</code>. * * @param actual the actual value in the failed assertion. * @param expected values expected to be contained in {@code actual}. * @param notFound values in {@code expected} not found in {@code actual}. * @param notOnlyOnce values in {@code actual} that were found not only once in {@code expected}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldContainsOnlyOnce(Object actual, Object expected, Set<?> notFound, Set<?> notOnlyOnce) { return shouldContainsOnlyOnce(actual, expected, notFound, notOnlyOnce, StandardComparisonStrategy.instance()); } private ShouldContainsOnlyOnce(Object actual, Object expected, Set<?> notFound, Set<?> notOnlyOnce, ComparisonStrategy comparisonStrategy) { super("%nExpecting actual:%n %s%nto contain only once:%n %s%n" + "but some elements were not found:%n %s%n" + "and others were found more than once:%n %s%n%s", actual, expected, notFound, notOnlyOnce, comparisonStrategy); } private ShouldContainsOnlyOnce(Object actual, Object expected, Set<?> notFound, ComparisonStrategy comparisonStrategy) { super("%nExpecting actual:%n %s%nto contain only once:%n %s%nbut some elements were not found:%n %s%n%s", actual, expected, notFound, comparisonStrategy); } // change the order of parameters to avoid confusion with previous constructor private ShouldContainsOnlyOnce(Set<?> notOnlyOnce, Object actual, Object expected, ComparisonStrategy comparisonStrategy) { super("%nExpecting actual:%n %s%nto contain only once:%n %s%nbut some elements were found more than once:%n %s%n%s", actual, expected, notOnlyOnce, comparisonStrategy); } }
if (!isNullOrEmpty(notFound) && !isNullOrEmpty(notOnlyOnce)) return new ShouldContainsOnlyOnce(actual, expected, notFound, notOnlyOnce, comparisonStrategy); if (!isNullOrEmpty(notFound)) return new ShouldContainsOnlyOnce(actual, expected, notFound, comparisonStrategy); // case where no elements were missing but some appeared more than once. return new ShouldContainsOnlyOnce(notOnlyOnce, actual, expected, comparisonStrategy);
726
116
842
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHave.java
ShouldHave
shouldHave
class ShouldHave extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldHave}</code>. * @param <T> guarantees that the type of the actual value and the generic type of the {@code Condition} are the same. * @param actual the actual value in the failed assertion. * @param condition the {@code Condition}. * @return the created {@code ErrorMessageFactory}. */ public static <T> ErrorMessageFactory shouldHave(T actual, Condition<? super T> condition) {<FILL_FUNCTION_BODY>} private ShouldHave(Object actual, Condition<?> condition) { super("%nExpecting actual:%n %s%nto have %s", actual, condition); } private <T> ShouldHave(T actual, Join<? super T> join) { super("%n" + "Expecting actual:%n" + " %s%n" + // use concatenation to avoid the string to be double quoted later on "to have:%n" + join.conditionDescriptionWithStatus(actual), actual); } }
if (condition instanceof Join) return new ShouldHave(actual, (Join<? super T>) condition); return new ShouldHave(actual, condition);
284
39
323
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveAllNullFields.java
ShouldHaveAllNullFields
shouldHaveAllNullFields
class ShouldHaveAllNullFields extends BasicErrorMessageFactory { private static final String EXPECTED_MULTIPLE = "%nExpecting%n %s%nto only have null properties or fields but these were not null:%n %s.%n"; private static final String EXPECTED_SINGLE = "%nExpecting%n %s%nto only have null property or field, but %s was not null.%n"; private static final String COMPARISON = "Check was performed on all fields/properties"; private static final String EXCLUDING = COMPARISON + " except: %s."; private static final String DOT = "."; public ShouldHaveAllNullFields(Object actual, List<String> nonNullFields, List<String> ignoredFields) { super(EXPECTED_MULTIPLE + EXCLUDING, actual, nonNullFields, ignoredFields); } public ShouldHaveAllNullFields(Object actual, List<String> nonNullFields) { super(EXPECTED_MULTIPLE + COMPARISON + DOT, actual, nonNullFields); } public ShouldHaveAllNullFields(Object actual, String nonNullField) { super(EXPECTED_SINGLE + COMPARISON + DOT, actual, nonNullField); } public ShouldHaveAllNullFields(Object actual, String nonNullField, List<String> ignoredFields) { super(EXPECTED_SINGLE + EXCLUDING, actual, nonNullField, ignoredFields); } public static ShouldHaveAllNullFields shouldHaveAllNullFields(Object actual, List<String> nonNullFields, List<String> ignoredFields) {<FILL_FUNCTION_BODY>} }
if (nonNullFields.size() == 1) { if (ignoredFields.isEmpty()) { return new ShouldHaveAllNullFields(actual, nonNullFields.get(0)); } return new ShouldHaveAllNullFields(actual, nonNullFields.get(0), ignoredFields); } return ignoredFields.isEmpty() ? new ShouldHaveAllNullFields(actual, nonNullFields) : new ShouldHaveAllNullFields(actual, nonNullFields, ignoredFields);
427
120
547
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveCause.java
ShouldHaveCause
shouldHaveCause
class ShouldHaveCause extends BasicErrorMessageFactory { public static ErrorMessageFactory shouldHaveCause(Throwable actual, Throwable expectedCause) {<FILL_FUNCTION_BODY>} public static ErrorMessageFactory shouldHaveCause(Throwable actualCause) { return new BasicErrorMessageFactory("Expecting actual throwable to have a cause but it did not, actual was:%n%s", actualCause); } private ShouldHaveCause(Throwable actual, Throwable expectedCause) { super("%n" + "Expecting a cause with type:%n" + " %s%n" + "and message:%n" + " %s%n" + "but type was:%n" + " %s%n" + "and message was:%n" + " %s.%n%n" + "Throwable that failed the check:%n" + escapePercent(getStackTrace(actual)), expectedCause.getClass().getName(), expectedCause.getMessage(), actual.getCause().getClass().getName(), actual.getCause().getMessage()); } private ShouldHaveCause(Throwable expectedCause) { super("%n" + "Expecting a cause with type:%n" + " %s%n" + "and message:%n" + " %s%n" + "but actualCause had no cause.", expectedCause.getClass().getName(), expectedCause.getMessage()); } private ShouldHaveCause(Throwable actual, Class<? extends Throwable> expectedCauseClass) { super("%n" + "Expecting a cause with type:%n" + " %s%n" + "but type was:%n" + " %s.%n%n" + "Throwable that failed the check:%n" + escapePercent(getStackTrace(actual)), expectedCauseClass.getName(), actual.getCause().getClass().getName()); } private ShouldHaveCause(Throwable actual, String expectedCauseMessage) { super("%n" + "Expecting a cause with message:%n" + " %s%n" + "but message was:%n" + " %s.%n%n" + "Throwable that failed the check:%n" + escapePercent(getStackTrace(actual)), expectedCauseMessage, actual.getCause().getMessage()); } }
checkArgument(expectedCause != null, "expected cause should not be null"); // actual has no cause if (actual.getCause() == null) return new ShouldHaveCause(expectedCause); // same message => different type if (Objects.equals(actual.getCause().getMessage(), expectedCause.getMessage())) return new ShouldHaveCause(actual, expectedCause.getClass()); // same type => different message if (Objects.equals(actual.getCause().getClass(), expectedCause.getClass())) return new ShouldHaveCause(actual, expectedCause.getMessage()); return new ShouldHaveCause(actual, expectedCause);
648
166
814
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveCauseExactlyInstance.java
ShouldHaveCauseExactlyInstance
shouldHaveCauseExactlyInstance
class ShouldHaveCauseExactlyInstance extends BasicErrorMessageFactory { /** * Creates a new <code>{@link BasicErrorMessageFactory}</code>. * * @param actual the actual value in the failed assertion. * @param expectedCauseType the expected cause instance. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldHaveCauseExactlyInstance(Throwable actual, Class<? extends Throwable> expectedCauseType) {<FILL_FUNCTION_BODY>} private ShouldHaveCauseExactlyInstance(Throwable actual, Class<? extends Throwable> expectedCauseType) { super("%nExpecting a throwable with cause being exactly an instance of:%n" + " %s%n" + "but was an instance of:%n" + " %s%n" + "Throwable that failed the check:%n" + "%n" + escapePercent(getStackTrace(actual)), expectedCauseType, actual.getCause().getClass()); } private ShouldHaveCauseExactlyInstance(Class<? extends Throwable> expectedCauseType, Throwable actual) { super("%nExpecting a throwable with cause being exactly an instance of:%n %s%nbut current throwable has no cause." + "%nThrowable that failed the check:%n" + escapePercent(getStackTrace(actual)), expectedCauseType); } }
return actual.getCause() == null ? new ShouldHaveCauseExactlyInstance(expectedCauseType, actual) : new ShouldHaveCauseExactlyInstance(actual, expectedCauseType);
378
54
432
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveCauseInstance.java
ShouldHaveCauseInstance
shouldHaveCauseInstance
class ShouldHaveCauseInstance extends BasicErrorMessageFactory { /** * Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>. * * @param actual the actual value in the failed assertion. * @param expectedCauseType the expected cause type. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldHaveCauseInstance(Throwable actual, Class<? extends Throwable> expectedCauseType) {<FILL_FUNCTION_BODY>} private ShouldHaveCauseInstance(Throwable actual, Class<? extends Throwable> expectedCauseType) { super("%nExpecting a throwable with cause being an instance of:%n" + " %s%n" + "but was an instance of:%n" + " %s%n" + "Throwable that failed the check:%n" + "%n" + escapePercent(getStackTrace(actual)), expectedCauseType, actual.getCause().getClass()); } private ShouldHaveCauseInstance(Class<? extends Throwable> expectedCauseType) { super("%nExpecting a throwable with cause being an instance of:%n" + " %s%n" + "but current throwable has no cause.", expectedCauseType); } }
return actual.getCause() == null ? new ShouldHaveCauseInstance(expectedCauseType) : new ShouldHaveCauseInstance(actual, expectedCauseType);
354
46
400
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveDigest.java
ShouldHaveDigest
errorMessage
class ShouldHaveDigest extends BasicErrorMessageFactory { public static ErrorMessageFactory shouldHaveDigest(Path actualSource, DigestDiff diff) { return new ShouldHaveDigest(actualSource, diff); } public static ErrorMessageFactory shouldHaveDigest(File actualSource, DigestDiff diff) { return new ShouldHaveDigest(actualSource, diff); } public static ErrorMessageFactory shouldHaveDigest(InputStream actualSource, DigestDiff diff) { return new ShouldHaveDigest(actualSource, diff); } private ShouldHaveDigest(Path actualSource, DigestDiff diff) { super(errorMessage("Path", diff), actualSource, diff.getExpected(), diff.getActual()); } private ShouldHaveDigest(File actualSource, DigestDiff diff) { super(errorMessage("File", diff), actualSource, diff.getExpected(), diff.getActual()); } private ShouldHaveDigest(InputStream actualSource, DigestDiff diff) { super(errorMessage("InputStream", diff), actualSource, diff.getExpected(), diff.getActual()); } private static String errorMessage(String actualType, DigestDiff diff) {<FILL_FUNCTION_BODY>} }
return "%nExpecting " + actualType + " %s " + diff.getDigestAlgorithm() + " digest to be:%n" + " %s%n" + "but was:%n" + " %s";
304
66
370
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveDuration.java
ShouldHaveDuration
shouldHaveDays
class ShouldHaveDuration extends BasicErrorMessageFactory { private static final String EXPECTED_PREFIX = "%n" + "Expecting Duration:%n" + " %s%n" + "to have %s "; public static ShouldHaveDuration shouldHaveNanos(Duration actual, long actualNanos, long expectedNanos) { String metric; if (expectedNanos == 1 || expectedNanos == -1) { metric = "nano"; } else { metric = "nanos"; } return new ShouldHaveDuration(actual, actualNanos, expectedNanos, metric); } public static ShouldHaveDuration shouldHaveMillis(Duration actual, long actualMillis, long expectedMillis) { String metric; if (expectedMillis == 1 || expectedMillis == -1) { metric = "milli"; } else { metric = "millis"; } return new ShouldHaveDuration(actual, actualMillis, expectedMillis, metric); } public static ShouldHaveDuration shouldHaveSeconds(Duration actual, long actualSeconds, long expectedSeconds) { String metric; if (expectedSeconds == 1 || expectedSeconds == -1) { metric = "second"; } else { metric = "seconds"; } return new ShouldHaveDuration(actual, actualSeconds, expectedSeconds, metric); } public static ShouldHaveDuration shouldHaveMinutes(Duration actual, long actualMinutes, long expectedMinutes) { String metric; if (expectedMinutes == 1 || expectedMinutes == -1) { metric = "minute"; } else { metric = "minutes"; } return new ShouldHaveDuration(actual, actualMinutes, expectedMinutes, metric); } public static ShouldHaveDuration shouldHaveHours(Duration actual, long actualHours, long expectedHours) { String metric; if (expectedHours == 1 || expectedHours == -1) { metric = "hour"; } else { metric = "hours"; } return new ShouldHaveDuration(actual, actualHours, expectedHours, metric); } public static ShouldHaveDuration shouldHaveDays(Duration actual, long actualDays, long expectedDays) {<FILL_FUNCTION_BODY>} private ShouldHaveDuration(Duration actual, long actualSpecific, long expectedSpecific, String metric) { super(EXPECTED_PREFIX + metric + " but had %s", actual, expectedSpecific, actualSpecific); } }
String metric; if (expectedDays == 1 || expectedDays == -1) { metric = "day"; } else { metric = "days"; } return new ShouldHaveDuration(actual, actualDays, expectedDays, metric);
647
68
715
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveExactlyTypes.java
ShouldHaveExactlyTypes
shouldHaveTypes
class ShouldHaveExactlyTypes extends BasicErrorMessageFactory { public static ErrorMessageFactory shouldHaveTypes(Object actual, Iterable<Class<?>> expectedTypes, Iterable<Class<?>> expectedTypesNotFoundInActual, Iterable<Class<?>> actualTypesNotExpected) {<FILL_FUNCTION_BODY>} public static ErrorMessageFactory elementsTypesDifferAtIndex(Object actualElement, Class<?> expectedElement, int indexOfDifference) { return new ShouldHaveExactlyTypes(actualElement, expectedElement, indexOfDifference); } private ShouldHaveExactlyTypes(Object actual, Iterable<Class<?>> expected, Iterable<Class<?>> expectedTypesNotFoundInActual, Iterable<Class<?>> actualTypesNotExpected) { super("%n" + "Expecting actual elements:%n" + " %s%n" + "to have the following types (in this order):%n" + " %s%n" + "but there were no actual elements with these types:%n" + " %s%n" + "and these actual elements types were not expected:%n" + " %s", actual, expected, expectedTypesNotFoundInActual, actualTypesNotExpected); } private ShouldHaveExactlyTypes(Object actual, Iterable<Class<?>> expected, Iterable<Class<?>> diff, boolean expectedTypesNotFoundInActualOnly) { // @format:off super("%n" + "Expecting actual elements:%n" + " %s%n" + "to have the following types (in this order):%n" + " %s%n" + (expectedTypesNotFoundInActualOnly ? "but there were no actual elements with these types" : "but these actual elements types were not expected") + ":%n" + " %s", actual, expected, diff); // @format:on } private ShouldHaveExactlyTypes(Object actualElement, Class<?> expectedType, int indexOfDifference) { super("%n" + "actual element at index %s does not have the expected type, element was:%s%n" + "actual element type: %s%n" + "expected type : %s", indexOfDifference, actualElement, actualElement.getClass(), expectedType); } }
if (!isNullOrEmpty(actualTypesNotExpected) && !isNullOrEmpty(expectedTypesNotFoundInActual)) { return new ShouldHaveExactlyTypes(actual, expectedTypes, expectedTypesNotFoundInActual, actualTypesNotExpected); } // empty actualTypesNotExpected means expectedTypesNotFoundInActual is not empty boolean expectedTypesNotFoundInActualOnly = isNullOrEmpty(actualTypesNotExpected); Iterable<Class<?>> diff = expectedTypesNotFoundInActualOnly ? expectedTypesNotFoundInActual : actualTypesNotExpected; return new ShouldHaveExactlyTypes(actual, expectedTypes, diff, expectedTypesNotFoundInActualOnly);
606
152
758
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveExtension.java
ShouldHaveExtension
shouldHaveExtension
class ShouldHaveExtension extends BasicErrorMessageFactory { public static ShouldHaveExtension shouldHaveExtension(File actual, String actualExtension, String expectedExtension) {<FILL_FUNCTION_BODY>} public static ShouldHaveExtension shouldHaveExtension(Path actual, String actualExtension, String expectedExtension) { Objects.requireNonNull(actualExtension); return new ShouldHaveExtension(actual, actualExtension, expectedExtension); } private ShouldHaveExtension(Object actual, String actualExtension, String expectedExtension) { super("%nExpecting%n %s%nto have extension:%n %s%nbut had:%n %s.", actual, expectedExtension, actualExtension); } public static ShouldHaveExtension shouldHaveExtension(Path actual, String expectedExtension) { return new ShouldHaveExtension(actual, expectedExtension); } public static ShouldHaveExtension shouldHaveExtension(File actual, String expectedExtension) { return new ShouldHaveExtension(actual, expectedExtension); } private ShouldHaveExtension(Object actual, String expectedExtension) { super("%nExpecting%n %s%nto have extension:%n %s%nbut had no extension.", actual, expectedExtension); } }
return actualExtension == null ? new ShouldHaveExtension(actual, expectedExtension) : new ShouldHaveExtension(actual, actualExtension, expectedExtension);
300
39
339
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveNoFields.java
ShouldHaveNoFields
fieldDescription
class ShouldHaveNoFields extends BasicErrorMessageFactory { public static ErrorMessageFactory shouldHaveNoPublicFields(Class<?> actual, Set<String> fields) { return new ShouldHaveNoFields(actual, fields, true, false); } public static ErrorMessageFactory shouldHaveNoDeclaredFields(Class<?> actual, Set<String> fields) { return new ShouldHaveNoFields(actual, fields, false, true); } private ShouldHaveNoFields(Class<?> actual, Set<String> fields, boolean publik, boolean declared) { super("%nExpecting%n" + " %s%n" + "not to have any " + fieldDescription(publik, declared) + " fields but it has:%n" + " %s", actual, fields); } private static String fieldDescription(boolean publik, boolean declared) {<FILL_FUNCTION_BODY>} }
if (publik) { return declared ? "public declared" : "public"; } return declared ? "declared" : "";
231
38
269
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
assertj_assertj
assertj/assertj-core/src/main/java/org/assertj/core/error/ShouldHaveNoNullFields.java
ShouldHaveNoNullFields
shouldHaveNoNullFieldsExcept
class ShouldHaveNoNullFields extends BasicErrorMessageFactory { private static final String EXPECTED_MULTIPLE = "%nExpecting%n %s%nto have a property or a field named %s.%n"; private static final String EXPECTED_SINGLE = "%nExpecting%n %s%nnot to have any null property or field, but %s was null.%n"; private static final String COMPARISON = "Check was performed on all fields/properties"; private static final String EXCLUDING = COMPARISON + " except: %s"; private static final String DOT = "."; public ShouldHaveNoNullFields(Object actual, List<String> rejectedFields, List<String> ignoredFields) { super(EXPECTED_MULTIPLE + EXCLUDING, actual, rejectedFields, ignoredFields); } public ShouldHaveNoNullFields(Object actual, List<String> rejectedFields) { super(EXPECTED_MULTIPLE + COMPARISON + DOT, actual, rejectedFields); } public ShouldHaveNoNullFields(Object actual, String rejectedField) { super(EXPECTED_SINGLE + COMPARISON + DOT, actual, rejectedField); } public ShouldHaveNoNullFields(Object actual, String rejectedField, List<String> ignoredFields) { super(EXPECTED_SINGLE + EXCLUDING, actual, rejectedField, ignoredFields); } public static ShouldHaveNoNullFields shouldHaveNoNullFieldsExcept(Object actual, List<String> rejectedFields, List<String> ignoredFields) {<FILL_FUNCTION_BODY>} }
if (rejectedFields.size() == 1) { if (ignoredFields.isEmpty()) { return new ShouldHaveNoNullFields(actual, rejectedFields.get(0)); } return new ShouldHaveNoNullFields(actual, rejectedFields.get(0), ignoredFields); } if (ignoredFields.isEmpty()) { return new ShouldHaveNoNullFields(actual, rejectedFields); } return new ShouldHaveNoNullFields(actual, rejectedFields, ignoredFields);
412
122
534
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter