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/error/ShouldHavePackage.java
|
ShouldHavePackage
|
shouldHavePackage
|
class ShouldHavePackage extends BasicErrorMessageFactory {
private static final String SHOULD_HAVE_PACKAGE = new StringJoiner("%n", "%n", "").add("Expecting")
.add(" %s")
.add("to have package:")
.add(" %s")
.toString();
private static final String BUT_HAD_NONE = new StringJoiner("%n", "%n", "").add("but had none.")
.toString();
private static final String BUT_HAD = new StringJoiner("%n", "%n", "").add("but had:")
.add(" %s")
.toString();
/**
* Creates a new <code>ShouldHavePackage</code> with a {@link Package} instance.
*
* @param actual the actual value in the failed assertion.
* @param aPackage the expected package
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldHavePackage(Class<?> actual, Package aPackage) {
return shouldHavePackage(actual, aPackage.getName());
}
/**
* Creates a new <code>ShouldHavePackage</code> with a package name.
*
* @param actual the actual value in the failed assertion.
* @param packageName the expected package name
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldHavePackage(Class<?> actual, String packageName) {<FILL_FUNCTION_BODY>}
private ShouldHavePackage(Class<?> actual, String expectedPackage) {
super(SHOULD_HAVE_PACKAGE + BUT_HAD_NONE, actual, expectedPackage);
}
private ShouldHavePackage(Class<?> actual, String expectedPackage, String actualPackage) {
super(SHOULD_HAVE_PACKAGE + BUT_HAD, actual, expectedPackage, actualPackage);
}
}
|
final Package actualPackage = actual.getPackage();
return (actualPackage == null)
? new ShouldHavePackage(actual, packageName)
: new ShouldHavePackage(actual, packageName, actualPackage.getName());
| 493
| 55
| 548
|
<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/ShouldHaveParent.java
|
ShouldHaveParent
|
shouldHaveParent
|
class ShouldHaveParent extends BasicErrorMessageFactory {
@VisibleForTesting
public static final String PATH_NO_PARENT = "%nExpecting path%n %s%nto have parent:%n %s%nbut did not have one.";
@VisibleForTesting
public static final String PATH_NOT_EXPECTED_PARENT = "%nExpecting path%n %s%nto have parent:%n %s%nbut had:%n %s.";
@VisibleForTesting
public static final String FILE_NO_PARENT = "%nExpecting file%n %s%nto have parent:%n %s%nbut did not have one.";
@VisibleForTesting
public static final String FILE_NOT_EXPECTED_PARENT = "%nExpecting file%n %s%nto have parent:%n %s%nbut had:%n %s.";
public static ShouldHaveParent shouldHaveParent(File actual, File expected) {
return actual.getParentFile() == null ? new ShouldHaveParent(actual, expected)
: new ShouldHaveParent(actual,
actual.getParentFile(), expected);
}
public static ShouldHaveParent shouldHaveParent(Path actual, Path expected) {<FILL_FUNCTION_BODY>}
public static ShouldHaveParent shouldHaveParent(Path actual, Path actualParent, Path expected) {
return new ShouldHaveParent(actual, actualParent, expected);
}
private ShouldHaveParent(File actual, File expected) {
super(FILE_NO_PARENT, actual, expected);
}
private ShouldHaveParent(File actual, File actualParent, File expected) {
super(FILE_NOT_EXPECTED_PARENT, actual, expected, actualParent);
}
private ShouldHaveParent(Path actual, Path expected) {
super(PATH_NO_PARENT, actual, expected);
}
private ShouldHaveParent(Path actual, Path actualParent, Path expected) {
super(PATH_NOT_EXPECTED_PARENT, actual, expected, actualParent);
}
}
|
final Path actualParent = actual.getParent();
return actualParent == null
? new ShouldHaveParent(actual, expected)
: new ShouldHaveParent(actual, actualParent, expected);
| 524
| 49
| 573
|
<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/ShouldHavePeriod.java
|
ShouldHavePeriod
|
shouldHaveDays
|
class ShouldHavePeriod extends BasicErrorMessageFactory {
private static final String EXPECTED_PREFIX = "%n" +
"Expecting Period:%n" +
" %s%n" +
"to have %s ";
private ShouldHavePeriod(Period actual, int actualSpecific, int expectedSpecific, String metric) {
super(EXPECTED_PREFIX + metric + " but had %s", actual, expectedSpecific, actualSpecific);
}
public static ShouldHavePeriod shouldHaveYears(Period actual, int actualYear, int expectedYear) {
final String metric = Math.abs(expectedYear) == 1 ? "year" : "years";
return new ShouldHavePeriod(actual, actualYear, expectedYear, metric);
}
public static ShouldHavePeriod shouldHaveMonths(Period actual, int actualMonths, int expectedMonths) {
final String metric = Math.abs(expectedMonths) == 1 ? "month" : "months";
return new ShouldHavePeriod(actual, actualMonths, expectedMonths, metric);
}
public static ShouldHavePeriod shouldHaveDays(Period actual, int actualDays, int expectedDays) {<FILL_FUNCTION_BODY>}
}
|
final String metric = Math.abs(expectedDays) == 1 ? "day" : "days";
return new ShouldHavePeriod(actual, actualDays, expectedDays, metric);
| 300
| 47
| 347
|
<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/ShouldHaveRootCause.java
|
ShouldHaveRootCause
|
shouldHaveRootCause
|
class ShouldHaveRootCause extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldHaveRootCauseWithMessage(Throwable actual, Throwable actualCause,
String expectedMessage) {
checkArgument(actual != null, "actual should not be null");
checkArgument(expectedMessage != null, "expected root cause message should not be null");
if (actualCause == null) return new ShouldHaveRootCause(actual, expectedMessage);
return new ShouldHaveRootCause(actual, actualCause, expectedMessage);
}
public static ErrorMessageFactory shouldHaveRootCause(Throwable actual, Throwable actualCause, Throwable expectedCause) {<FILL_FUNCTION_BODY>}
public static ErrorMessageFactory shouldHaveRootCause(Throwable actualCause) {
return new BasicErrorMessageFactory("Expecting actual throwable to have a root cause but it did not, actual was:%n%s",
actualCause);
}
private ShouldHaveRootCause(Throwable actual, Throwable actualCause, Throwable expectedCause) {
super("%n" +
"Expecting a root cause with type:%n" +
" %s%n" +
"and message:%n" +
" %s%n" +
"but type was:%n" +
" %s%n" +
"and message was:%n" +
" %s." +
"%n" +
"Throwable that failed the check:%n" +
"%n" + escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting
expectedCause.getClass().getName(), expectedCause.getMessage(),
actualCause.getClass().getName(), actualCause.getMessage());
}
private ShouldHaveRootCause(Throwable actual, Throwable expectedCause) {
super("%n" +
"Expecting a root cause with type:%n" +
" %s%n" +
"and message:%n" +
" %s%n" +
"but actual had no root cause." +
"%n" +
"Throwable that failed the check:%n" +
"%n" + escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting
expectedCause.getClass().getName(), expectedCause.getMessage());
}
private ShouldHaveRootCause(Throwable actual, Throwable actualCause, Class<? extends Throwable> expectedCauseClass) {
super("%n" +
"Expecting a root cause with type:%n" +
" %s%n" +
"but type was:%n" +
" %s." +
"%n" +
"Throwable that failed the check:%n" +
"%n" + escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting
expectedCauseClass.getName(), actualCause.getClass().getName());
}
private ShouldHaveRootCause(Throwable actual, String expectedMessage) {
super("%n" +
"Expecting a root cause with message:%n" +
" %s%n" +
"but actual had no root cause." +
"%n" +
"Throwable that failed the check:%n" +
"%n" + escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting
expectedMessage);
}
private ShouldHaveRootCause(Throwable actual, Throwable actualCause, String expectedCauseMessage) {
super("%n" +
"Expecting a root cause with message:%n" +
" %s%n" +
"but message was:%n" +
" %s." +
"%n" +
"Throwable that failed the check:%n" +
"%n" + escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting
expectedCauseMessage, actualCause.getMessage());
}
}
|
checkArgument(actual != null, "actual should not be null");
checkArgument(expectedCause != null, "expected cause should not be null");
// actualCause has no cause
if (actualCause == null) return new ShouldHaveRootCause(actual, expectedCause);
// same message => different type
if (Objects.equals(actualCause.getMessage(), expectedCause.getMessage()))
return new ShouldHaveRootCause(actual, actualCause, expectedCause.getClass());
// same type => different message
if (Objects.equals(actualCause.getClass(), expectedCause.getClass()))
return new ShouldHaveRootCause(actual, actualCause, expectedCause.getMessage());
return new ShouldHaveRootCause(actual, actualCause, expectedCause);
| 1,006
| 196
| 1,202
|
<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/ShouldHaveRootCauseExactlyInstance.java
|
ShouldHaveRootCauseExactlyInstance
|
shouldHaveRootCauseExactlyInstance
|
class ShouldHaveRootCauseExactlyInstance 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 instance.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldHaveRootCauseExactlyInstance(Throwable actual,
Class<? extends Throwable> expectedCauseType) {<FILL_FUNCTION_BODY>}
private ShouldHaveRootCauseExactlyInstance(Throwable actual, Class<? extends Throwable> expectedCauseType) {
super("%nExpecting a throwable with root cause being exactly an instance of:%n %s%nbut was an instance of:%n %s%n" +
"%nThrowable that failed the check:%n" + escapePercent(getStackTrace(actual)),
expectedCauseType, Throwables.getRootCause(actual).getClass());
}
private ShouldHaveRootCauseExactlyInstance(Class<? extends Throwable> expectedCauseType, Throwable actual) {
super("%nExpecting a throwable with root 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 Throwables.getRootCause(actual) == null
? new ShouldHaveRootCauseExactlyInstance(expectedCauseType, actual)
: new ShouldHaveRootCauseExactlyInstance(actual, expectedCauseType);
| 378
| 61
| 439
|
<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/ShouldHaveRootCauseInstance.java
|
ShouldHaveRootCauseInstance
|
shouldHaveRootCauseInstance
|
class ShouldHaveRootCauseInstance extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link 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 shouldHaveRootCauseInstance(Throwable actual,
Class<? extends Throwable> expectedCauseType) {<FILL_FUNCTION_BODY>}
private ShouldHaveRootCauseInstance(Throwable actual, Class<? extends Throwable> expectedCauseType) {
super("%nExpecting a throwable with root cause being an instance of:%n %s%nbut was an instance of:%n %s%n" +
"%nThrowable that failed the check:%n" + escapePercent(getStackTrace(actual)),
expectedCauseType, Throwables.getRootCause(actual).getClass());
}
private ShouldHaveRootCauseInstance(Class<? extends Throwable> expectedCauseType, Throwable actual) {
super("%nExpecting a throwable with root cause being an instance of:%n %s%nbut current throwable has no cause." +
"%nThrowable that failed the check:%n" + escapePercent(getStackTrace(actual)), expectedCauseType);
}
}
|
return Throwables.getRootCause(actual) == null
? new ShouldHaveRootCauseInstance(expectedCauseType, actual)
: new ShouldHaveRootCauseInstance(actual, expectedCauseType);
| 355
| 55
| 410
|
<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/ShouldHaveSameDimensionsAs.java
|
ShouldHaveSameDimensionsAs
|
shouldHaveSameDimensionsAs
|
class ShouldHaveSameDimensionsAs extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldHaveSameDimensionsAs}</code>.
* @param actual the actual value in the failed assertion.
* @param expected the expected value in the failed assertion.
* @param actualSize the size of {@code actual}.
* @param expectedSize the expected size.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldHaveSameDimensionsAs(Object actual, Object expected, Object actualSize,
Object expectedSize) {
return new ShouldHaveSameDimensionsAs(actual, expected, actualSize, expectedSize);
}
public static ErrorMessageFactory shouldHaveSameDimensionsAs(int rowIndex, int actualRowSize, int expectedRowSize,
Object actualRow, Object expectedRow, Object actual,
Object expected) {<FILL_FUNCTION_BODY>}
private ShouldHaveSameDimensionsAs(Object actual, Object expected, Object actualSize, Object expectedSize) {
// format the sizes in a standard way, otherwise if we use (for ex) an Hexadecimal representation
// it will format sizes in hexadecimal while we only want actual to be formatted in hexadecimal
super(format("%n"
+ "Actual and expected should have same dimensions but actual and expected have different number of rows.%n"
+ "Actual has %s rows while expected has %s.%n"
+ "Actual was:%n"
+ " %s%n"
+ "Expected was:%n"
+ " %s", actualSize, expectedSize, "%s", "%s"),
actual, expected);
}
private ShouldHaveSameDimensionsAs(int rowIndex, int actualRowSize, int expectedRowSize, Object actualRow, Object expectedRow,
Object actual, Object expected) {
// format the sizes in a standard way, otherwise if we use (for ex) an Hexadecimal representation
// it will format sizes in hexadecimal while we only want actual to be formatted in hexadecimal
super(format("%n"
+ "Actual and expected should have same dimensions but rows at index %d don't have the same size.%n"
+ "Actual row size is %d while expected row size is %d%n"
+ "Actual row was:%n"
+ " %s%n"
+ "Expected row was:%n"
+ " %s%n"
+ "Actual was:%n"
+ " %s%n"
+ "Expected was:%n"
+ " %s",
rowIndex, actualRowSize, expectedRowSize, "%s", "%s", "%s", "%s"),
actualRow, expectedRow, actual, expected);
}
}
|
return new ShouldHaveSameDimensionsAs(rowIndex, actualRowSize, expectedRowSize, actualRow, expectedRow, actual, expected);
| 683
| 35
| 718
|
<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/ShouldHaveSuperclass.java
|
ShouldHaveSuperclass
|
shouldHaveSuperclass
|
class ShouldHaveSuperclass extends BasicErrorMessageFactory {
private static final String SHOULD_HAVE_SUPERCLASS = new StringJoiner("%n", "%n", "").add("Expecting")
.add(" %s")
.add("to have superclass:")
.add(" %s")
.toString();
private static final String BUT_HAD_NONE = new StringJoiner("%n", "%n", "").add("but had none.")
.toString();
private static final String BUT_HAD = new StringJoiner("%n", "%n", "").add("but had:")
.add(" %s")
.toString();
/**
* Creates a new <code>{@link ShouldHaveSuperclass}</code>.
*
* @param actual the actual value in the failed assertion.
* @param superclass expected superclass for this class.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldHaveSuperclass(Class<?> actual, Class<?> superclass) {<FILL_FUNCTION_BODY>}
private ShouldHaveSuperclass(Class<?> actual, Class<?> expectedSuperclass) {
super(SHOULD_HAVE_SUPERCLASS + BUT_HAD_NONE, actual, expectedSuperclass);
}
private ShouldHaveSuperclass(Class<?> actual, Class<?> expectedSuperclass, Class<?> actualSuperclass) {
super(SHOULD_HAVE_SUPERCLASS + BUT_HAD, actual, expectedSuperclass, actualSuperclass);
}
}
|
Class<?> actualSuperclass = actual.getSuperclass();
return (actualSuperclass == null)
? new ShouldHaveSuperclass(actual, superclass)
: new ShouldHaveSuperclass(actual, superclass, actualSuperclass);
| 414
| 61
| 475
|
<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/ShouldMatch.java
|
ShouldMatch
|
shouldMatch
|
class ShouldMatch extends BasicErrorMessageFactory {
// @format:off
public static final String ADVICE = format("%n%n"+
"You can use 'matches(Predicate p, String description)' to have a better error message%n" +
"For example:%n" +
" assertThat(player).matches(p -> p.isRookie(), \"is rookie\");%n" +
"will give an error message looking like:%n" +
"%n" +
"Expecting actual:%n" +
" player%n" +
"to match 'is rookie' predicate");
// @format:on
/**
* Creates a new <code>{@link ShouldMatch}</code>.
*
* @param <T> guarantees that the type of the actual value and the generic type of the {@code Predicate} are the same.
* @param actual the actual value in the failed assertion.
* @param predicate the {@code Predicate}.
* @param predicateDescription predicate description to include in the error message
* @return the created {@code ErrorMessageFactory}.
*/
public static <T> ErrorMessageFactory shouldMatch(T actual, Predicate<? super T> predicate,
PredicateDescription predicateDescription) {<FILL_FUNCTION_BODY>}
private ShouldMatch(Object actual, PredicateDescription description) {
super("%nExpecting actual:%n %s%nto match %s predicate." + (description.isDefault() ? ADVICE : ""), actual, description);
}
}
|
requireNonNull(predicateDescription, "The predicate description must not be null");
return new ShouldMatch(actual, predicateDescription);
| 398
| 34
| 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/ShouldNotAccept.java
|
ShouldNotAccept
|
shouldNotAccept
|
class ShouldNotAccept extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldNotAccept}</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 shouldNotAccept(Predicate<? super T> predicate, T value,
PredicateDescription description) {<FILL_FUNCTION_BODY>}
private ShouldNotAccept(Object value, PredicateDescription description) {
super("%nExpecting actual:%n %s predicate%nnot to accept %s but it did.", description, value);
}
}
|
requireNonNull(description, "The predicate description must not be null");
return new ShouldNotAccept(value, description);
| 228
| 32
| 260
|
<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/ShouldNotBeEmpty.java
|
ShouldNotBeEmpty
|
shouldNotBeEmpty
|
class ShouldNotBeEmpty extends BasicErrorMessageFactory {
private static final ShouldNotBeEmpty INSTANCE = new ShouldNotBeEmpty("%nExpecting actual not to be empty");
/**
* Returns the singleton instance of this class.
* @return the singleton instance of this class.
*/
public static ErrorMessageFactory shouldNotBeEmpty() {
return INSTANCE;
}
/**
* Creates a new <code>{@link ShouldNotBeEmpty}</code>.
* @param actual the actual file in the failed assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotBeEmpty(File actual) {
return new ShouldNotBeEmpty("%nExpecting file %s not to be empty", actual);
}
/**
* Creates a new <code>{@link ShouldNotBeEmpty}</code>.
* @param actual the actual path in the failed assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotBeEmpty(Path actual) {<FILL_FUNCTION_BODY>}
private ShouldNotBeEmpty(String format, Object... arguments) {
super(format, arguments);
}
}
|
return new ShouldNotBeEmpty("%nExpecting path %s not to be empty", actual);
| 311
| 26
| 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/ShouldNotBeEqualComparingFieldByFieldRecursively.java
|
ShouldNotBeEqualComparingFieldByFieldRecursively
|
shouldNotBeEqualComparingFieldByFieldRecursively
|
class ShouldNotBeEqualComparingFieldByFieldRecursively extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldNotBeEqualComparingFieldByFieldRecursively(Object actual, Object other,
RecursiveComparisonConfiguration recursiveComparisonConfiguration,
Representation representation) {
String recursiveComparisonConfigurationDescription = recursiveComparisonConfiguration.multiLineDescription(representation);
return new ShouldNotBeEqualComparingFieldByFieldRecursively("%n" +
"Expecting actual:%n" +
" %s%n" +
"not to be equal to:%n" +
" %s%n" +
"when recursively comparing field by field" +
"%n" +
"The recursive comparison was performed with this configuration:%n"
+
recursiveComparisonConfigurationDescription, // don't use %s
// to avoid AssertJ
// formatting String
// with ""
actual, other);
}
public static ErrorMessageFactory shouldNotBeEqualComparingFieldByFieldRecursively(Object actual) {<FILL_FUNCTION_BODY>}
private ShouldNotBeEqualComparingFieldByFieldRecursively(String message, Object... arguments) {
super(message, arguments);
}
}
|
if (actual == null)
return new ShouldNotBeEqualComparingFieldByFieldRecursively("%n" +
"Expecting actual not to be equal to other but both are null.");
return new ShouldNotBeEqualComparingFieldByFieldRecursively("%n" +
"Expecting actual not to be equal to other but both refer to the same object (actual == other):%n"
+ " %s%n", actual);
| 321
| 111
| 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/ShouldNotBeEqualWithinPercentage.java
|
ShouldNotBeEqualWithinPercentage
|
shouldNotBeEqualWithinPercentage
|
class ShouldNotBeEqualWithinPercentage extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldNotBeEqualWithinPercentage}</code>.
*
* @param <T> the type of the actual value and the type of values that given {@code Condition} takes.
* @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 shouldNotBeEqualWithinPercentage(T actual, T expected,
Percentage percentage,
T difference) {<FILL_FUNCTION_BODY>}
private ShouldNotBeEqualWithinPercentage(Number actual, Number expected, Percentage percentage, double expectedPercentage) {
super("%nExpecting actual:%n" +
" %s%n" +
"not to be close to:%n" +
" %s%n" +
"by more than %s but difference was %s%%.%n" +
"(a difference of exactly %s being considered incorrect)",
actual, expected, percentage, expectedPercentage, percentage);
}
}
|
double expectedPercentage = difference.doubleValue() / expected.doubleValue() * 100d;
return new ShouldNotBeEqualWithinPercentage(actual, expected, percentage, expectedPercentage);
| 335
| 54
| 389
|
<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/ShouldNotBeExactlyInstanceOf.java
|
ShouldNotBeExactlyInstanceOf
|
shouldNotBeExactlyInstance
|
class ShouldNotBeExactlyInstanceOf extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldNotBeExactlyInstanceOf}</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 shouldNotBeExactlyInstance(Object actual, Class<?> type) {<FILL_FUNCTION_BODY>}
private ShouldNotBeExactlyInstanceOf(Object actual, Class<?> type) {
super("%nExpecting%n %s%nnot to be of exact type:%n %s", actual, type);
}
private ShouldNotBeExactlyInstanceOf(Throwable throwable, Class<?> type) {
super("%nExpecting%n %s%nnot to be of exact type:%n %s", getStackTrace(throwable), type);
}
}
|
return actual instanceof Throwable ? new ShouldNotBeExactlyInstanceOf((Throwable) actual, type)
: new ShouldNotBeExactlyInstanceOf(actual, type);
| 256
| 46
| 302
|
<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/ShouldNotBeInstance.java
|
ShouldNotBeInstance
|
shouldNotBeInstance
|
class ShouldNotBeInstance extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldNotBeInstance}</code>.
* @param actual the actual value in the failed assertion.
* @param type the type {@code actual} is expected to belong to.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotBeInstance(Object actual, Class<?> type) {<FILL_FUNCTION_BODY>}
private ShouldNotBeInstance(Object actual, Class<?> type) {
super("%nExpecting actual:%n %s%nnot to be an instance of: %s", actual, type);
}
private ShouldNotBeInstance(Throwable throwable, Class<?> type) {
super("%nExpecting actual:%n %s%nnot to be an instance of: %s", getStackTrace(throwable), type);
}
}
|
return actual instanceof Throwable ? new ShouldNotBeInstance((Throwable) actual, type)
: new ShouldNotBeInstance(actual, type);
| 236
| 38
| 274
|
<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/ShouldNotBeInstanceOfAny.java
|
ShouldNotBeInstanceOfAny
|
shouldNotBeInstanceOfAny
|
class ShouldNotBeInstanceOfAny extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldNotBeInstanceOfAny}</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 shouldNotBeInstanceOfAny(Object actual, Class<?>[] types) {<FILL_FUNCTION_BODY>}
private ShouldNotBeInstanceOfAny(Object actual, Class<?>[] types) {
super("%nExpecting actual:%n %s%nnot to be an instance of any of these types:%n %s", actual, types);
}
private ShouldNotBeInstanceOfAny(Throwable throwable, Class<?>[] types) {
super("%nExpecting actual:%n %s%nnot to be an instance of any of these types:%n %s", getStackTrace(throwable), types);
}
}
|
return actual instanceof Throwable ? new ShouldNotBeInstanceOfAny((Throwable) actual, types)
: new ShouldNotBeInstanceOfAny(actual, types);
| 266
| 42
| 308
|
<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/ShouldNotBeNull.java
|
ShouldNotBeNull
|
shouldNotBeNull
|
class ShouldNotBeNull extends BasicErrorMessageFactory {
private static final ShouldNotBeNull INSTANCE = new ShouldNotBeNull("%nExpecting actual not to be null");
/**
* Returns the default instance of this class.
* @return the default instance of this class.
*/
public static ErrorMessageFactory shouldNotBeNull() {
return INSTANCE;
}
/**
* Create a instance specifying a label
* @param label of what should not be null
* @return the new instance
*/
public static ShouldNotBeNull shouldNotBeNull(String label) {<FILL_FUNCTION_BODY>}
private ShouldNotBeNull(String label) {
super(label);
}
}
|
return new ShouldNotBeNull(format("%nExpecting %s not to be null", label));
| 186
| 27
| 213
|
<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/ShouldNotContainCharSequence.java
|
ShouldNotContainCharSequence
|
shouldNotContainIgnoringCase
|
class ShouldNotContainCharSequence extends BasicErrorMessageFactory {
private ShouldNotContainCharSequence(String format, CharSequence actual, CharSequence sequence,
ComparisonStrategy comparisonStrategy) {
super(format, actual, sequence, comparisonStrategy);
}
private ShouldNotContainCharSequence(String format, CharSequence actual, CharSequence[] values,
Set<? extends CharSequence> found,
ComparisonStrategy comparisonStrategy) {
super(format, actual, values, found, comparisonStrategy);
}
/**
* Creates a new <code>{@link ShouldNotContainCharSequence}</code>.
* @param actual the actual value in the failed assertion.
* @param sequence the charsequence expected not to be in {@code actual}.
* @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotContain(CharSequence actual, CharSequence sequence,
ComparisonStrategy comparisonStrategy) {
return new ShouldNotContainCharSequence("%n" +
"Expecting actual:%n" +
" %s%n" +
"not to contain:%n" +
" %s%n" +
"%s",
actual, sequence, comparisonStrategy);
}
public static ErrorMessageFactory shouldNotContain(CharSequence actual, CharSequence sequence) {
return shouldNotContain(actual, sequence, StandardComparisonStrategy.instance());
}
/**
* Creates a new <code>{@link ShouldNotContainCharSequence}</code>
* @param actual the actual value in the failed assertion.
* @param values the charsequences expected not to be in {@code actual}.
* @param found the charsequences unexpectedly in {@code actual}.
* @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotContain(CharSequence actual, CharSequence[] values,
Set<? extends CharSequence> found,
ComparisonStrategy comparisonStrategy) {
return new ShouldNotContainCharSequence("%n" +
"Expecting actual:%n" +
" %s%n" +
"not to contain:%n" +
" %s%n" +
"but found:%n" +
" %s%n" +
"%s",
actual, values, found, comparisonStrategy);
}
/**
* Creates a new <code>{@link ShouldContainCharSequence}</code>.
*
* @param actual the actual value in the failed assertion.
* @param sequence the sequence of values expected to be in {@code actual}, ignoring case
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotContainIgnoringCase(CharSequence actual, CharSequence sequence) {
return new ShouldNotContainCharSequence("%n" +
"Expecting actual:%n" +
" %s%n" +
"not to contain (ignoring case):%n" +
" %s%n" +
"%s",
actual, sequence, StandardComparisonStrategy.instance());
}
public static ErrorMessageFactory shouldNotContainIgnoringCase(CharSequence actual, CharSequence[] sequences,
Set<CharSequence> foundSequences) {<FILL_FUNCTION_BODY>}
}
|
return new ShouldNotContainCharSequence("%n" +
"Expecting actual:%n" +
" %s%n" +
"not to contain (ignoring case):%n" +
" %s%n" +
"but found:%n" +
" %s%n" +
"%s",
actual, sequences, foundSequences, StandardComparisonStrategy.instance());
| 857
| 106
| 963
|
<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/ShouldNotContainKeys.java
|
ShouldNotContainKeys
|
shouldNotContainKeys
|
class ShouldNotContainKeys extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldNotContainKeys}</code>.
*
* @param <K> key type
* @param actual the actual value in the failed assertion.
* @param keys the unexpected keys
* @return the created {@code ErrorMessageFactory}.
*/
public static <K> ErrorMessageFactory shouldNotContainKeys(Object actual, Set<K> keys) {<FILL_FUNCTION_BODY>}
private <K> ShouldNotContainKeys(Object actual, Set<K> key) {
super("%nExpecting actual:%n %s%nnot to contain keys:%n %s", actual, key);
}
}
|
if (keys.size() == 1) return shouldNotContainKey(actual, keys.iterator().next());
return new ShouldNotContainKeys(actual, keys);
| 191
| 43
| 234
|
<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/ShouldNotMatch.java
|
ShouldNotMatch
|
shouldNotMatch
|
class ShouldNotMatch extends BasicErrorMessageFactory {
// @format:off
public static final String ADVICE = format("%n%n"+
"You can use 'doesNotMatch(Predicate p, String description)' to have a better error message%n" +
"For example:%n" +
" assertThat(player).doesNotMatch(p -> p.isRookie(), \"is not rookie\");%n" +
"will give an error message looking like:%n" +
"%n" +
"Expecting actual:%n" +
" player%n" +
"not to match 'is not rookie' predicate");
// @format:on
/**
* Creates a new <code>{@link ShouldNotMatch}</code>.
*
* @param <T> guarantees that the type of the actual value and the generic type of the {@code Predicate} are the same.
* @param actual the actual value in the failed assertion.
* @param predicate the {@code Predicate}.
* @param predicateDescription predicate description to include in the error message
* @return the created {@code ErrorMessageFactory}.
*/
public static <T> ErrorMessageFactory shouldNotMatch(T actual, Predicate<? super T> predicate,
PredicateDescription predicateDescription) {<FILL_FUNCTION_BODY>}
private ShouldNotMatch(Object actual, PredicateDescription description) {
super("%nExpecting actual:%n %s%nnot to match %s predicate." + (description.isDefault() ? ADVICE : ""), actual, description);
}
}
|
requireNonNull(predicateDescription, "The predicate description must not be null");
return new ShouldNotMatch(actual, predicateDescription);
| 407
| 35
| 442
|
<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/ShouldNotSatisfyPredicateRecursively.java
|
ShouldNotSatisfyPredicateRecursively
|
shouldNotSatisfyRecursively
|
class ShouldNotSatisfyPredicateRecursively extends BasicErrorMessageFactory {
private static final String INDENT = " ";
private static final String NEW_LINE = format("%n");
public static ErrorMessageFactory shouldNotSatisfyRecursively(RecursiveAssertionConfiguration recursiveAssertionConfiguration,
List<FieldLocation> failedFields) {<FILL_FUNCTION_BODY>}
private ShouldNotSatisfyPredicateRecursively(String message) {
super(message);
}
}
|
List<String> fieldsDescription = failedFields.stream().map(FieldLocation::getPathToUseInErrorReport).collect(toList());
StringBuilder builder = new StringBuilder(NEW_LINE);
builder.append("The following fields did not satisfy the predicate:").append(NEW_LINE);
builder.append(INDENT + fieldsDescription.toString() + NEW_LINE);
builder.append("The recursive assertion was performed with this configuration:").append(NEW_LINE);
builder.append(recursiveAssertionConfiguration);
return new ShouldNotSatisfyPredicateRecursively(builder.toString());
| 130
| 145
| 275
|
<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/ShouldOnlyHaveElementsOfTypes.java
|
ShouldOnlyHaveElementsOfTypes
|
resolveClassNames
|
class ShouldOnlyHaveElementsOfTypes extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldOnlyHaveElementsOfTypes}</code>.
*
* @param actual the object value in the failed assertion.
* @param types the expected classes and interfaces.
* @param mismatches elements that are not an instance of one of the given types.
* @return the created {@code ErrorMessageFactory}.
*/
public static ShouldOnlyHaveElementsOfTypes shouldOnlyHaveElementsOfTypes(Object actual, Class<?>[] types,
Iterable<?> mismatches) {
return new ShouldOnlyHaveElementsOfTypes(actual, types, mismatches);
}
private ShouldOnlyHaveElementsOfTypes(Object actual, Class<?>[] types, Iterable<?> nonMatchingElements) {
super("%n" +
"Expecting actual:%n" +
" %s%n" +
"to only have instances of:%n" +
" %s%n" +
"but these elements are not:%n" +
" [" + resolveClassNames(nonMatchingElements) + "]",
actual, types);
}
private static String resolveClassNames(Iterable<?> elements) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder();
for (Object element : elements) {
if (builder.length() > 0) {
builder.append(", ");
}
String formatted = CONFIGURATION_PROVIDER.representation().toStringOf(element);
builder.append(formatted);
if (element != null && !formatted.contains(element.getClass().getName())) {
builder.append(" (").append(element.getClass().getName()).append(")");
}
}
return builder.toString();
| 330
| 138
| 468
|
<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/ShouldOnlyHaveFields.java
|
ShouldOnlyHaveFields
|
create
|
class ShouldOnlyHaveFields extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldOnlyHaveFields}</code>.
*
* @param actual the actual value in the failed assertion.
* @param expected expected fields for this class
* @param notFound fields in {@code expected} not found in the {@code actual}.
* @param notExpected fields in the {@code actual} that were not in {@code expected}.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldOnlyHaveFields(Class<?> actual, Collection<String> expected,
Collection<String> notFound,
Collection<String> notExpected) {
return create(actual, expected, notFound, notExpected, false);
}
/**
* Creates a new <code>{@link ShouldOnlyHaveFields}</code>.
*
* @param actual the actual value in the failed assertion.
* @param expected expected fields for this class
* @param notFound fields in {@code expected} not found in the {@code actual}.
* @param notExpected fields in the {@code actual} that were not in {@code expected}.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldOnlyHaveDeclaredFields(Class<?> actual, Collection<String> expected,
Collection<String> notFound,
Collection<String> notExpected) {
return create(actual, expected, notFound, notExpected, true);
}
private static ErrorMessageFactory create(Class<?> actual, Collection<String> expected, Collection<String> notFound,
Collection<String> notExpected, boolean declared) {<FILL_FUNCTION_BODY>}
private ShouldOnlyHaveFields(Class<?> actual, Collection<String> expected, Collection<String> notFound,
Collection<String> notExpected,
boolean declared) {
super("%n" +
"Expecting%n" +
" %s%n" +
"to only have the following " + (declared ? "declared" : "public accessible") + " fields:%n" +
" %s%n" +
"fields not found:%n" +
" %s%n" +
"and fields not expected:%n" +
" %s", actual, expected, notFound, notExpected);
}
private ShouldOnlyHaveFields(Class<?> actual, Collection<String> expected,
Collection<String> notFoundOrNotExpected,
ErrorType errorType, boolean declared) {
super("%n" +
"Expecting%n" +
" %s%n" +
"to only have the following " + (declared ? "declared" : "public accessible") + " fields:%n" +
" %s%n" +
(errorType == NOT_FOUND_ONLY ? "but could not find the following fields:%n"
: "but the following fields were unexpected:%n")
+
" %s",
actual, expected, notFoundOrNotExpected);
}
enum ErrorType {
NOT_FOUND_ONLY, NOT_EXPECTED_ONLY
}
}
|
if (isNullOrEmpty(notExpected)) {
return new ShouldOnlyHaveFields(actual, expected, notFound, NOT_FOUND_ONLY, declared);
}
if (isNullOrEmpty(notFound)) {
return new ShouldOnlyHaveFields(actual, expected, notExpected, NOT_EXPECTED_ONLY, declared);
}
return new ShouldOnlyHaveFields(actual, expected, notFound, notExpected, declared);
| 795
| 111
| 906
|
<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/ShouldSatisfyOnlyOnce.java
|
ShouldSatisfyOnlyOnce
|
shouldSatisfyOnlyOnce
|
class ShouldSatisfyOnlyOnce extends BasicErrorMessageFactory {
private static final String NO_ELEMENT_SATISFIED_REQUIREMENTS = "%nExpecting exactly one element of actual:%n" +
" %s%n" +
"to satisfy the requirements but none did";
// @format:off
private static final String MORE_THAN_ONE_ELEMENT_SATISFIED_REQUIREMENTS = "%n" +
"Expecting exactly one element of actual:%n" +
" %s%n" +
"to satisfy the requirements but these %s elements did:%n" +
" %s";
// @format:on
/**
* Creates a new <code>{@link ShouldSatisfyOnlyOnce}</code>.
*
* @param <E> the iterable elements type.
* @param actual the actual iterable in the failed assertion.
* @param satisfiedElements the elements which satisfied the requirement
* @return the created {@link ErrorMessageFactory}.
*/
public static <E> ErrorMessageFactory shouldSatisfyOnlyOnce(Iterable<? extends E> actual, List<? extends E> satisfiedElements) {<FILL_FUNCTION_BODY>}
private ShouldSatisfyOnlyOnce(Iterable<?> actual) {
super(NO_ELEMENT_SATISFIED_REQUIREMENTS, actual);
}
private ShouldSatisfyOnlyOnce(Iterable<?> actual, List<?> satisfiedElements) {
super(MORE_THAN_ONE_ELEMENT_SATISFIED_REQUIREMENTS, actual, satisfiedElements.size(), satisfiedElements);
}
}
|
return satisfiedElements.isEmpty() ? new ShouldSatisfyOnlyOnce(actual) : new ShouldSatisfyOnlyOnce(actual, satisfiedElements);
| 430
| 36
| 466
|
<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/SubarraysShouldHaveSameSize.java
|
SubarraysShouldHaveSameSize
|
subarraysShouldHaveSameSize
|
class SubarraysShouldHaveSameSize extends BasicErrorMessageFactory {
private static final String MESSAGE = "%n" +
"actual and expected 2d arrays should be deeply equal but rows at index %s differ:%n" +
"actual[%s] size is %s and expected[%s] is %s.%n" +
"actual[%s] was:%n" +
" %s%n" +
"expected[%s] was:%n" +
" %s%n" +
"actual was:%n" +
" %s%n" +
"expected was:%n" +
" %s";
/**
* Creates a new <code>{@link SubarraysShouldHaveSameSize}</code>.
* @param actual the actual 2D array in the failed assertion.
* @param expected the actual 2D array to compare actual with.
* @param actualSubArray actual[index] array
* @param actualSubArrayLength actual[index] lentgth
* @param expectedSubArray expected[index]
* @param expectedSubArrayLength actual[index] lentgth
* @param index index of {@code actualSubArray}, e.g. {@code 3} when checking size (length) of {@code actual[3]}
* @return the created {@code ErrorMessageFactory}
*/
public static ErrorMessageFactory subarraysShouldHaveSameSize(Object actual, Object expected, Object actualSubArray,
int actualSubArrayLength, Object expectedSubArray,
int expectedSubArrayLength, int index) {<FILL_FUNCTION_BODY>}
private SubarraysShouldHaveSameSize(Object actual, Object expected, Object actualSubArray, int actualSubArrayLength,
Object expectedSubArray, int expectedSubArrayLength, int index) {
// reuse %s to let representation format the arrays but don't do it for integers as we want to keep the default toString of
// int (that would mot be the case if the representation was changed to hex representation for example).
super(format(MESSAGE, index, index, actualSubArrayLength, index, expectedSubArrayLength, index, "%s", index, "%s", "%s",
"%s"),
actualSubArray, expectedSubArray, actual, expected);
}
}
|
return new SubarraysShouldHaveSameSize(actual, expected, actualSubArray, actualSubArrayLength, expectedSubArray,
expectedSubArrayLength, index);
| 568
| 42
| 610
|
<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/UnsatisfiedRequirement.java
|
UnsatisfiedRequirement
|
describe
|
class UnsatisfiedRequirement {
private final Object elementNotSatisfyingRequirements;
private final String errorMessage;
public UnsatisfiedRequirement(Object elementNotSatisfyingRequirements, String errorMessage) {
this.elementNotSatisfyingRequirements = elementNotSatisfyingRequirements;
this.errorMessage = errorMessage;
}
public String describe(AssertionInfo info) {
return format("%s%nerror: %s", info.representation().toStringOf(elementNotSatisfyingRequirements), errorMessage);
}
@Override
public String toString() {
return format("%s %s", elementNotSatisfyingRequirements, errorMessage);
}
public String describe(int index, AssertionInfo info) {<FILL_FUNCTION_BODY>}
}
|
return format("%s%n" +
"- element index: %s%n" +
"- error: %s",
info.representation().toStringOf(elementNotSatisfyingRequirements), index, errorMessage);
| 201
| 56
| 257
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/error/ZippedElementsShouldSatisfy.java
|
ZippedElementsShouldSatisfy
|
describe
|
class ZippedElementsShouldSatisfy extends BasicErrorMessageFactory {
private static final String DELIMITER = String.format("%n%n- ");
public static ErrorMessageFactory zippedElementsShouldSatisfy(AssertionInfo info,
Iterable<?> actual, Iterable<?> other,
List<ZipSatisfyError> zipSatisfyErrors) {
return new ZippedElementsShouldSatisfy(info, actual, other, zipSatisfyErrors);
}
private ZippedElementsShouldSatisfy(AssertionInfo info, Iterable<?> actual, Iterable<?> other,
List<ZipSatisfyError> zipSatisfyErrors) {
// no use of %s for describe(zipSatisfyErrors) to avoid extra "" but need to make sure there is no extra/unwanted format flag
super("%n" +
"Expecting zipped elements of:%n" +
" %s%n" +
"and:%n" +
" %s%n" +
"to satisfy given requirements but these zipped elements did not:" + describe(info, zipSatisfyErrors),
actual, other);
}
private static String describe(AssertionInfo info, List<ZipSatisfyError> zipSatisfyErrors) {<FILL_FUNCTION_BODY>}
public static class ZipSatisfyError {
public final Object actualElement;
public final Object otherElement;
public final String error;
public ZipSatisfyError(Object actualElement, Object otherElement, String error) {
this.actualElement = actualElement;
this.otherElement = otherElement;
this.error = error;
}
public static String describe(AssertionInfo info, ZipSatisfyError satisfyError) {
return String.format("(%s, %s)%nerror: %s",
info.representation().toStringOf(satisfyError.actualElement),
info.representation().toStringOf(satisfyError.otherElement),
satisfyError.error);
}
@Override
public String toString() {
return String.format("(%s, %s)%nerror: %s", actualElement, otherElement, error);
}
}
}
|
List<String> errorsToStrings = zipSatisfyErrors.stream()
.map(error -> ZipSatisfyError.describe(info, error))
.collect(toList());
return escapePercent(DELIMITER + String.join(DELIMITER, errorsToStrings));
| 562
| 80
| 642
|
<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/future/ShouldBeCompletedWithin.java
|
ShouldBeCompletedWithin
|
toChronoUnit
|
class ShouldBeCompletedWithin extends BasicErrorMessageFactory {
private static final String SHOULD_BE_COMPLETED_WITHIN_DURATION = "%n"
+ "Expecting%n"
+ " <%s>%n"
+ "to be completed within %s.%n%n"
+ "exception caught while trying to get the future result: ";
private static final String SHOULD_BE_COMPLETED_WITHIN = "%n"
+ "Expecting%n"
+ " <%s>%n"
+ "to be completed within %s %s.%n%n"
+ "exception caught while trying to get the future result: ";
public static ErrorMessageFactory shouldBeCompletedWithin(Future<?> actual, Duration duration, Exception exception) {
return new ShouldBeCompletedWithin(actual, duration, exception);
}
public static ErrorMessageFactory shouldBeCompletedWithin(Future<?> actual, long timeout, TimeUnit timeUnit,
Exception exception) {
return new ShouldBeCompletedWithin(actual, timeout, timeUnit, exception);
}
private ShouldBeCompletedWithin(Future<?> actual, Duration duration, Exception exception) {
// don't put the stack trace as a parameter to avoid AssertJ default String formatting
super(SHOULD_BE_COMPLETED_WITHIN_DURATION + escapePercent(getStackTrace(exception)), actual, duration);
}
private ShouldBeCompletedWithin(Future<?> actual, long timeout, TimeUnit timeUnit, Exception exception) {
// don't put the stack trace as a parameter to avoid AssertJ default String formatting
// ChronoUnit toString looks better than TimeUnit
super(SHOULD_BE_COMPLETED_WITHIN + escapePercent(getStackTrace(exception)), actual, timeout, toChronoUnit(timeUnit));
}
// copied from java 9 code
private static ChronoUnit toChronoUnit(TimeUnit timeUnit) {<FILL_FUNCTION_BODY>}
}
|
switch (timeUnit) {
case NANOSECONDS:
return ChronoUnit.NANOS;
case MICROSECONDS:
return ChronoUnit.MICROS;
case MILLISECONDS:
return ChronoUnit.MILLIS;
case SECONDS:
return ChronoUnit.SECONDS;
case MINUTES:
return ChronoUnit.MINUTES;
case HOURS:
return ChronoUnit.HOURS;
case DAYS:
return ChronoUnit.DAYS;
default:
throw new AssertionError();
}
| 524
| 160
| 684
|
<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/uri/ShouldHaveAnchor.java
|
ShouldHaveAnchor
|
shouldHaveAnchor
|
class ShouldHaveAnchor extends BasicErrorMessageFactory {
private static final String SHOULD_HAVE_ANCHOR = "%nExpecting anchor of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>";
private static final String SHOULD_NOT_HAVE_ANCHOR = "%nExpecting actual:%n <%s>%nnot to have an anchor but had:%n <%s>";
public static ErrorMessageFactory shouldHaveAnchor(URL actual, String expectedAnchor) {<FILL_FUNCTION_BODY>}
private ShouldHaveAnchor(URL actual, String expectedAnchor) {
super(SHOULD_HAVE_ANCHOR, actual, expectedAnchor, actual.getRef());
}
private ShouldHaveAnchor(URL actual) {
super(SHOULD_NOT_HAVE_ANCHOR, actual, actual.getRef());
}
}
|
return expectedAnchor == null ? new ShouldHaveAnchor(actual) : new ShouldHaveAnchor(actual, expectedAnchor);
| 243
| 33
| 276
|
<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/uri/ShouldHaveFragment.java
|
ShouldHaveFragment
|
shouldHaveFragment
|
class ShouldHaveFragment extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldHaveFragment(URI actual, String expectedFragment) {<FILL_FUNCTION_BODY>}
private ShouldHaveFragment(URI actual, String expectedFragment) {
super("%nExpecting fragment of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>", actual, expectedFragment,
actual.getFragment());
}
private ShouldHaveFragment(URI actual) {
super("%nExpecting URI:%n <%s>%nnot to have a fragment but had:%n <%s>", actual, actual.getFragment());
}
}
|
return expectedFragment == null ? new ShouldHaveFragment(actual) : new ShouldHaveFragment(actual, expectedFragment);
| 170
| 29
| 199
|
<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/uri/ShouldHaveParameter.java
|
ShouldHaveParameter
|
shouldHaveNoParameters
|
class ShouldHaveParameter extends BasicErrorMessageFactory {
private static final String SHOULD_HAVE_PARAMETER_BUT_WAS_MISSING = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nbut was missing";
private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_PARAMETER_WAS_MISSING = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter was missing";
private static final String SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_PARAMETER_WAS_MISSING = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut parameter was missing";
private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUE = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter had value:%n <%s>";
private static final String SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUES = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith no value, but parameter had values:%n <%s>";
private static final String SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_HAD_NO_VALUE = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut parameter had no value";
private static final String SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUE = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut had value:%n <%s>";
private static final String SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUES = "%nExpecting actual:%n <%s>%nto have parameter:%n <%s>%nwith value:%n <%s>%nbut had values:%n <%s>";
private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_WITHOUT_VALUE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with no value";
private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_VALUE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with value:%n <%s>";
private static final String SHOULD_HAVE_NO_PARAMETER_BUT_HAD_MULTIPLE_VALUES = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nbut parameter was present with values:%n <%s>";
private static final String SHOULD_HAVE_NO_PARAMETER_WITHOUT_VALUE_BUT_FOUND_ONE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nwith no value, but did";
private static final String SHOULD_HAVE_NO_PARAMETER_WITH_GIVEN_VALUE_BUT_FOUND_ONE = "%nExpecting actual:%n <%s>%nnot to have parameter:%n <%s>%nwith value:%n <%s>%nbut did";
private static final String SHOULD_HAVE_NO_PARAMETERS = "%nExpecting actual:%n <%s>%nnot to have any parameters but found:%n <%s>";
public static ErrorMessageFactory shouldHaveParameter(Object actual, String name) {
return new ShouldHaveParameter(SHOULD_HAVE_PARAMETER_BUT_WAS_MISSING, actual, name);
}
public static ErrorMessageFactory shouldHaveParameter(Object actual, String name, String expectedValue) {
if (expectedValue == null)
return new ShouldHaveParameter(SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_PARAMETER_WAS_MISSING, actual, name);
return new ShouldHaveParameter(SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_PARAMETER_WAS_MISSING, actual, name,
expectedValue);
}
public static ErrorMessageFactory shouldHaveParameter(Object actual, String name, String expectedValue,
List<String> actualValues) {
if (expectedValue == null)
return new ShouldHaveParameter(multipleValues(actualValues) ? SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUES
: SHOULD_HAVE_PARAMETER_WITHOUT_VALUE_BUT_HAD_VALUE, actual, name, valueDescription(actualValues));
if (noValueIn(actualValues))
return new ShouldHaveParameter(SHOULD_HAVE_PARAMETER_WITH_VALUE_BUT_HAD_NO_VALUE, actual, name, expectedValue);
return new ShouldHaveParameter(multipleValues(actualValues) ? SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUES
: SHOULD_HAVE_PARAMETER_VALUE_BUT_HAD_WRONG_VALUE, actual, name, expectedValue, valueDescription(actualValues));
}
public static ErrorMessageFactory shouldHaveNoParameters(Object actual, Set<String> parameterNames) {<FILL_FUNCTION_BODY>}
public static ErrorMessageFactory shouldHaveNoParameter(Object actual, String name, List<String> actualValues) {
return noValueIn(actualValues)
? new ShouldHaveParameter(SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_WITHOUT_VALUE, actual, name)
: new ShouldHaveParameter(multipleValues(actualValues) ? SHOULD_HAVE_NO_PARAMETER_BUT_HAD_MULTIPLE_VALUES
: SHOULD_HAVE_NO_PARAMETER_BUT_HAD_ONE_VALUE, actual, name, valueDescription(actualValues));
}
public static ErrorMessageFactory shouldHaveNoParameter(Object actual, String name, String unwantedValue,
List<String> actualValues) {
if (noValueIn(actualValues))
return new ShouldHaveParameter(SHOULD_HAVE_NO_PARAMETER_WITHOUT_VALUE_BUT_FOUND_ONE, actual, name);
return new ShouldHaveParameter(SHOULD_HAVE_NO_PARAMETER_WITH_GIVEN_VALUE_BUT_FOUND_ONE, actual, name,
unwantedValue);
}
private static boolean noValueIn(List<String> actualValues) {
return actualValues == null || (actualValues.size() == 1 && actualValues.contains(null));
}
private static String valueDescription(List<String> actualValues) {
return multipleValues(actualValues) ? actualValues.toString() : actualValues.get(0);
}
private static boolean multipleValues(List<String> values) {
return values.size() > 1;
}
private ShouldHaveParameter(String format, Object... arguments) {
super(format, arguments);
}
}
|
String parametersDescription = parameterNames.size() == 1 ? parameterNames.iterator().next()
: parameterNames.toString();
return new ShouldHaveParameter(SHOULD_HAVE_NO_PARAMETERS, actual, parametersDescription);
| 1,947
| 59
| 2,006
|
<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/uri/ShouldHavePath.java
|
ShouldHavePath
|
shouldHavePath
|
class ShouldHavePath extends BasicErrorMessageFactory {
private static final String SHOULD_NOT_HAVE_PATH = "%nExpecting actual:%n <%s>%nnot to have a path but had:%n <%s>";
private static final String SHOULD_HAVE_PATH = "%nExpecting path of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>";
public static ErrorMessageFactory shouldHavePath(URI actual, String expectedPath) {
return expectedPath == null ? new ShouldHavePath(actual) : new ShouldHavePath(actual, expectedPath);
}
private ShouldHavePath(URI actual, String expectedPath) {
super(SHOULD_HAVE_PATH, actual, expectedPath, actual.getPath());
}
private ShouldHavePath(URI actual) {
super(SHOULD_NOT_HAVE_PATH, actual, actual.getPath());
}
public static ErrorMessageFactory shouldHavePath(URL actual, String expectedPath) {<FILL_FUNCTION_BODY>}
private ShouldHavePath(URL actual, String expectedPath) {
super(SHOULD_HAVE_PATH, actual, expectedPath, actual.getPath());
}
private ShouldHavePath(URL actual) {
super(SHOULD_NOT_HAVE_PATH, actual, actual.getPath());
}
}
|
return isNullOrEmpty(expectedPath) ? new ShouldHavePath(actual) : new ShouldHavePath(actual, expectedPath);
| 358
| 33
| 391
|
<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/uri/ShouldHavePort.java
|
ShouldHavePort
|
shouldHavePort
|
class ShouldHavePort extends BasicErrorMessageFactory {
private static final int NO_PORT = -1;
private static final String SHOULD_HAVE_NO_PORT = "%nExpecting actual:%n <%s>%nnot to have a port but had:%n <%s>";
private static final String SHOULD_HAVE_PORT = "%nExpecting port of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>";
public static ErrorMessageFactory shouldHavePort(URI actual, int expectedPort) {<FILL_FUNCTION_BODY>}
private ShouldHavePort(URI actual, int expectedPort) {
super(SHOULD_HAVE_PORT, actual, expectedPort, actual.getPort());
}
private ShouldHavePort(URI actual) {
super(SHOULD_HAVE_NO_PORT, actual, actual.getPort());
}
public static ErrorMessageFactory shouldHavePort(URL actual, int expectedPort) {
return expectedPort == NO_PORT ? new ShouldHavePort(actual) : new ShouldHavePort(actual, expectedPort);
}
private ShouldHavePort(URL actual, int expectedPort) {
super(SHOULD_HAVE_PORT, actual, expectedPort, actual.getPort());
}
private ShouldHavePort(URL actual) {
super(SHOULD_HAVE_NO_PORT, actual, actual.getPort());
}
}
|
return expectedPort == NO_PORT ? new ShouldHavePort(actual) : new ShouldHavePort(actual, expectedPort);
| 372
| 31
| 403
|
<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/uri/ShouldHaveQuery.java
|
ShouldHaveQuery
|
shouldHaveQuery
|
class ShouldHaveQuery extends BasicErrorMessageFactory {
private static final String SHOULD_HAVE_QUERY = "%nExpecting query of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>";
private static final String SHOULD_NOT_HAVE_QUERY = "%nExpecting actual:%n <%s>%nnot to have a query but had:%n <%s>";
public static ErrorMessageFactory shouldHaveQuery(URI actual, String expectedQuery) {
return expectedQuery == null ? new ShouldHaveQuery(actual) : new ShouldHaveQuery(actual, expectedQuery);
}
private ShouldHaveQuery(URI actual, String expectedQuery) {
super(SHOULD_HAVE_QUERY, actual, expectedQuery, actual.getQuery());
}
private ShouldHaveQuery(URI actual) {
super(SHOULD_NOT_HAVE_QUERY, actual, actual.getQuery());
}
public static ErrorMessageFactory shouldHaveQuery(URL actual, String expectedQuery) {<FILL_FUNCTION_BODY>}
private ShouldHaveQuery(URL actual, String expectedQuery) {
super(SHOULD_HAVE_QUERY, actual, expectedQuery, actual.getQuery());
}
private ShouldHaveQuery(URL actual) {
super(SHOULD_NOT_HAVE_QUERY, actual, actual.getQuery());
}
}
|
return expectedQuery == null ? new ShouldHaveQuery(actual) : new ShouldHaveQuery(actual, expectedQuery);
| 363
| 29
| 392
|
<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/uri/ShouldHaveUserInfo.java
|
ShouldHaveUserInfo
|
shouldHaveUserInfo
|
class ShouldHaveUserInfo extends BasicErrorMessageFactory {
private static final String SHOULD_HAVE_NO_USER_INFO = "%nExpecting actual:%n <%s>%nnot to have user info but had:%n <%s>";
private static final String SHOULD_HAVE_USER_INFO = "%nExpecting user info of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>";
public static ErrorMessageFactory shouldHaveUserInfo(URI actual, String expectedUserInfo) {
return expectedUserInfo == null ? new ShouldHaveUserInfo(actual) : new ShouldHaveUserInfo(actual, expectedUserInfo);
}
private ShouldHaveUserInfo(URI actual, String expectedUserInfo) {
super(SHOULD_HAVE_USER_INFO, actual, expectedUserInfo, actual.getUserInfo());
}
private ShouldHaveUserInfo(URI actual) {
super(SHOULD_HAVE_NO_USER_INFO, actual, actual.getUserInfo());
}
public static ErrorMessageFactory shouldHaveUserInfo(URL actual, String expectedUserInfo) {<FILL_FUNCTION_BODY>}
private ShouldHaveUserInfo(URL actual, String expectedUserInfo) {
super(SHOULD_HAVE_USER_INFO, actual, expectedUserInfo, actual.getUserInfo());
}
private ShouldHaveUserInfo(URL actual) {
super(SHOULD_HAVE_NO_USER_INFO, actual, actual.getUserInfo());
}
}
|
return expectedUserInfo == null ? new ShouldHaveUserInfo(actual) : new ShouldHaveUserInfo(actual, expectedUserInfo);
| 391
| 33
| 424
|
<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/extractor/ByNameMultipleExtractor.java
|
ByNameMultipleExtractor
|
apply
|
class ByNameMultipleExtractor implements Function<Object, Tuple> {
private final String[] fieldsOrProperties;
ByNameMultipleExtractor(String... fieldsOrProperties) {
this.fieldsOrProperties = fieldsOrProperties;
}
@Override
public Tuple apply(Object input) {<FILL_FUNCTION_BODY>}
private List<Function<Object, Object>> buildExtractors() {
return Arrays.stream(fieldsOrProperties).map(ByNameSingleExtractor::new).collect(toList());
}
private List<Object> extractValues(Object input, List<Function<Object, Object>> singleExtractors) {
return singleExtractors.stream().map(extractor -> extractor.apply(input)).collect(toList());
}
}
|
checkArgument(fieldsOrProperties != null, "The names of the fields/properties to read should not be null");
checkArgument(fieldsOrProperties.length > 0, "The names of the fields/properties to read should not be empty");
checkArgument(input != null, "The object to extract fields/properties from should not be null");
List<Function<Object, Object>> extractors = buildExtractors();
List<Object> values = extractValues(input, extractors);
return new Tuple(values.toArray());
| 198
| 130
| 328
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/groups/FieldsOrPropertiesExtractor.java
|
FieldsOrPropertiesExtractor
|
checkObjectToExtractFromIsNotNull
|
class FieldsOrPropertiesExtractor {
/**
* Call {@link #extract(Iterable, Function)} after converting objects to an iterable.
* <p>
* Behavior is described in javadoc {@link AbstractObjectArrayAssert#extracting(Function)}
* @param <F> type of elements to extract a value from
* @param <T> the extracted value type
* @param objects the elements to extract a value from
* @param extractor the extractor function
* @return the extracted values
*/
public static <F, T> T[] extract(F[] objects, Function<? super F, T> extractor) {
checkObjectToExtractFromIsNotNull(objects);
List<T> result = extract(newArrayList(objects), extractor);
return toArray(result);
}
/**
* Behavior is described in {@link AbstractIterableAssert#extracting(Function)}
* @param <F> type of elements to extract a value from
* @param <T> the extracted value type
* @param objects the elements to extract a value from
* @param extractor the extractor function
* @return the extracted values
*/
public static <F, T> List<T> extract(Iterable<? extends F> objects, Function<? super F, T> extractor) {
checkObjectToExtractFromIsNotNull(objects);
return stream(objects).map(extractor).collect(toList());
}
private static void checkObjectToExtractFromIsNotNull(Object object) {<FILL_FUNCTION_BODY>}
}
|
if (object == null) throw new AssertionError("Expecting actual not to be null");
| 388
| 26
| 414
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/groups/Properties.java
|
Properties
|
checkIsNotNullOrEmpty
|
class Properties<T> {
@VisibleForTesting
final String propertyName;
final Class<T> propertyType;
@VisibleForTesting
PropertySupport propertySupport = PropertySupport.instance();
/**
* Creates a new <code>{@link Properties}</code>.
* @param <T> the type of value to extract.
* @param propertyName the name of the property to be read from the elements of a {@code Iterable}. It may be a nested
* property (e.g. "address.street.number").
* @param propertyType the type of property to extract
* @throws NullPointerException if the given property name is {@code null}.
* @throws IllegalArgumentException if the given property name is empty.
* @return the created {@code Properties}.
*/
public static <T> Properties<T> extractProperty(String propertyName, Class<T> propertyType) {
checkIsNotNullOrEmpty(propertyName);
return new Properties<>(propertyName, propertyType);
}
/**
* Creates a new <code>{@link Properties} with given propertyName and Object as property type.</code>.
*
* @param propertyName the name of the property to be read from the elements of a {@code Iterable}. It may be a nested
* property (e.g. "address.street.number").
* @throws NullPointerException if the given property name is {@code null}.
* @throws IllegalArgumentException if the given property name is empty.
* @return the created {@code Properties}.
*/
public static Properties<Object> extractProperty(String propertyName) {
return extractProperty(propertyName, Object.class);
}
private static void checkIsNotNullOrEmpty(String propertyName) {<FILL_FUNCTION_BODY>}
@VisibleForTesting
Properties(String propertyName, Class<T> propertyType) {
this.propertyName = propertyName;
this.propertyType = propertyType;
}
/**
* Specifies the target type of an instance that was previously created with {@link #extractProperty(String)}.
* <p>
* This is so that you can write:
* <pre><code class='java'> extractProperty("name").ofType(String.class).from(fellowshipOfTheRing);</code></pre>
*
* instead of:
* <pre><code class='java'> extractProperty("name", String.class).from(fellowshipOfTheRing);</code></pre>
*
* @param <U> the type of value to extract.
* @param propertyType the type of property to extract.
* @return a new {@code Properties} with the given type.
*/
public <U> Properties<U> ofType(Class<U> propertyType) {
return extractProperty(this.propertyName, propertyType);
}
/**
* Extracts the values of the property (specified previously in <code>{@link #extractProperty(String)}</code>) from the elements
* of the given <code>{@link Iterable}</code>.
* @param c the given {@code Iterable}.
* @return the values of the previously specified property extracted from the given {@code Iterable}.
* @throws IntrospectionError if an element in the given {@code Iterable} does not have a property with a matching name.
*/
public List<T> from(Iterable<?> c) {
return propertySupport.propertyValues(propertyName, propertyType, c);
}
/**
* Extracts the values of the property (specified previously in <code>{@link #extractProperty(String)}</code>) from the elements
* of the given array.
* @param array the given array.
* @return the values of the previously specified property extracted from the given array.
* @throws IntrospectionError if an element in the given array does not have a property with a matching name.
*/
public List<T> from(Object[] array) {
return propertySupport.propertyValues(propertyName, propertyType, wrap(array));
}
}
|
requireNonNull(propertyName, "The name of the property to read should not be null");
checkArgument(propertyName.length() > 0, "The name of the property to read should not be empty");
| 1,024
| 51
| 1,075
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/groups/Tuple.java
|
Tuple
|
equals
|
class Tuple {
private final List<Object> values;
public Tuple(Object... values) {
this.values = list(values);
}
public Object[] toArray() {
return values.toArray();
}
public List<Object> toList() {
return values;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Arrays.deepHashCode(values.toArray());
}
@Override
public String toString() {
return CONFIGURATION_PROVIDER.representation().toStringOf(this);
}
public static Tuple tuple(Object... values) {
return new Tuple(values);
}
}
|
if (this == obj) return true;
if (!(obj instanceof Tuple)) return false;
Tuple other = (Tuple) obj;
return Arrays.deepEquals(values.toArray(), other.values.toArray());
| 205
| 60
| 265
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/AbstractComparisonStrategy.java
|
AbstractComparisonStrategy
|
arrayContains
|
class AbstractComparisonStrategy implements ComparisonStrategy {
@Override
public Iterable<?> duplicatesFrom(Iterable<?> iterable) {
if (isNullOrEmpty(iterable)) return EMPTY_SET;
Set<Object> noDuplicates = newSetUsingComparisonStrategy();
Set<Object> duplicatesWithOrderPreserved = new LinkedHashSet<>();
for (Object element : iterable) {
if (noDuplicates.contains(element)) {
duplicatesWithOrderPreserved.add(element);
} else {
noDuplicates.add(element);
}
}
return duplicatesWithOrderPreserved;
}
/**
* Returns a {@link Set} honoring the comparison strategy used.
*
* @return a {@link Set} honoring the comparison strategy used.
*/
protected abstract Set<Object> newSetUsingComparisonStrategy();
@Override
public boolean arrayContains(Object array, Object value) {<FILL_FUNCTION_BODY>}
@Override
public boolean isLessThan(Object actual, Object other) {
return !areEqual(actual, other) && !isGreaterThan(actual, other);
}
@Override
public boolean isLessThanOrEqualTo(Object actual, Object other) {
return areEqual(actual, other) || isLessThan(actual, other);
}
@Override
public boolean isGreaterThanOrEqualTo(Object actual, Object other) {
return areEqual(actual, other) || isGreaterThan(actual, other);
}
@Override
public boolean isStandard() {
return false;
}
}
|
for (int i = 0; i < getLength(array); i++) {
Object element = Array.get(array, i);
if (areEqual(element, value)) return true;
}
return false;
| 423
| 58
| 481
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Arrays2D.java
|
Arrays2D
|
assertNumberOfRows
|
class Arrays2D {
private static final Arrays2D INSTANCE = new Arrays2D();
/**
* Returns the singleton instance of this class based on {@link StandardComparisonStrategy}.
*
* @return the singleton instance of this class based on {@link StandardComparisonStrategy}.
*/
public static Arrays2D instance() {
return INSTANCE;
}
@VisibleForTesting
public void assertNullOrEmpty(AssertionInfo info, Failures failures, Object array) {
if (array == null) return;
if (countArrayElements(array) > 0) throw failures.failure(info, shouldBeNullOrEmpty(array));
}
@VisibleForTesting
public void assertEmpty(AssertionInfo info, Failures failures, Object array) {
assertNotNull(info, array);
// need to check that all rows are empty
int numberOfRows = sizeOf(array);
for (int i = 0; i < numberOfRows; i++) {
Object actualArrayRow = Array.get(array, i);
if (sizeOf(actualArrayRow) > 0) throw failures.failure(info, shouldBeEmpty(array));
}
}
@VisibleForTesting
public void assertHasDimensions(AssertionInfo info, Failures failures, Object array2d, int expectedNumberOfRows,
int expectedRowSize) {
assertNumberOfRows(info, failures, array2d, expectedNumberOfRows);
for (int i = 0; i < expectedNumberOfRows; i++) {
Object actualRow = Array.get(array2d, i);
assertSecondDimension(info, failures, actualRow, expectedRowSize, i);
}
}
@VisibleForTesting
public void assertNumberOfRows(AssertionInfo info, Failures failures, Object array, int expectedSize) {<FILL_FUNCTION_BODY>}
private void assertSecondDimension(AssertionInfo info, Failures failures, Object actual, int expectedSize, int rowIndex) {
assertNotNull(info, actual);
checkArraySizes(actual, failures, sizeOf(actual), expectedSize, info, rowIndex);
}
private static void checkArraySizes(Object actual, Failures failures, int sizeOfActual, int sizeOfOther, AssertionInfo info,
int rowIndex) {
if (sizeOfActual != sizeOfOther) {
throw failures.failure(info, shouldHaveSize(actual, sizeOfActual, sizeOfOther, rowIndex));
}
}
@VisibleForTesting
public void assertHasSameDimensionsAs(AssertionInfo info, Object actual, Object other) {
assertNotNull(info, actual);
assertIsArray(info, actual);
assertIsArray(info, other);
// check first dimension
int actualFirstDimension = sizeOf(actual);
int otherFirstDimension = sizeOf(other);
if (actualFirstDimension != otherFirstDimension) {
throw Failures.instance().failure(info,
shouldHaveSameDimensionsAs(actual, other, actualFirstDimension, otherFirstDimension));
}
// check second dimensions
for (int i = 0; i < actualFirstDimension; i++) {
Object actualRow = Array.get(actual, i);
assertIsArray(info, actualRow);
Object otherRow = Array.get(other, i);
assertIsArray(info, otherRow);
hasSameRowSizeAsCheck(info, i, actual, other, actualRow, otherRow, sizeOf(actualRow));
}
}
static void hasSameRowSizeAsCheck(AssertionInfo info, int rowIndex, Object actual, Object other, Object actualRow,
Object otherRow, int actualRowSize) {
requireNonNull(other, format("The array to compare %s size with should not be null", actual));
int expectedRowSize = Array.getLength(otherRow);
if (actualRowSize != expectedRowSize)
throw Failures.instance().failure(info, shouldHaveSameDimensionsAs(rowIndex, actualRowSize, expectedRowSize, actualRow,
otherRow, actual, other));
}
@VisibleForTesting
public void assertContains(AssertionInfo info, Failures failures, Object array, Object value, Index index) {
assertNotNull(info, array);
assertNotEmpty(info, failures, array);
checkIndexValueIsValid(index, sizeOf(array) - 1);
Object actualElement = Array.get(array, index.value);
if (!deepEquals(actualElement, value)) {
throw failures.failure(info, shouldContainAtIndex(array, value, index, Array.get(array, index.value)));
}
}
@VisibleForTesting
public void assertNotEmpty(AssertionInfo info, Failures failures, Object array) {
assertNotNull(info, array);
if (countArrayElements(array) == 0) throw failures.failure(info, shouldNotBeEmpty());
}
private static int countArrayElements(Object array) {
// even if array has many rows, they could all be empty
int numberOfRows = sizeOf(array);
// if any rows is not empty, the assertion succeeds.
int allRowsElementsCount = 0;
for (int i = 0; i < numberOfRows; i++) {
Object actualRow = Array.get(array, i);
allRowsElementsCount += sizeOf(actualRow);
}
return allRowsElementsCount;
}
@VisibleForTesting
public void assertDoesNotContain(AssertionInfo info, Failures failures, Object array, Object value, Index index) {
assertNotNull(info, array);
checkIndexValueIsValid(index, Integer.MAX_VALUE);
if (index.value >= sizeOf(array)) return;
if (deepEquals(Array.get(array, index.value), value)) {
throw failures.failure(info, shouldNotContainAtIndex(array, value, index));
}
}
}
|
assertNotNull(info, array);
int sizeOfActual = sizeOf(array);
if (sizeOfActual != expectedSize)
throw failures.failure(info, ShouldHaveDimensions.shouldHaveFirstDimension(array, sizeOfActual, expectedSize));
| 1,499
| 66
| 1,565
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/AtomicReferenceArrayElementComparisonStrategy.java
|
AtomicReferenceArrayElementComparisonStrategy
|
areEqual
|
class AtomicReferenceArrayElementComparisonStrategy<T> extends StandardComparisonStrategy {
private final Comparator<? super T> elementComparator;
public AtomicReferenceArrayElementComparisonStrategy(Comparator<? super T> elementComparator) {
this.elementComparator = elementComparator;
}
@SuppressWarnings("unchecked")
@Override
public boolean areEqual(Object actual, Object other) {<FILL_FUNCTION_BODY>}
private boolean compareElementsOf(AtomicReferenceArray<T> actual, T[] other) {
if (actual.length() != other.length) return false;
// compare their elements with elementComparator
for (int i = 0; i < actual.length(); i++) {
if (elementComparator.compare(actual.get(i), other[i]) != 0) return false;
}
return true;
}
@Override
public String toString() {
return "AtomicReferenceArrayElementComparisonStrategy using " + CONFIGURATION_PROVIDER.representation()
.toStringOf(
elementComparator);
}
@Override
public String asText() {
return "when comparing elements using " + CONFIGURATION_PROVIDER.representation().toStringOf(elementComparator);
}
@Override
public boolean isStandard() {
return false;
}
}
|
if (actual == null && other == null) return true;
if (actual == null || other == null) return false;
// expecting actual and other to be T[]
return actual instanceof AtomicReferenceArray && isArray(other)
&& compareElementsOf((AtomicReferenceArray<T>) actual, (T[]) other);
| 356
| 82
| 438
|
<methods>public boolean areEqual(java.lang.Object, java.lang.Object) ,public Iterable<?> duplicatesFrom(Iterable<?>) ,public static org.assertj.core.internal.StandardComparisonStrategy instance() ,public boolean isGreaterThan(java.lang.Object, java.lang.Object) ,public boolean isLessThan(java.lang.Object, java.lang.Object) ,public boolean isStandard() ,public boolean iterableContains(Iterable<?>, java.lang.Object) ,public void iterableRemoves(Iterable<?>, java.lang.Object) ,public void iterablesRemoveFirst(Iterable<?>, java.lang.Object) ,public boolean stringContains(java.lang.String, java.lang.String) ,public boolean stringEndsWith(java.lang.String, java.lang.String) ,public boolean stringStartsWith(java.lang.String, java.lang.String) <variables>private static final org.assertj.core.internal.StandardComparisonStrategy INSTANCE
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/BigDecimals.java
|
BigDecimals
|
areEqual
|
class BigDecimals extends Numbers<BigDecimal> {
private static final BigDecimals INSTANCE = new BigDecimals();
/**
* Returns the singleton instance of this class based on {@link StandardComparisonStrategy}.
*
* @return the singleton instance of this class based on {@link StandardComparisonStrategy}.
*/
public static BigDecimals instance() {
return INSTANCE;
}
@VisibleForTesting
BigDecimals() {
super();
}
public BigDecimals(ComparisonStrategy comparisonStrategy) {
super(comparisonStrategy);
}
@Override
protected BigDecimal zero() {
return ZERO;
}
@Override
protected BigDecimal one() {
return ONE;
}
@Override
protected BigDecimal absDiff(BigDecimal actual, BigDecimal other) {
return actual.subtract(other).abs();
}
@Override
protected boolean isGreaterThan(BigDecimal value, BigDecimal other) {
return value.subtract(other).compareTo(ZERO) > 0;
}
@Override
protected boolean areEqual(BigDecimal value1, BigDecimal value2) {<FILL_FUNCTION_BODY>}
public void assertHasScale(AssertionInfo info, BigDecimal actual, int expectedScale) {
assertNotNull(info, actual);
if (areEqual(actual.scale(), expectedScale)) return;
throw failures.failure(info, shouldHaveScale(actual, expectedScale));
}
}
|
if (value1 == null) return value2 == null;
// we know value1 is not null
if (value2 == null) return false;
return value1.compareTo(value2) == 0;
| 404
| 55
| 459
|
<methods>public void <init>() ,public void <init>(org.assertj.core.internal.ComparisonStrategy) ,public void assertIsBetween(org.assertj.core.api.AssertionInfo, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal) ,public void assertIsCloseTo(org.assertj.core.api.AssertionInfo, java.math.BigDecimal, java.math.BigDecimal, Offset<java.math.BigDecimal>) ,public void assertIsCloseToPercentage(org.assertj.core.api.AssertionInfo, java.math.BigDecimal, java.math.BigDecimal, org.assertj.core.data.Percentage) ,public void assertIsNegative(org.assertj.core.api.AssertionInfo, java.math.BigDecimal) ,public void assertIsNotCloseTo(org.assertj.core.api.AssertionInfo, java.math.BigDecimal, java.math.BigDecimal, Offset<java.math.BigDecimal>) ,public void assertIsNotCloseToPercentage(org.assertj.core.api.AssertionInfo, java.math.BigDecimal, java.math.BigDecimal, org.assertj.core.data.Percentage) ,public void assertIsNotNegative(org.assertj.core.api.AssertionInfo, java.math.BigDecimal) ,public void assertIsNotPositive(org.assertj.core.api.AssertionInfo, java.math.BigDecimal) ,public void assertIsNotZero(org.assertj.core.api.AssertionInfo, java.math.BigDecimal) ,public void assertIsOne(org.assertj.core.api.AssertionInfo, java.math.BigDecimal) ,public void assertIsPositive(org.assertj.core.api.AssertionInfo, java.math.BigDecimal) ,public void assertIsStrictlyBetween(org.assertj.core.api.AssertionInfo, java.math.BigDecimal, java.math.BigDecimal, java.math.BigDecimal) ,public void assertIsZero(org.assertj.core.api.AssertionInfo, java.math.BigDecimal) <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/BinaryDiff.java
|
BinaryDiff
|
diff
|
class BinaryDiff {
@VisibleForTesting
public BinaryDiffResult diff(File actual, byte[] expected) throws IOException {
return diff(actual.toPath(), expected);
}
@VisibleForTesting
public BinaryDiffResult diff(Path actual, byte[] expected) throws IOException {
try (InputStream actualStream = new BufferedInputStream(Files.newInputStream(actual))) {
return diff(actualStream, expected);
}
}
@VisibleForTesting
public BinaryDiffResult diff(InputStream actualStream, byte[] expected) throws IOException {
try (InputStream expectedStream = new ByteArrayInputStream(expected)) {
return diff(actualStream, expectedStream);
}
}
@VisibleForTesting
public BinaryDiffResult diff(InputStream actualStream, InputStream expectedStream) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int index = 0;
while (true) {
int actual = actualStream.read();
int expected = expectedStream.read();
if (actual == -1 && expected == -1) return BinaryDiffResult.noDiff(); // reached end of both streams
if (actual != expected) return new BinaryDiffResult(index, expected, actual);
index += 1;
}
| 216
| 97
| 313
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/BinaryDiffResult.java
|
BinaryDiffResult
|
describe
|
class BinaryDiffResult {
private static final int EOF = -1;
public final int offset;
public final String expected;
public final String actual;
/**
* Builds a new instance.
*
* @param offset the offset at which the difference occurred.
* @param expected the expected byte as an int in the range 0 to 255, or -1 for EOF.
* @param actual the actual byte in the same format.
*/
public BinaryDiffResult(int offset, int expected, int actual) {
this.offset = offset;
this.expected = describe(expected);
this.actual = describe(actual);
}
public boolean hasNoDiff() {
return offset == EOF;
}
public boolean hasDiff() {
return !hasNoDiff();
}
public static BinaryDiffResult noDiff() {
return new BinaryDiffResult(EOF, 0, 0);
}
private String describe(int b) {<FILL_FUNCTION_BODY>}
}
|
return (b == EOF) ? "EOF" : "0x" + Integer.toHexString(b).toUpperCase();
| 267
| 37
| 304
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Booleans.java
|
Booleans
|
assertNotEqual
|
class Booleans {
private static final Booleans INSTANCE = new Booleans();
/**
* Returns the singleton instance of this class.
* @return the singleton instance of this class.
*/
public static Booleans instance() {
return INSTANCE;
}
@VisibleForTesting
Failures failures = Failures.instance();
@VisibleForTesting
Booleans() {}
/**
* Asserts that two booleans are equal.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param expected the expected value.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not equal to the expected one. This method will throw a
* {@code org.junit.ComparisonFailure} instead if JUnit is in the classpath and the expected and actual values are not
* equal.
*/
public void assertEqual(AssertionInfo info, Boolean actual, boolean expected) {
assertNotNull(info, actual);
if (actual == expected) return;
throw failures.failure(info, shouldBeEqual(actual, expected, info.representation()));
}
/**
* Asserts that two longs are not equal.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param other the value to compare the actual value to.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is equal to the other one.
*/
public void assertNotEqual(AssertionInfo info, Boolean actual, boolean other) {<FILL_FUNCTION_BODY>}
private static void assertNotNull(AssertionInfo info, Boolean actual) {
Objects.instance().assertNotNull(info, actual);
}
}
|
assertNotNull(info, actual);
if (actual != other) return;
throw failures.failure(info, shouldNotBeEqual(actual, other));
| 468
| 42
| 510
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Bytes.java
|
Bytes
|
absDiff
|
class Bytes extends Numbers<Byte> implements WholeNumbers<Byte> {
private static final Bytes INSTANCE = new Bytes();
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static Bytes instance() {
return INSTANCE;
}
@VisibleForTesting
Bytes() {
super();
}
public Bytes(ComparisonStrategy comparisonStrategy) {
super(comparisonStrategy);
}
@Override
protected Byte zero() {
return 0;
}
@Override
protected Byte one() {
return 1;
}
@Override
protected Byte absDiff(Byte actual, Byte other) {<FILL_FUNCTION_BODY>}
@Override
protected boolean isGreaterThan(Byte value, Byte other) {
return value > other;
}
@Override
public boolean isEven(Byte number) {
return (number & one()) == zero();
}
}
|
return (byte) Math.abs(actual - other); // TODO check corner case when diff > max byte
| 271
| 27
| 298
|
<methods>public void <init>() ,public void <init>(org.assertj.core.internal.ComparisonStrategy) ,public void assertIsBetween(org.assertj.core.api.AssertionInfo, java.lang.Byte, java.lang.Byte, java.lang.Byte) ,public void assertIsCloseTo(org.assertj.core.api.AssertionInfo, java.lang.Byte, java.lang.Byte, Offset<java.lang.Byte>) ,public void assertIsCloseToPercentage(org.assertj.core.api.AssertionInfo, java.lang.Byte, java.lang.Byte, org.assertj.core.data.Percentage) ,public void assertIsNegative(org.assertj.core.api.AssertionInfo, java.lang.Byte) ,public void assertIsNotCloseTo(org.assertj.core.api.AssertionInfo, java.lang.Byte, java.lang.Byte, Offset<java.lang.Byte>) ,public void assertIsNotCloseToPercentage(org.assertj.core.api.AssertionInfo, java.lang.Byte, java.lang.Byte, org.assertj.core.data.Percentage) ,public void assertIsNotNegative(org.assertj.core.api.AssertionInfo, java.lang.Byte) ,public void assertIsNotPositive(org.assertj.core.api.AssertionInfo, java.lang.Byte) ,public void assertIsNotZero(org.assertj.core.api.AssertionInfo, java.lang.Byte) ,public void assertIsOne(org.assertj.core.api.AssertionInfo, java.lang.Byte) ,public void assertIsPositive(org.assertj.core.api.AssertionInfo, java.lang.Byte) ,public void assertIsStrictlyBetween(org.assertj.core.api.AssertionInfo, java.lang.Byte, java.lang.Byte, java.lang.Byte) ,public void assertIsZero(org.assertj.core.api.AssertionInfo, java.lang.Byte) <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/CommonErrors.java
|
CommonErrors
|
wrongElementTypeForFlatExtracting
|
class CommonErrors {
public static NullPointerException arrayOfValuesToLookForIsNull() {
return new NullPointerException(ErrorMessages.arrayOfValuesToLookForIsNull());
}
public static NullPointerException iterableToLookForIsNull() {
return new NullPointerException(ErrorMessages.iterableToLookForIsNull());
}
public static NullPointerException iterableOfValuesToLookForIsNull() {
return new NullPointerException(ErrorMessages.iterableValuesToLookForIsNull());
}
public static IllegalArgumentException arrayOfValuesToLookForIsEmpty() {
return new IllegalArgumentException(ErrorMessages.arrayOfValuesToLookForIsEmpty());
}
public static IllegalArgumentException iterableOfValuesToLookForIsEmpty() {
return new IllegalArgumentException(ErrorMessages.iterableValuesToLookForIsEmpty());
}
public static void wrongElementTypeForFlatExtracting(Object group) {<FILL_FUNCTION_BODY>}
private CommonErrors() {}
}
|
throw new IllegalArgumentException("Flat extracting expects extracted values to be Iterables or arrays but was a "
+ group.getClass().getSimpleName());
| 248
| 39
| 287
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/CommonValidations.java
|
CommonValidations
|
checkLineCounts
|
class CommonValidations {
private static final Failures FAILURES = Failures.instance();
private CommonValidations() {}
static void checkIndexValueIsValid(Index index, int maximum) {
requireNonNull(index, "Index should not be null");
if (index.value <= maximum) return;
String errorMessage = "Index should be between <0> and <%d> (inclusive) but was:%n <%d>";
throw new IndexOutOfBoundsException(format(errorMessage, maximum, index.value));
}
static void checkOffsetIsNotNull(Offset<?> offset) {
requireNonNull(offset, "The given offset should not be null");
}
static void checkPercentageIsNotNull(Percentage percentage) {
requireNonNull(percentage, "The given percentage should not be null");
}
static void checkNumberIsNotNull(Number number) {
requireNonNull(number, "The given number should not be null");
}
static void checkIsNotEmpty(Object[] values) {
if (values.length == 0) throw arrayOfValuesToLookForIsEmpty();
}
static void checkIsNotEmpty(Iterable<?> iterable) {
if (!iterable.iterator().hasNext()) throw iterableOfValuesToLookForIsEmpty();
}
public static void checkIsNotNull(Object[] values) {
if (values == null) throw arrayOfValuesToLookForIsNull();
}
static void checkIsNotNull(Iterable<?> iterable) {
if (iterable == null) throw iterableOfValuesToLookForIsNull();
}
static void checkIsNotNullAndNotEmpty(Object[] values) {
checkIsNotNull(values);
checkIsNotEmpty(values);
}
static void checkIsNotNullAndNotEmpty(Iterable<?> iterable) {
checkIsNotNull(iterable);
checkIsNotEmpty(iterable);
}
public static void failIfEmptySinceActualIsNotEmpty(AssertionInfo info, Failures failures, Object actual,
Object values) {
if (isArrayEmpty(values)) throw failures.failure(info, actualIsNotEmpty(actual));
}
public static void hasSameSizeAsCheck(AssertionInfo info, Object actual, Object other, int sizeOfActual) {
checkOtherIsNotNull(other, "Array");
checkSameSizes(info, actual, other, sizeOfActual, Array.getLength(other));
}
public static void hasSameSizeAsCheck(AssertionInfo info, Object actual, Iterable<?> other, int sizeOfActual) {
checkOtherIsNotNull(other, "Iterable");
checkSameSizes(info, actual, other, sizeOfActual, sizeOf(other));
}
public static void hasSameSizeAsCheck(AssertionInfo info, Object actual, Map<?, ?> other, int sizeOfActual) {
checkOtherIsNotNull(other, "Map");
checkSameSizes(info, actual, other, sizeOfActual, other.size());
}
static void checkOtherIsNotNull(Object other, String otherType) {
requireNonNull(other, "The " + otherType + " to compare actual size with should not be null");
}
static void checkSameSizes(AssertionInfo info, Object actual, Object other, int sizeOfActual, int sizeOfOther) {
if (sizeOfActual != sizeOfOther)
throw FAILURES.failure(info, shouldHaveSameSizeAs(actual, other, sizeOfActual, sizeOfOther));
}
public static void checkSizes(Object actual, int sizeOfActual, int sizeOfOther, AssertionInfo info) {
if (sizeOfActual != sizeOfOther) throw FAILURES.failure(info, shouldHaveSize(actual, sizeOfActual, sizeOfOther));
}
public static void checkSizeGreaterThan(Object actual, int boundary, int sizeOfActual,
AssertionInfo info) {
if (!(sizeOfActual > boundary))
throw FAILURES.failure(info, shouldHaveSizeGreaterThan(actual, sizeOfActual, boundary));
}
public static void checkSizeGreaterThanOrEqualTo(Object actual, int boundary, int sizeOfActual,
AssertionInfo info) {
if (!(sizeOfActual >= boundary))
throw FAILURES.failure(info, shouldHaveSizeGreaterThanOrEqualTo(actual, sizeOfActual, boundary));
}
public static void checkSizeLessThan(Object actual, int boundary, int sizeOfActual,
AssertionInfo info) {
if (!(sizeOfActual < boundary))
throw FAILURES.failure(info, shouldHaveSizeLessThan(actual, sizeOfActual, boundary));
}
public static void checkSizeLessThanOrEqualTo(Object actual, int boundary, int sizeOfActual,
AssertionInfo info) {
if (!(sizeOfActual <= boundary))
throw FAILURES.failure(info, shouldHaveSizeLessThanOrEqualTo(actual, sizeOfActual, boundary));
}
public static void checkSizeBetween(Object actual, int lowerBoundary, int higherBoundary,
int sizeOfActual, AssertionInfo info) {
if (!(higherBoundary >= lowerBoundary))
throw new IllegalArgumentException(format("The higher boundary <%s> must be greater than the lower boundary <%s>.",
higherBoundary, lowerBoundary));
if (!(lowerBoundary <= sizeOfActual && sizeOfActual <= higherBoundary))
throw FAILURES.failure(info, shouldHaveSizeBetween(actual, sizeOfActual, lowerBoundary, higherBoundary));
}
public static void checkLineCounts(Object actual, int lineCountOfActual, int lineCountOfOther, AssertionInfo info) {<FILL_FUNCTION_BODY>}
public static void checkTypeIsNotNull(Class<?> expectedType) {
requireNonNull(expectedType, "The given type should not be null");
}
public static void checkIterableIsNotNull(Iterable<?> set) {
requireNonNull(set, "The iterable to look for should not be null");
}
public static void checkSequenceIsNotNull(Object sequence) {
requireNonNull(sequence, nullSequence());
}
public static void checkSubsequenceIsNotNull(Object subsequence) {
requireNonNull(subsequence, nullSubsequence());
}
}
|
if (lineCountOfActual != lineCountOfOther)
throw FAILURES.failure(info, shouldHaveLinesCount(actual, lineCountOfActual, lineCountOfOther));
| 1,605
| 49
| 1,654
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/ComparatorBasedComparisonStrategy.java
|
ComparatorBasedComparisonStrategy
|
areEqual
|
class ComparatorBasedComparisonStrategy extends AbstractComparisonStrategy {
static final int NOT_EQUAL = -1;
// A raw type is necessary because we can't make assumptions on object to be compared.
@SuppressWarnings("rawtypes")
private final Comparator comparator;
// Comparator description used in assertion messages.
private final String comparatorDescription;
/**
* Creates a new <code>{@link ComparatorBasedComparisonStrategy}</code> specifying the comparison strategy with given
* comparator.
*
* @param comparator the comparison strategy to use.
*/
public ComparatorBasedComparisonStrategy(@SuppressWarnings("rawtypes") Comparator comparator) {
this(comparator, null);
}
/**
* Creates a new <code>{@link ComparatorBasedComparisonStrategy}</code> specifying the comparison strategy with given
* comparator and comparator description
*
* @param comparator the comparison strategy to use.
* @param comparatorDescription the comparator description to use in assertion messages.
*/
public ComparatorBasedComparisonStrategy(@SuppressWarnings("rawtypes") Comparator comparator,
String comparatorDescription) {
this.comparator = comparator;
this.comparatorDescription = comparatorDescription;
}
/**
* Creates a new <code>{@link ComparatorBasedComparisonStrategy}</code> specifying the comparison strategy with given
* {@link DescribableComparator}.
*
* @param comparator the comparator to use in the comparison strategy.
*/
public ComparatorBasedComparisonStrategy(DescribableComparator<?> comparator) {
this(comparator, comparator.description());
}
/**
* Returns true if given {@link Iterable} contains given value according to {@link #comparator}, false otherwise.<br>
* If given {@link Iterable} is null or empty, return false.
*
* @param iterable the {@link Iterable} to search value in
* @param value the object to look for in given {@link Iterable}
* @return true if given {@link Iterable} contains given value according to {@link #comparator}, false otherwise.
*/
@Override
@SuppressWarnings("unchecked")
public boolean iterableContains(Iterable<?> iterable, Object value) {
if (isNullOrEmpty(iterable)) return false;
for (Object element : iterable) {
// avoid comparison when objects are the same or both null
if (element == value) return true;
// both objects are not null => if one is then the other is not => compare next element with value
if (value == null || element == null) continue;
if (comparator.compare(element, value) == 0) return true;
}
return false;
}
/**
* Look for given value in given {@link Iterable} according to the {@link Comparator}, if value is found it is removed
* from it.<br>
* Does nothing if given {@link Iterable} is null (meaning no exception thrown).
*
* @param iterable the {@link Iterable} we want remove value from
* @param value object to remove from given {@link Iterable}
*/
@Override
@SuppressWarnings("unchecked")
public void iterableRemoves(Iterable<?> iterable, Object value) {
if (iterable == null) return;
// Avoid O(N^2) complexity of serial removal from an iterator of collections like ArrayList
if (iterable instanceof Collection) {
((Collection<?>) iterable).removeIf(o -> comparator.compare(o, value) == 0);
} else {
Iterator<?> iterator = iterable.iterator();
while (iterator.hasNext()) {
if (comparator.compare(iterator.next(), value) == 0) {
iterator.remove();
}
}
}
}
@Override
@SuppressWarnings("unchecked")
public void iterablesRemoveFirst(Iterable<?> iterable, Object value) {
if (iterable == null) return;
Iterator<?> iterator = iterable.iterator();
while (iterator.hasNext()) {
if (comparator.compare(iterator.next(), value) == 0) {
iterator.remove();
return;
}
}
}
/**
* Returns true if actual and other are equal according to {@link #comparator}, false otherwise.<br>
* Handles the cases where one of the parameter is null so that internal {@link #comparator} does not have too.
*
* @param actual the object to compare to other
* @param other the object to compare to actual
* @return true if actual and other are equal according to {@link #comparator}, false otherwise.
*/
@Override
@SuppressWarnings("unchecked")
public boolean areEqual(Object actual, Object other) {<FILL_FUNCTION_BODY>}
/**
* Returns any duplicate elements from the given {@link Iterable} according to {@link #comparator}.
*
* @param iterable the given {@link Iterable} we want to extract duplicate elements.
* @return an {@link Iterable} containing the duplicate elements of the given one. If no duplicates are found, an
* empty {@link Iterable} is returned.
*/
// overridden to write javadoc.
@Override
public Iterable<?> duplicatesFrom(Iterable<?> iterable) {
return super.duplicatesFrom(iterable);
}
@SuppressWarnings("unchecked")
@Override
protected Set<Object> newSetUsingComparisonStrategy() {
return new TreeSet<>(comparator);
}
@Override
public String asText() {
return "when comparing values using " + toString();
}
@Override
public String toString() {
return CONFIGURATION_PROVIDER.representation().toStringOf(this);
}
public Comparator<?> getComparator() {
return comparator;
}
public String getComparatorDescription() {
return comparatorDescription;
}
@Override
@SuppressWarnings("unchecked")
public boolean stringStartsWith(String string, String prefix) {
if (string.length() < prefix.length()) return false;
String stringPrefix = string.substring(0, prefix.length());
return comparator.compare(stringPrefix, prefix) == 0;
}
@Override
@SuppressWarnings("unchecked")
public boolean stringEndsWith(String string, String suffix) {
if (string.length() < suffix.length()) return false;
String stringSuffix = string.substring(string.length() - suffix.length());
return comparator.compare(stringSuffix, suffix) == 0;
}
@Override
public boolean stringContains(String string, String sequence) {
int sequenceLength = sequence.length();
for (int i = 0; i < string.length(); i++) {
String subString = string.substring(i);
if (subString.length() < sequenceLength) return false;
if (stringStartsWith(subString, sequence)) return true;
}
return false;
}
@Override
@SuppressWarnings("unchecked")
public boolean isGreaterThan(Object actual, Object other) {
return comparator.compare(actual, other) > 0;
}
@Override
public boolean isStandard() {
return false;
}
}
|
// we don't check actual or expected for null, this should be done by the comparator, the rationale being that a
// comparator might consider null to be equals to some special value (like blank String and null)
return comparator.compare(actual, other) == 0;
| 1,934
| 70
| 2,004
|
<methods>public non-sealed void <init>() ,public boolean arrayContains(java.lang.Object, java.lang.Object) ,public Iterable<?> duplicatesFrom(Iterable<?>) ,public boolean isGreaterThanOrEqualTo(java.lang.Object, java.lang.Object) ,public boolean isLessThan(java.lang.Object, java.lang.Object) ,public boolean isLessThanOrEqualTo(java.lang.Object, java.lang.Object) ,public boolean isStandard() <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Conditions.java
|
Conditions
|
assertIsNotNull
|
class Conditions {
private static final Conditions INSTANCE = new Conditions();
/**
* Returns the singleton instance of this class.
* @return the singleton instance of this class.
*/
public static Conditions instance() {
return INSTANCE;
}
@VisibleForTesting
Failures failures = Failures.instance();
@VisibleForTesting
Conditions() {}
/**
* Asserts that the actual value satisfies the given <code>{@link Condition}</code>.
* @param <T> the type of the actual value and the type of values that given {@code Condition} takes.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given {@code Condition} is {@code null}.
* @throws AssertionError if the actual value does not satisfy the given {@code Condition}.
*/
public <T> void assertIs(AssertionInfo info, T actual, Condition<? super T> condition) {
assertIsNotNull(condition);
if (!condition.matches(actual)) throw failures.failure(info, shouldBe(actual, condition));
}
/**
* Asserts that the actual value does not satisfy the given <code>{@link Condition}</code>.
* @param <T> the type of the actual value and the type of values that given {@code Condition} takes.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given {@code Condition} is {@code null}.
* @throws AssertionError if the actual value satisfies the given {@code Condition}.
*/
public <T> void assertIsNot(AssertionInfo info, T actual, Condition<? super T> condition) {
assertIsNotNull(condition);
if (condition.matches(actual)) throw failures.failure(info, shouldNotBe(actual, condition));
}
/**
* Asserts that the actual value satisfies the given <code>{@link Condition}</code>.
* @param <T> the type of the actual value and the type of values that given {@code Condition} takes.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given {@code Condition} is {@code null}.
* @throws AssertionError if the actual value does not satisfy the given {@code Condition}.
*/
public <T> void assertHas(AssertionInfo info, T actual, Condition<? super T> condition) {
assertIsNotNull(condition);
if (!condition.matches(actual)) throw failures.failure(info, shouldHave(actual, condition));
}
/**
* Asserts that the actual value does not satisfy the given <code>{@link Condition}</code>.
* @param <T> the type of the actual value and the type of values that given {@code Condition} takes.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given {@code Condition} is {@code null}.
* @throws AssertionError if the actual value satisfies the given {@code Condition}.
*/
public <T> void assertDoesNotHave(AssertionInfo info, T actual, Condition<? super T> condition) {
assertIsNotNull(condition);
if (condition.matches(actual)) throw failures.failure(info, shouldNotHave(actual, condition));
}
public <T> void assertSatisfies(AssertionInfo info, T actual, Condition<? super T> condition) {
assertIsNotNull(condition);
if (!condition.matches(actual)) throw failures.failure(info, shouldSatisfy(actual, condition));
}
/**
* Asserts the given <code>{@link Condition}</code> is not null.
* @param condition the given {@code Condition}.
* @throws NullPointerException if the given {@code Condition} is {@code null}.
*/
public void assertIsNotNull(Condition<?> condition) {<FILL_FUNCTION_BODY>}
/**
* Asserts the given <code>{@link Condition}</code> is not null.
* @param condition the given {@code Condition}.
* @param format as in {@link String#format(String, Object...)}
* @param args as in {@link String#format(String, Object...)}
* @throws NullPointerException if the given {@code Condition} is {@code null}.
*/
public void assertIsNotNull(Condition<?> condition, String format, Object... args) {
requireNonNull(condition, format(format, args));
}
}
|
assertIsNotNull(condition, "The condition to evaluate should not be null");
| 1,203
| 21
| 1,224
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/ConfigurableRecursiveFieldByFieldComparator.java
|
ConfigurableRecursiveFieldByFieldComparator
|
toString
|
class ConfigurableRecursiveFieldByFieldComparator implements Comparator<Object> {
private RecursiveComparisonConfiguration configuration;
private RecursiveComparisonDifferenceCalculator recursiveComparisonDifferenceCalculator;
// for testing
ConfigurableRecursiveFieldByFieldComparator(RecursiveComparisonConfiguration configuration,
RecursiveComparisonDifferenceCalculator recursiveComparisonDifferenceCalculator) {
requireNonNull(configuration, "RecursiveComparisonConfiguration must not be null");
this.configuration = configuration;
this.recursiveComparisonDifferenceCalculator = recursiveComparisonDifferenceCalculator;
}
public ConfigurableRecursiveFieldByFieldComparator(RecursiveComparisonConfiguration configuration) {
this(configuration, new RecursiveComparisonDifferenceCalculator());
}
@Override
public int compare(Object actual, Object other) {
if (actual == null && other == null) return 0;
if (actual == null || other == null) return NOT_EQUAL;
return areEqual(actual, other) ? 0 : NOT_EQUAL;
}
protected boolean areEqual(Object actual, Object other) {
try {
return recursiveComparisonDifferenceCalculator.determineDifferences(actual, other, configuration).isEmpty();
} catch (@SuppressWarnings("unused") IntrospectionError e) {
return false;
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(configuration);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ConfigurableRecursiveFieldByFieldComparator other = (ConfigurableRecursiveFieldByFieldComparator) obj;
return Objects.equals(configuration, other.configuration);
}
}
|
return format("recursive field/property by field/property comparator on all fields/properties using the following configuration:%n%s",
configuration);
| 498
| 39
| 537
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Diff.java
|
Diff
|
linesFromBufferedReader
|
class Diff {
@VisibleForTesting
public List<Delta<String>> diff(InputStream actual, InputStream expected) throws IOException {
return diff(readerFor(actual), readerFor(expected));
}
@VisibleForTesting
public List<Delta<String>> diff(InputStream actual, String expected) throws IOException {
return diff(readerFor(actual), readerFor(expected));
}
@VisibleForTesting
public List<Delta<String>> diff(File actual, Charset actualCharset, File expected, Charset expectedCharset) throws IOException {
return diff(actual.toPath(), actualCharset, expected.toPath(), expectedCharset);
}
@VisibleForTesting
public List<Delta<String>> diff(Path actual, Charset actualCharset, Path expected, Charset expectedCharset) throws IOException {
return diff(newBufferedReader(actual, actualCharset), newBufferedReader(expected, expectedCharset));
}
@VisibleForTesting
public List<Delta<String>> diff(File actual, String expected, Charset charset) throws IOException {
return diff(actual.toPath(), expected, charset);
}
@VisibleForTesting
public List<Delta<String>> diff(Path actual, String expected, Charset charset) throws IOException {
return diff(newBufferedReader(actual, charset), readerFor(expected));
}
private BufferedReader readerFor(InputStream stream) {
return new BufferedReader(new InputStreamReader(stream, Charset.defaultCharset()));
}
private BufferedReader readerFor(String string) {
return new BufferedReader(new StringReader(string));
}
private List<Delta<String>> diff(BufferedReader actual, BufferedReader expected) throws IOException {
try {
List<String> actualLines = linesFromBufferedReader(actual);
List<String> expectedLines = linesFromBufferedReader(expected);
Patch<String> patch = DiffUtils.diff(expectedLines, actualLines);
return unmodifiableList(patch.getDeltas());
} finally {
closeQuietly(actual, expected);
}
}
private List<String> linesFromBufferedReader(BufferedReader reader) throws IOException {<FILL_FUNCTION_BODY>}
}
|
String line;
List<String> lines = new ArrayList<>();
while ((line = reader.readLine()) != null) {
lines.add(line);
}
return lines;
| 567
| 52
| 619
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Digests.java
|
Digests
|
digestDiff
|
class Digests {
private static final int BUFFER_SIZE = 1024 * 8;
private Digests() {}
public static String toHex(byte[] digest) {
requireNonNull(digest, "The digest should not be null");
StringBuilder hex = new StringBuilder(digest.length * 2);
for (byte b : digest) {
hex.append(byteToHexString(b));
}
return hex.toString();
}
public static byte[] fromHex(String digest) {
requireNonNull(digest, "The digest should not be null");
byte[] bytes = new byte[digest.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = Integer.valueOf(digest.substring(i * 2, (i + 1) * 2), 16).byteValue();
}
return bytes;
}
public static DigestDiff digestDiff(InputStream stream, MessageDigest messageDigest, byte[] expected) throws IOException {<FILL_FUNCTION_BODY>}
}
|
requireNonNull(stream, "The stream should not be null");
requireNonNull(messageDigest, "The digest should not be null");
requireNonNull(expected, "The expected should not be null");
messageDigest.reset();
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = stream.read(buffer)) > 0) {
messageDigest.update(buffer, 0, len);
}
byte[] actualDigest = messageDigest.digest();
String expectedHex = toHex(expected);
String actualHex = toHex(actualDigest);
return new DigestDiff(actualHex, expectedHex, messageDigest);
| 281
| 177
| 458
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Doubles.java
|
Doubles
|
absDiff
|
class Doubles extends RealNumbers<Double> {
private static final Doubles INSTANCE = new Doubles();
/**
* Returns the singleton instance of this class based on {@link StandardComparisonStrategy}.
*
* @return the singleton instance of this class based on {@link StandardComparisonStrategy}.
*/
public static Doubles instance() {
return INSTANCE;
}
@VisibleForTesting
Doubles() {
super();
}
public Doubles(ComparisonStrategy comparisonStrategy) {
super(comparisonStrategy);
}
@Override
protected Double zero() {
return 0.0d;
}
@Override
protected Double one() {
return 1.0d;
}
@Override
protected Double NaN() {
return Double.NaN;
}
@Override
protected Double absDiff(Double actual, Double other) {<FILL_FUNCTION_BODY>}
@Override
protected boolean isFinite(Double value) {
return Double.isFinite(value);
}
@Override
protected boolean isNotFinite(Double value) {
return !Double.isFinite(value);
}
@Override
protected boolean isInfinite(Double value) {
return Double.isInfinite(value);
}
@Override
protected boolean isNotInfinite(Double value) {
return !Double.isInfinite(value);
}
@Override
protected boolean isNaN(Double value) {
return Double.isNaN(value);
}
}
|
return isNanOrInfinite(actual) || isNanOrInfinite(other)
? abs(actual - other)
: abs(absBigDecimalDiff(actual, other).doubleValue());
| 405
| 52
| 457
|
<methods>public void assertIsFinite(org.assertj.core.api.AssertionInfo, java.lang.Double) ,public void assertIsInfinite(org.assertj.core.api.AssertionInfo, java.lang.Double) ,public void assertIsNaN(org.assertj.core.api.AssertionInfo, java.lang.Double) ,public void assertIsNotFinite(org.assertj.core.api.AssertionInfo, java.lang.Double) ,public void assertIsNotInfinite(org.assertj.core.api.AssertionInfo, java.lang.Double) ,public void assertIsNotNaN(org.assertj.core.api.AssertionInfo, java.lang.Double) ,public boolean isNanOrInfinite(java.lang.Double) <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/ElementsSatisfyingConsumer.java
|
ElementsSatisfyingConsumer
|
withoutElement
|
class ElementsSatisfyingConsumer<E> {
private final List<E> elements;
ElementsSatisfyingConsumer(Iterable<? extends E> actual, Consumer<? super E> assertions) {
this(filterByPassingAssertions(actual, assertions));
}
private static <E> List<E> filterByPassingAssertions(Iterable<? extends E> actual, Consumer<? super E> assertions) {
return stream(actual).filter(byPassingAssertions(assertions)).collect(toList());
}
private ElementsSatisfyingConsumer(List<E> elements) {
this.elements = elements;
}
List<E> getElements() {
return elements;
}
/**
* New <code>ElementsSatisfyingConsumer</code> containing all elements except the first occurrence of the given element.
*
* <p> This instance is not modified.
*
* @param element the element to remove from the result
* @return all except the given element
*/
ElementsSatisfyingConsumer<E> withoutElement(E element) {<FILL_FUNCTION_BODY>}
private static void removeFirstReference(Object element, List<?> elements) {
range(0, elements.size()).filter(i -> elements.get(i) == element)
.findFirst()
.ifPresent(elements::remove);
}
}
|
ArrayList<E> listWithoutElement = new ArrayList<>(elements);
removeFirstReference(element, listWithoutElement);
return new ElementsSatisfyingConsumer<>(listWithoutElement);
| 357
| 47
| 404
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/ErrorMessages.java
|
ErrorMessages
|
endDateToCompareActualWithIsNull
|
class ErrorMessages {
public static String arrayIsNull() {
return "The given array should not be null";
}
public static String arrayIsEmpty() {
return "The given array should not be empty";
}
public static String iterableIsNull() {
return "The given iterable should not be null";
}
public static String iterableIsEmpty() {
return "The given iterable should not be empty";
}
public static String descriptionIsNull() {
return "The description to set should not be null";
}
public static String keysToLookForIsEmpty(String placeholder) {
return String.format("The %s to look for should not be empty", placeholder);
}
public static String keysToLookForIsNull(String placeholder) {
return String.format("The %s to look for should not be null", placeholder);
}
public static String entriesToLookForIsEmpty() {
return "The array of entries to look for should not be empty";
}
public static String entriesToLookForIsNull() {
return "The array of entries to look for should not be null";
}
public static String mapOfEntriesToLookForIsNull() {
return "The map of entries to look for should not be null";
}
public static String entryToLookForIsNull() {
return "Entries to look for should not be null";
}
public static String isNotArray(Object o) {
return String.format("The object <%s> should be an array", o);
}
public static String iterableToLookForIsNull() {
return "The iterable to look for should not be null";
}
public static String offsetIsNull() {
return "The given offset should not be null";
}
public static String offsetValueIsNotPositive() {
return "An offset value should be greater than or equal to zero";
}
public static String strictOffsetValueIsNotStrictlyPositive() {
return "A strict offset value should be greater than zero";
}
public static String percentageValueIsInRange(Number number) {
return String.format("The percentage value <%s> should be greater than or equal to zero", number.doubleValue());
}
public static String regexPatternIsNull() {
return "The regular expression pattern to match should not be null";
}
public static String charSequenceToLookForIsNull() {
return "The char sequence to look for should not be null";
}
public static String valuesToLookForIsEmpty() {
return "The array of values to look for should not be empty";
}
public static String valuesToLookForIsNull() {
return "The array of values to look for should not be null";
}
public static String iterableValuesToLookForIsEmpty() {
return "The iterable of values to look for should not be empty";
}
public static String iterableValuesToLookForIsNull() {
return "The iterable of values to look for should not be null";
}
public static String dateToCompareActualWithIsNull() {
return "The date to compare actual with should not be null";
}
public static String startDateToCompareActualWithIsNull() {
return "The start date of period to compare actual with should not be null";
}
public static String endDateToCompareActualWithIsNull() {<FILL_FUNCTION_BODY>}
public static String arrayOfValuesToLookForIsNull() {
return "The array of values to look for should not be null";
}
public static String arrayOfValuesToLookForIsEmpty() {
return "The array of values to look for should not be empty";
}
public static String predicateIsNull() {
return "The predicate must not be null";
}
public static String emptySequence() {
return "The sequence of values should not be empty";
}
public static String emptySubsequence() {
return "The subsequence of values should not be empty";
}
public static String nullSequence() {
return "The sequence of values should not be null";
}
public static String nullSubsequence() {
return "The subsequence of values should not be null";
}
private ErrorMessages() {}
}
|
return "The end date of period to compare actual with should not be null";
| 1,076
| 21
| 1,097
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/ExtendedByTypesComparator.java
|
ExtendedByTypesComparator
|
compare
|
class ExtendedByTypesComparator implements Comparator<Object> {
private final Comparator<Object> comparator;
private final TypeComparators comparatorsByType;
public ExtendedByTypesComparator(TypeComparators comparatorsByType) {
this(
new Comparator<Object>() {
@Override
public int compare(Object actual, Object other) {
return Objects.deepEquals(actual, other) ? 0 : NOT_EQUAL;
}
@Override
public String toString() {
return "AssertJ Object comparator";
}
}, comparatorsByType);
}
public ExtendedByTypesComparator(Comparator<Object> comparator, TypeComparators comparatorsByType) {
this.comparator = comparator;
this.comparatorsByType = comparatorsByType;
}
@Override
@SuppressWarnings("unchecked")
public int compare(Object actual, Object other) {<FILL_FUNCTION_BODY>}
public Comparator<Object> getComparator() {
return comparator;
}
@Override
public String toString() {
// only used in element comparator
return comparatorsByType.isEmpty()
? format("%s", comparator)
: format("%s%n- for elements (by type): %s", comparator, comparatorsByType);
}
}
|
// value returned is not relevant for ordering if objects are not equal
if (actual == null && other == null) return 0;
if (actual == null || other == null) return NOT_EQUAL;
@SuppressWarnings("rawtypes")
Comparator comparatorByType = comparatorsByType == null ? null : comparatorsByType.getComparatorForType(actual.getClass());
if (comparatorByType != null) {
return other.getClass().isInstance(actual) ? comparatorByType.compare(actual, other) : NOT_EQUAL;
}
return comparator.compare(actual, other);
| 361
| 164
| 525
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/FieldByFieldComparator.java
|
FieldByFieldComparator
|
compare
|
class FieldByFieldComparator implements Comparator<Object> {
protected final Map<String, Comparator<?>> comparatorsByPropertyOrField;
protected final TypeComparators comparatorsByType;
public FieldByFieldComparator(Map<String, Comparator<?>> comparatorsByPropertyOrField,
TypeComparators typeComparators) {
this.comparatorsByPropertyOrField = comparatorsByPropertyOrField == null
? new TreeMap<>()
: comparatorsByPropertyOrField;
this.comparatorsByType = isNullOrEmpty(typeComparators) ? defaultTypeComparators() : typeComparators;
}
public FieldByFieldComparator() {
this(new TreeMap<>(), defaultTypeComparators());
}
@Override
public int compare(Object actual, Object other) {<FILL_FUNCTION_BODY>}
protected boolean areEqual(Object actual, Object other) {
try {
return Objects.instance().areEqualToIgnoringGivenFields(actual, other, comparatorsByPropertyOrField,
comparatorsByType);
} catch (IntrospectionError e) {
return false;
}
}
@Override
public String toString() {
return description() + describeUsedComparators();
}
protected String description() {
return "field/property by field/property comparator on all fields/properties";
}
protected String describeUsedComparators() {
if (comparatorsByPropertyOrField.isEmpty()) {
return format("%nComparators used:%n%s", describeFieldComparatorsByType());
}
return format("%nComparators used:%n%s%n%s", describeFieldComparatorsByName(), describeFieldComparatorsByType());
}
protected String describeFieldComparatorsByType() {
return format("- for elements fields (by type): %s", comparatorsByType);
}
protected String describeFieldComparatorsByName() {
if (comparatorsByPropertyOrField.isEmpty()) {
return "";
}
List<String> fieldComparatorsDescription = this.comparatorsByPropertyOrField.entrySet().stream()
.map(FieldByFieldComparator::formatFieldComparator)
.collect(toList());
return format("- for elements fields (by name): {%s}", join(fieldComparatorsDescription).with(", "));
}
private static String formatFieldComparator(Entry<String, Comparator<?>> next) {
return next.getKey() + " -> " + next.getValue();
}
private static boolean isNullOrEmpty(TypeComparators comparatorByType) {
return comparatorByType == null || comparatorByType.isEmpty();
}
}
|
if (actual == null && other == null) return 0;
if (actual == null || other == null) return NOT_EQUAL;
// value returned is not relevant for ordering if objects are not equal.
return areEqual(actual, other) ? 0 : NOT_EQUAL;
| 705
| 74
| 779
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Floats.java
|
Floats
|
absDiff
|
class Floats extends RealNumbers<Float> {
private static final Floats INSTANCE = new Floats();
/**
* Returns the singleton instance of this class based on {@link StandardComparisonStrategy}.
*
* @return the singleton instance of this class based on {@link StandardComparisonStrategy}.
*/
public static Floats instance() {
return INSTANCE;
}
@VisibleForTesting
Floats() {
super();
}
public Floats(ComparisonStrategy comparisonStrategy) {
super(comparisonStrategy);
}
@Override
protected Float zero() {
return 0.0f;
}
@Override
protected Float one() {
return 1.0f;
}
@Override
protected Float NaN() {
return Float.NaN;
}
@Override
protected Float absDiff(Float actual, Float other) {<FILL_FUNCTION_BODY>}
@Override
protected boolean isFinite(Float value) {
return Float.isFinite(value);
}
@Override
protected boolean isNotFinite(Float value) {
return !Float.isFinite(value);
}
@Override
protected boolean isInfinite(Float value) {
return Float.isInfinite(value);
}
@Override
protected boolean isNotInfinite(Float value) {
return !Float.isInfinite(value);
}
@Override
protected boolean isNaN(Float value) {
return Float.isNaN(value);
}
}
|
return isNanOrInfinite(actual) || isNanOrInfinite(other)
? abs(actual - other)
: abs(absBigDecimalDiff(actual, other).floatValue());
| 414
| 52
| 466
|
<methods>public void assertIsFinite(org.assertj.core.api.AssertionInfo, java.lang.Float) ,public void assertIsInfinite(org.assertj.core.api.AssertionInfo, java.lang.Float) ,public void assertIsNaN(org.assertj.core.api.AssertionInfo, java.lang.Float) ,public void assertIsNotFinite(org.assertj.core.api.AssertionInfo, java.lang.Float) ,public void assertIsNotInfinite(org.assertj.core.api.AssertionInfo, java.lang.Float) ,public void assertIsNotNaN(org.assertj.core.api.AssertionInfo, java.lang.Float) ,public boolean isNanOrInfinite(java.lang.Float) <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Futures.java
|
Futures
|
assertSucceededWithin
|
class Futures {
private static final Futures INSTANCE = new Futures();
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static Futures instance() {
return INSTANCE;
}
@VisibleForTesting
Failures failures = Failures.instance();
/**
* Verifies that the {@link Future} is cancelled.
* @param info contains information about the assertion.
* @param actual the "actual" {@code Date}.
*/
public void assertIsCancelled(AssertionInfo info, Future<?> actual) {
assertNotNull(info, actual);
if (!actual.isCancelled())
throw failures.failure(info, shouldBeCancelled(actual));
}
/**
* Verifies that the {@link Future} is not cancelled.
* @param info contains information about the assertion.
* @param actual the "actual" {@code Date}.
*/
public void assertIsNotCancelled(AssertionInfo info, Future<?> actual) {
assertNotNull(info, actual);
if (actual.isCancelled())
throw failures.failure(info, shouldNotBeCancelled(actual));
}
/**
* Verifies that the {@link Future} is done.
* @param info contains information about the assertion.
* @param actual the "actual" {@code Date}.
*/
public void assertIsDone(AssertionInfo info, Future<?> actual) {
assertNotNull(info, actual);
if (!actual.isDone())
throw failures.failure(info, shouldBeDone(actual));
}
/**
* Verifies that the {@link Future} is not done.
* @param info contains information about the assertion.
* @param actual the "actual" {@code Date}.
*/
public void assertIsNotDone(AssertionInfo info, Future<?> actual) {
assertNotNull(info, actual);
if (actual.isDone())
throw failures.failure(info, shouldNotBeDone(actual));
}
public <RESULT> RESULT assertSucceededWithin(AssertionInfo info, Future<RESULT> actual, long timeout, TimeUnit unit) {
assertNotNull(info, actual);
try {
return actual.get(timeout, unit);
} catch (InterruptedException | ExecutionException | TimeoutException | CancellationException e) {
throw failures.failure(info, shouldBeCompletedWithin(actual, timeout, unit, e));
}
}
public <RESULT> RESULT assertSucceededWithin(AssertionInfo info, Future<RESULT> actual, Duration timeout) {<FILL_FUNCTION_BODY>}
public Exception assertFailedWithin(AssertionInfo info, Future<?> actual, Duration timeout) {
assertNotNull(info, actual);
try {
actual.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
throw failures.failure(info, shouldHaveFailedWithin(actual, timeout));
} catch (InterruptedException | ExecutionException | TimeoutException | CancellationException e) {
return e;
}
}
public Exception assertFailedWithin(AssertionInfo info, Future<?> actual, long timeout, TimeUnit unit) {
assertNotNull(info, actual);
try {
actual.get(timeout, unit);
throw failures.failure(info, shouldHaveFailedWithin(actual, timeout, unit));
} catch (InterruptedException | ExecutionException | TimeoutException | CancellationException e) {
return e;
}
}
private void assertNotNull(AssertionInfo info, Future<?> actual) {
Objects.instance().assertNotNull(info, actual);
}
}
|
assertNotNull(info, actual);
try {
return actual.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException | CancellationException e) {
throw failures.failure(info, shouldBeCompletedWithin(actual, timeout, e));
}
| 957
| 90
| 1,047
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/IgnoringFieldsComparator.java
|
IgnoringFieldsComparator
|
areEqual
|
class IgnoringFieldsComparator extends FieldByFieldComparator {
private final String[] fields;
public IgnoringFieldsComparator(Map<String, Comparator<?>> comparatorByPropertyOrField,
TypeComparators comparatorByType, String... fields) {
super(comparatorByPropertyOrField, comparatorByType);
this.fields = fields;
}
public IgnoringFieldsComparator(String... fields) {
this(new HashMap<>(), defaultTypeComparators(), fields);
}
@VisibleForTesting
public String[] getFields() {
return fields;
}
@Override
protected boolean areEqual(Object actualElement, Object otherElement) {<FILL_FUNCTION_BODY>}
@Override
protected String description() {
return "field/property by field/property comparator on all fields/properties except "
+ CONFIGURATION_PROVIDER.representation().toStringOf(fields);
}
}
|
try {
return Objects.instance().areEqualToIgnoringGivenFields(actualElement, otherElement, comparatorsByPropertyOrField,
comparatorsByType, fields);
} catch (IntrospectionError e) {
return false;
}
| 248
| 66
| 314
|
<methods>public void <init>(Map<java.lang.String,Comparator<?>>, org.assertj.core.internal.TypeComparators) ,public void <init>() ,public int compare(java.lang.Object, java.lang.Object) ,public java.lang.String toString() <variables>protected final non-sealed Map<java.lang.String,Comparator<?>> comparatorsByPropertyOrField,protected final non-sealed org.assertj.core.internal.TypeComparators comparatorsByType
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/IndexedDiff.java
|
IndexedDiff
|
equals
|
class IndexedDiff {
public final Object actual;
public final Object expected;
public final int index;
/**
* Create a {@link IndexedDiff}.
* @param actual the actual value of the diff.
* @param expected the expected value of the diff.
* @param index the index the diff occurred at.
*/
public IndexedDiff(Object actual, Object expected, int index) {
this.actual = actual;
this.expected = expected;
this.index = index;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return String.format("IndexedDiff(actual=%s, expected=%s, index=%s)", this.actual, this.expected, this.index);
}
@Override
public int hashCode() {
return Objects.hash(actual, expected, index);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IndexedDiff that = (IndexedDiff) o;
return index == that.index && Objects.equals(actual, that.actual) && Objects.equals(expected, that.expected);
| 242
| 81
| 323
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/InputStreams.java
|
InputStreams
|
assertHasBinaryContent
|
class InputStreams {
private static final InputStreams INSTANCE = new InputStreams();
/**
* Returns the singleton instance of this class.
* @return the singleton instance of this class.
*/
public static InputStreams instance() {
return INSTANCE;
}
@VisibleForTesting
Diff diff = new Diff();
@VisibleForTesting
BinaryDiff binaryDiff = new BinaryDiff();
@VisibleForTesting
Failures failures = Failures.instance();
@VisibleForTesting
InputStreams() {}
/**
* Asserts that the given InputStreams have same content.
*
* @param info contains information about the assertion.
* @param actual the "actual" InputStream.
* @param expected the "expected" InputStream.
* @throws NullPointerException if {@code expected} is {@code null}.
* @throws AssertionError if {@code actual} is {@code null}.
* @throws AssertionError if the given InputStreams do not have same content.
* @throws InputStreamsException if an I/O error occurs.
*/
public void assertSameContentAs(AssertionInfo info, InputStream actual, InputStream expected) {
requireNonNull(expected, "The InputStream to compare to should not be null");
assertNotNull(info, actual);
try {
List<Delta<String>> diffs = diff.diff(actual, expected);
if (diffs.isEmpty()) return;
throw failures.failure(info, shouldHaveSameContent(actual, expected, diffs));
} catch (IOException e) {
String msg = format("Unable to compare contents of InputStreams:%n <%s>%nand:%n <%s>", actual, expected);
throw new InputStreamsException(msg, e);
}
}
/**
* Asserts that the given InputStream has the same content as the given String.
*
* @param info contains information about the assertion.
* @param actual the actual InputStream.
* @param expected the expected String.
* @throws NullPointerException if {@code expected} is {@code null}.
* @throws AssertionError if {@code actual} is {@code null}.
* @throws AssertionError if the given InputStream does not have the same content as the given String.
* @throws InputStreamsException if an I/O error occurs.
*/
public void assertHasContent(AssertionInfo info, InputStream actual, String expected) {
requireNonNull(expected, "The String to compare to should not be null");
assertNotNull(info, actual);
try {
List<Delta<String>> diffs = diff.diff(actual, expected);
if (diffs.isEmpty()) return;
throw failures.failure(info, shouldHaveSameContent(actual, expected, diffs));
} catch (IOException e) {
String msg = format("Unable to compare contents of InputStream:%n <%s>%nand String:%n <%s>", actual, expected);
throw new InputStreamsException(msg, e);
}
}
/**
* Asserts that the given InputStream has the given binary content.
* @param info contains information about the assertion.
* @param actual the actual InputStream.
* @param expected the expected binary content.
* @throws NullPointerException if {@code expected} is {@code null}.
* @throws AssertionError if {@code actual} is {@code null}.
* @throws AssertionError if the given InputStream does not have the same content as the given String.
* @throws InputStreamsException if an I/O error occurs.
*/
public void assertHasBinaryContent(AssertionInfo info, InputStream actual, byte[] expected) {<FILL_FUNCTION_BODY>}
private static void assertNotNull(AssertionInfo info, InputStream stream) {
Objects.instance().assertNotNull(info, stream);
}
public void assertHasDigest(AssertionInfo info, InputStream actual, MessageDigest digest, byte[] expected) {
requireNonNull(digest, "The message digest algorithm should not be null");
requireNonNull(expected, "The binary representation of digest to compare to should not be null");
assertNotNull(info, actual);
try {
DigestDiff diff = digestDiff(actual, digest, expected);
if (diff.digestsDiffer()) throw failures.failure(info, shouldHaveDigest(actual, diff));
} catch (IOException e) {
String msg = format("Unable to calculate digest of InputStream:%n <%s>", actual);
throw new InputStreamsException(msg, e);
}
}
public void assertHasDigest(AssertionInfo info, InputStream actual, MessageDigest digest, String expected) {
requireNonNull(expected, "The string representation of digest to compare to should not be null");
assertHasDigest(info, actual, digest, Digests.fromHex(expected));
}
public void assertHasDigest(AssertionInfo info, InputStream actual, String algorithm, byte[] expected) {
requireNonNull(algorithm, "The message digest algorithm should not be null");
try {
assertHasDigest(info, actual, MessageDigest.getInstance(algorithm), expected);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(format("Unable to find digest implementation for: <%s>", algorithm), e);
}
}
public void assertHasDigest(AssertionInfo info, InputStream actual, String algorithm, String expected) {
requireNonNull(expected, "The string representation of digest to compare to should not be null");
assertHasDigest(info, actual, algorithm, Digests.fromHex(expected));
}
}
|
requireNonNull(expected, "The binary content to compare to should not be null");
assertNotNull(info, actual);
try {
BinaryDiffResult result = binaryDiff.diff(actual, expected);
if (result.hasNoDiff()) return;
throw failures.failure(info, shouldHaveBinaryContent(actual, result));
} catch (IOException e) {
throw new InputStreamsException(format("Unable to verify binary contents of InputStream:%n <%s>", actual), e);
}
| 1,418
| 128
| 1,546
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/IterableDiff.java
|
IterableDiff
|
isActualElementInExpected
|
class IterableDiff<T> {
private final ComparisonStrategy comparisonStrategy;
List<T> unexpected;
List<T> missing;
IterableDiff(Iterable<T> actual, Iterable<T> expected, ComparisonStrategy comparisonStrategy) {
this.comparisonStrategy = comparisonStrategy;
// return the elements in actual that are not in expected: actual - expected
this.unexpected = unexpectedActualElements(actual, expected);
// return the elements in expected that are not in actual: expected - actual
this.missing = missingActualElements(actual, expected);
}
static <T> IterableDiff<T> diff(Iterable<T> actual, Iterable<T> expected, ComparisonStrategy comparisonStrategy) {
return new IterableDiff<>(actual, expected, comparisonStrategy);
}
static <T> IterableDiff<T> diff(Iterable<T> actual, Iterable<T> expected) {
return diff(actual, expected, StandardComparisonStrategy.instance());
}
boolean differencesFound() {
return !unexpected.isEmpty() || !missing.isEmpty();
}
/**
* Returns the list of elements in the first iterable that are not in the second, i.e. first - second
*
* @param actual the list we want to subtract from
* @param expected the list to subtract
* @return the list of elements in the first iterable that are not in the second, i.e. first - second
*/
private List<T> unexpectedActualElements(Iterable<T> actual, Iterable<T> expected) {
List<T> missingInFirst = new ArrayList<>();
// use a copy to deal correctly with potential duplicates
List<T> copyOfExpected = newArrayList(expected);
for (T elementInActual : actual) {
if (isActualElementInExpected(elementInActual, copyOfExpected)) {
// remove the element otherwise a duplicate would be found in the case if there is one in actual
iterablesRemoveFirst(copyOfExpected, elementInActual);
} else {
missingInFirst.add(elementInActual);
}
}
return unmodifiableList(missingInFirst);
}
private boolean isActualElementInExpected(T elementInActual, List<T> copyOfExpected) {<FILL_FUNCTION_BODY>}
private List<T> missingActualElements(Iterable<T> actual, Iterable<T> expected) {
List<T> missingInExpected = new ArrayList<>();
// use a copy to deal correctly with potential duplicates
List<T> copyOfActual = newArrayList(actual);
for (T expectedElement : expected) {
if (iterableContains(copyOfActual, expectedElement)) {
// remove the element otherwise a duplicate would be found in the case if there is one in actual
iterablesRemoveFirst(copyOfActual, expectedElement);
} else {
missingInExpected.add(expectedElement);
}
}
return unmodifiableList(missingInExpected);
}
private boolean iterableContains(Iterable<?> actual, T expectedElement) {
return comparisonStrategy.iterableContains(actual, expectedElement);
}
private void iterablesRemoveFirst(Iterable<?> actual, T value) {
comparisonStrategy.iterablesRemoveFirst(actual, value);
}
}
|
// the order of comparisonStrategy.areEqual is important if element comparison is not symmetrical, we must compare actual to
// expected but not expected to actual, for ex recursive comparison where:
// - actual element is PersonDto, expected a list of Person
// - Person has more fields than PersonDto => comparing PersonDto to Person is ok as it looks at PersonDto fields only,
// --- the opposite always fails as the reference fields are Person fields and PersonDto does not have all of them.
return copyOfExpected.stream().anyMatch(expectedElement -> comparisonStrategy.areEqual(elementInActual, expectedElement));
| 822
| 148
| 970
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/IterableElementComparisonStrategy.java
|
IterableElementComparisonStrategy
|
areEqual
|
class IterableElementComparisonStrategy<T> extends StandardComparisonStrategy {
private final Comparator<? super T> elementComparator;
public IterableElementComparisonStrategy(Comparator<? super T> elementComparator) {
this.elementComparator = elementComparator;
}
@SuppressWarnings("unchecked")
@Override
public boolean areEqual(Object actual, Object other) {<FILL_FUNCTION_BODY>}
private boolean compareElementsOf(Iterable<T> actual, Iterable<T> other) {
if (sizeOf(actual) != sizeOf(other)) return false;
// compare their elements with elementComparator
Iterator<T> iterator = other.iterator();
for (T actualElement : actual) {
T otherElement = iterator.next();
if (elementComparator.compare(actualElement, otherElement) != 0) return false;
}
return true;
}
@Override
public String toString() {
return "IterableElementComparisonStrategy using " +
CONFIGURATION_PROVIDER.representation().toStringOf(elementComparator);
}
@Override
public String asText() {
return format("when comparing elements using %s",
CONFIGURATION_PROVIDER.representation().toStringOf(elementComparator));
}
@Override
public boolean isStandard() {
return false;
}
}
|
if (actual == null && other == null) return true;
if (actual == null || other == null) return false;
// expecting actual and other to be iterable<T>
return actual instanceof Iterable && other instanceof Iterable
&& compareElementsOf((Iterable<T>) actual, (Iterable<T>) other);
| 365
| 83
| 448
|
<methods>public boolean areEqual(java.lang.Object, java.lang.Object) ,public Iterable<?> duplicatesFrom(Iterable<?>) ,public static org.assertj.core.internal.StandardComparisonStrategy instance() ,public boolean isGreaterThan(java.lang.Object, java.lang.Object) ,public boolean isLessThan(java.lang.Object, java.lang.Object) ,public boolean isStandard() ,public boolean iterableContains(Iterable<?>, java.lang.Object) ,public void iterableRemoves(Iterable<?>, java.lang.Object) ,public void iterablesRemoveFirst(Iterable<?>, java.lang.Object) ,public boolean stringContains(java.lang.String, java.lang.String) ,public boolean stringEndsWith(java.lang.String, java.lang.String) ,public boolean stringStartsWith(java.lang.String, java.lang.String) <variables>private static final org.assertj.core.internal.StandardComparisonStrategy INSTANCE
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/ObjectArrayElementComparisonStrategy.java
|
ObjectArrayElementComparisonStrategy
|
areEqual
|
class ObjectArrayElementComparisonStrategy<T> extends StandardComparisonStrategy {
private final Comparator<? super T> elementComparator;
public ObjectArrayElementComparisonStrategy(Comparator<? super T> elementComparator) {
this.elementComparator = elementComparator;
}
@SuppressWarnings("unchecked")
@Override
public boolean areEqual(Object actual, Object other) {<FILL_FUNCTION_BODY>}
private boolean compareElementsOf(T[] actual, T[] other) {
if (actual.length != other.length) return false;
// compare their elements with elementComparator
for (int i = 0; i < actual.length; i++) {
if (elementComparator.compare(actual[i], other[i]) != 0) return false;
}
return true;
}
@Override
public String toString() {
return "ObjectArrayElementComparisonStrategy using " + CONFIGURATION_PROVIDER.representation()
.toStringOf(elementComparator);
}
@Override
public String asText() {
return "when comparing elements using " + CONFIGURATION_PROVIDER.representation().toStringOf(elementComparator);
}
@Override
public boolean isStandard() {
return false;
}
}
|
if (actual == null && other == null) return true;
if (actual == null || other == null) return false;
// expecting actual and other to be T[]
return isArray(actual) && isArray(other) && compareElementsOf((T[]) actual, (T[]) other);
| 339
| 74
| 413
|
<methods>public boolean areEqual(java.lang.Object, java.lang.Object) ,public Iterable<?> duplicatesFrom(Iterable<?>) ,public static org.assertj.core.internal.StandardComparisonStrategy instance() ,public boolean isGreaterThan(java.lang.Object, java.lang.Object) ,public boolean isLessThan(java.lang.Object, java.lang.Object) ,public boolean isStandard() ,public boolean iterableContains(Iterable<?>, java.lang.Object) ,public void iterableRemoves(Iterable<?>, java.lang.Object) ,public void iterablesRemoveFirst(Iterable<?>, java.lang.Object) ,public boolean stringContains(java.lang.String, java.lang.String) ,public boolean stringEndsWith(java.lang.String, java.lang.String) ,public boolean stringStartsWith(java.lang.String, java.lang.String) <variables>private static final org.assertj.core.internal.StandardComparisonStrategy INSTANCE
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/OnFieldsComparator.java
|
OnFieldsComparator
|
areEqual
|
class OnFieldsComparator extends FieldByFieldComparator {
private final String[] fields;
public OnFieldsComparator(Map<String, Comparator<?>> comparatorByPropertyOrField,
TypeComparators comparatorByType, String... fields) {
super(comparatorByPropertyOrField, comparatorByType);
checkArgument(!isNullOrEmpty(fields), "No fields/properties specified");
for (String field : fields) {
checkArgument(!isNullOrEmpty(field) && !isNullOrEmpty(field.trim()),
"Null/blank fields/properties are invalid, fields/properties were %s",
CONFIGURATION_PROVIDER.representation().toStringOf(fields));
}
this.fields = fields;
}
public OnFieldsComparator(String... fields) {
this(new HashMap<>(), defaultTypeComparators(), fields);
}
@VisibleForTesting
public String[] getFields() {
return fields;
}
@Override
protected boolean areEqual(Object actualElement, Object otherElement) {<FILL_FUNCTION_BODY>}
@Override
protected String description() {
if (fields.length == 1) {
return "single field/property comparator on field/property " + CONFIGURATION_PROVIDER.representation()
.toStringOf(fields[0]);
}
return "field/property by field/property comparator on fields/properties "
+ CONFIGURATION_PROVIDER.representation().toStringOf(fields);
}
}
|
try {
return Objects.instance().areEqualToComparingOnlyGivenFields(actualElement, otherElement,
comparatorsByPropertyOrField, comparatorsByType,
fields);
} catch (IntrospectionError e) {
return false;
}
| 390
| 70
| 460
|
<methods>public void <init>(Map<java.lang.String,Comparator<?>>, org.assertj.core.internal.TypeComparators) ,public void <init>() ,public int compare(java.lang.Object, java.lang.Object) ,public java.lang.String toString() <variables>protected final non-sealed Map<java.lang.String,Comparator<?>> comparatorsByPropertyOrField,protected final non-sealed org.assertj.core.internal.TypeComparators comparatorsByType
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Predicates.java
|
Predicates
|
assertIsNotNull
|
class Predicates {
private static final Predicates INSTANCE = new Predicates();
/**
* Returns the singleton instance of this class.
* @return the singleton instance of this class.
*/
public static Predicates instance() {
return INSTANCE;
}
@VisibleForTesting
Failures failures = Failures.instance();
@VisibleForTesting
Predicates() {}
/**
* Asserts the given <code>{@link Predicate}</code> is not null.
* @param predicate the given {@code Predicate}.
* @throws NullPointerException if the given {@code Predicate} is {@code null}.
*/
public void assertIsNotNull(Predicate<?> predicate) {<FILL_FUNCTION_BODY>}
}
|
requireNonNull(predicate, "The predicate to evaluate should not be null");
| 207
| 22
| 229
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/RealNumbers.java
|
RealNumbers
|
absBigDecimalDiff
|
class RealNumbers<NUMBER extends Number & Comparable<NUMBER>> extends Numbers<NUMBER> {
protected RealNumbers() {
super();
}
protected RealNumbers(ComparisonStrategy comparisonStrategy) {
super(comparisonStrategy);
}
/**
* Verifies that the actual value is equal to {@code NaN}.<br>
* It does not rely on the custom comparisonStrategy (if one is set).
*
* @param info contains information about the assertion.
* @param actual the actual value.
* @throws AssertionError if the actual value is not equal to {@code NaN}.
*/
public void assertIsNaN(AssertionInfo info, NUMBER actual) {
assertEqualByComparison(info, actual, NaN());
}
protected BigDecimal absBigDecimalDiff(NUMBER number1, NUMBER number2) {<FILL_FUNCTION_BODY>}
protected abstract NUMBER NaN();
/**
* Verifies that the actual value is not equal to {@code NaN}.
* @param info contains information about the assertion.
* @param actual the actual value.
* @throws AssertionError if the actual value is equal to {@code NaN}.
*/
public void assertIsNotNaN(AssertionInfo info, NUMBER actual) {
assertNotEqualByComparison(info, actual, NaN());
}
@Override
protected boolean isGreaterThan(NUMBER value, NUMBER other) {
return value.compareTo(other) > 0;
}
public void assertIsFinite(AssertionInfo info, NUMBER actual) {
assertNotNull(info, actual);
if (isFinite(actual)) return;
throw failures.failure(info, shouldBeFinite(actual));
}
protected abstract boolean isFinite(NUMBER value);
public void assertIsNotFinite(AssertionInfo info, NUMBER actual) {
assertNotNull(info, actual);
if (isNotFinite(actual)) return;
throw failures.failure(info, shouldNotBeFinite(actual));
}
protected abstract boolean isNotFinite(NUMBER value);
public void assertIsInfinite(AssertionInfo info, NUMBER actual) {
assertNotNull(info, actual);
if (isInfinite(actual)) return;
throw failures.failure(info, shouldBeInfinite(actual));
}
protected abstract boolean isInfinite(NUMBER value);
public void assertIsNotInfinite(AssertionInfo info, NUMBER actual) {
assertNotNull(info, actual);
if (isNotInfinite(actual)) return;
throw failures.failure(info, shouldNotBeInfinite(actual));
}
/**
* Returns true is if the given value is Nan or Infinite, false otherwise.
*
* @param value the value to check
* @return true is if the given value is Nan or Infinite, false otherwise.
*/
public boolean isNanOrInfinite(NUMBER value) {
return isNaN(value) || isInfinite(value);
}
protected abstract boolean isNaN(NUMBER value);
protected abstract boolean isNotInfinite(NUMBER value);
}
|
BigDecimal number1AsbigDecimal = new BigDecimal(String.valueOf(number1));
BigDecimal number2AsbigDecimal = new BigDecimal(String.valueOf(number2));
return number1AsbigDecimal.subtract(number2AsbigDecimal).abs();
| 813
| 76
| 889
|
<methods>public void <init>() ,public void <init>(org.assertj.core.internal.ComparisonStrategy) ,public void assertIsBetween(org.assertj.core.api.AssertionInfo, NUMBER, NUMBER, NUMBER) ,public void assertIsCloseTo(org.assertj.core.api.AssertionInfo, NUMBER, NUMBER, Offset<NUMBER>) ,public void assertIsCloseToPercentage(org.assertj.core.api.AssertionInfo, NUMBER, NUMBER, org.assertj.core.data.Percentage) ,public void assertIsNegative(org.assertj.core.api.AssertionInfo, NUMBER) ,public void assertIsNotCloseTo(org.assertj.core.api.AssertionInfo, NUMBER, NUMBER, Offset<NUMBER>) ,public void assertIsNotCloseToPercentage(org.assertj.core.api.AssertionInfo, NUMBER, NUMBER, org.assertj.core.data.Percentage) ,public void assertIsNotNegative(org.assertj.core.api.AssertionInfo, NUMBER) ,public void assertIsNotPositive(org.assertj.core.api.AssertionInfo, NUMBER) ,public void assertIsNotZero(org.assertj.core.api.AssertionInfo, NUMBER) ,public void assertIsOne(org.assertj.core.api.AssertionInfo, NUMBER) ,public void assertIsPositive(org.assertj.core.api.AssertionInfo, NUMBER) ,public void assertIsStrictlyBetween(org.assertj.core.api.AssertionInfo, NUMBER, NUMBER, NUMBER) ,public void assertIsZero(org.assertj.core.api.AssertionInfo, NUMBER) <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/RecursiveHelper.java
|
RecursiveHelper
|
isContainer
|
class RecursiveHelper {
public static boolean isContainer(Object o) {<FILL_FUNCTION_BODY>}
}
|
return o instanceof Iterable ||
o instanceof Map ||
o instanceof Optional ||
o instanceof AtomicReference ||
o instanceof AtomicReferenceArray ||
o instanceof AtomicBoolean ||
o instanceof AtomicInteger ||
o instanceof AtomicIntegerArray ||
o instanceof AtomicLong ||
o instanceof AtomicLongArray ||
isArray(o);
| 33
| 89
| 122
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Spliterators.java
|
Spliterators
|
characteristicNames
|
class Spliterators {
/**
* Name for constant {@link Spliterator#DISTINCT}
*/
private static final String SPLITERATOR_DISTINCT = "DISTINCT";
/**
* Name for constant {@link Spliterator#SORTED}
*/
private static final String SPLITERATOR_SORTED = "SORTED";
/**
* Name for constant {@link Spliterator#ORDERED}
*/
private static final String SPLITERATOR_ORDERED = "ORDERED";
/**
* Name for constant {@link Spliterator#SIZED}
*/
private static final String SPLITERATOR_SIZED = "SIZED";
/**
* Name for constant {@link Spliterator#NONNULL}
*/
private static final String SPLITERATOR_NONNULL = "NONNULL";
/**
* Name for constant {@link Spliterator#IMMUTABLE}
*/
private static final String SPLITERATOR_IMMUTABLE = "IMMUTABLE";
/**
* Name for constant {@link Spliterator#CONCURRENT}
*/
private static final String SPLITERATOR_CONCURRENT = "CONCURRENT";
/**
* Name for constant {@link Spliterator#SUBSIZED}
*/
private static final String SPLITERATOR_SUBSIZED = "SUBSIZED";
private static final Spliterators INSTANCE = new Spliterators();
private final Iterables iterables = Iterables.instance();
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static Spliterators instance() {
return INSTANCE;
}
@VisibleForTesting
void setFailures(Failures failures) {
iterables.failures = failures;
}
/**
* Asserts the given <code>{@link Spliterator}</code> has the given characteristics.
*
* @param info contains information about the assertion.
* @param actual the given {@code Spliterator}.
* @param characteristics the expected characteristics.
* @throws AssertionError if the actual {@code Spliterator} is {@code null}.
* @throws AssertionError if the actual {@code Spliterator} does not have the expected characteristics.
*/
public void assertHasCharacteristics(AssertionInfo info, Spliterator<?> actual, int... characteristics) {
assertNotNull(info, actual);
Set<String> actualCharacteristicNames = characteristicNames(actual.characteristics());
Set<String> expectedCharacteristicNames = characteristicNames(characteristics);
iterables.assertContains(info, actualCharacteristicNames, expectedCharacteristicNames.toArray(new String[0]));
}
/**
* Asserts the given <code>{@link Spliterator}</code> has only the given characteristics and no else.
*
* @param info contains information about the assertion.
* @param actual the given {@code Spliterator}.
* @param characteristics the expected characteristics.
* @throws AssertionError if the actual {@code Spliterator} is {@code null}.
* @throws AssertionError if the actual {@code Spliterator} does not have the expected characteristics
* or the actual {@code Spliterator} has additional characteristics.
*/
public void assertHasOnlyCharacteristics(AssertionInfo info, Spliterator<?> actual, int... characteristics) {
assertNotNull(info, actual);
Set<String> actualCharacteristicNames = characteristicNames(actual.characteristics());
Set<String> expectedCharacteristicNames = characteristicNames(characteristics);
iterables.assertContainsOnly(info, actualCharacteristicNames, expectedCharacteristicNames.toArray(new String[0]));
}
private static Set<String> characteristicNames(int[] characteristics) {
Set<String> names = new HashSet<>();
for (int characteristic : characteristics) {
names.addAll(characteristicNames(characteristic));
}
return names;
}
private static Set<String> characteristicNames(int characteristics) {<FILL_FUNCTION_BODY>}
private static boolean hasCharacteristic(int characteristics, int expectedCharacteristic) {
return (characteristics & expectedCharacteristic) == expectedCharacteristic;
}
}
|
Set<String> names = new HashSet<>();
if (hasCharacteristic(characteristics, Spliterator.DISTINCT)) names.add(SPLITERATOR_DISTINCT);
if (hasCharacteristic(characteristics, Spliterator.SORTED)) names.add(SPLITERATOR_SORTED);
if (hasCharacteristic(characteristics, Spliterator.ORDERED)) names.add(SPLITERATOR_ORDERED);
if (hasCharacteristic(characteristics, Spliterator.SIZED)) names.add(SPLITERATOR_SIZED);
if (hasCharacteristic(characteristics, Spliterator.NONNULL)) names.add(SPLITERATOR_NONNULL);
if (hasCharacteristic(characteristics, Spliterator.IMMUTABLE)) names.add(SPLITERATOR_IMMUTABLE);
if (hasCharacteristic(characteristics, Spliterator.CONCURRENT)) names.add(SPLITERATOR_CONCURRENT);
if (hasCharacteristic(characteristics, Spliterator.SUBSIZED)) names.add(SPLITERATOR_SUBSIZED);
return names;
| 1,080
| 289
| 1,369
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/StandardComparisonStrategy.java
|
StandardComparisonStrategy
|
areEqual
|
class StandardComparisonStrategy extends AbstractComparisonStrategy {
private static final StandardComparisonStrategy INSTANCE = new StandardComparisonStrategy();
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static StandardComparisonStrategy instance() {
return INSTANCE;
}
/**
* Creates a new <code>{@link StandardComparisonStrategy}</code>, comparison strategy being based on
* {@link java.util.Objects#deepEquals(Object, Object)}.
*/
protected StandardComparisonStrategy() {
// empty
}
@Override
protected Set<Object> newSetUsingComparisonStrategy() {
// define a comparator so that we can use areEqual to compare objects in Set collections
// the "less than" comparison does not make much sense here but need to be defined.
return new TreeSet<>((o1, o2) -> {
if (areEqual(o1, o2)) return 0;
return Objects.hashCodeFor(o1) < Objects.hashCodeFor(o2) ? -1 : 1;
});
}
/**
* Returns {@code true} if the arguments are deeply equal to each other, {@code false} otherwise.
* <p>
* It mimics the behavior of {@link java.util.Objects#deepEquals(Object, Object)}, but without performing a reference
* check between the two arguments. According to {@code deepEquals} javadoc, the reference check should be delegated
* to the {@link Object#equals equals} method of the first argument, but this is not happening. Bug JDK-8196069 also
* mentions this gap.
*
* @param actual the object to compare to {@code other}
* @param other the object to compare to {@code actual}
* @return {@code true} if the arguments are deeply equal to each other, {@code false} otherwise
*
* @see <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8196069">JDK-8196069</a>
*
*/
@Override
public boolean areEqual(Object actual, Object other) {<FILL_FUNCTION_BODY>}
/**
* Returns true if given {@link Iterable} contains given value based on {@link java.util.Objects#deepEquals(Object, Object)},
* false otherwise.<br>
* If given {@link Iterable} is null, return false.
*
* @param iterable the {@link Iterable} to search value in
* @param value the object to look for in given {@link Iterable}
* @return true if given {@link Iterable} contains given value based on {@link java.util.Objects#deepEquals(Object, Object)},
* false otherwise.
*/
@Override
public boolean iterableContains(Iterable<?> iterable, Object value) {
if (iterable == null) {
return false;
}
return Streams.stream(iterable).anyMatch(object -> areEqual(object, value));
}
/**
* {@inheritDoc}
*/
@Override
public void iterableRemoves(Iterable<?> iterable, Object value) {
if (iterable == null) {
return;
}
// Avoid O(N^2) complexity of serial removal from an iterator of collections like ArrayList
if (iterable instanceof Collection) {
((Collection<?>) iterable).removeIf(o -> areEqual(o, value));
} else {
Iterator<?> iterator = iterable.iterator();
while (iterator.hasNext()) {
if (areEqual(iterator.next(), value)) {
iterator.remove();
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void iterablesRemoveFirst(Iterable<?> iterable, Object value) {
if (iterable == null) {
return;
}
Iterator<?> iterator = iterable.iterator();
while (iterator.hasNext()) {
if (areEqual(iterator.next(), value)) {
iterator.remove();
return;
}
}
}
/**
* Returns any duplicate elements from the given collection according to {@link java.util.Objects#deepEquals(Object, Object)}
* comparison strategy.
*
* @param iterable the given {@link Iterable} we want to extract duplicate elements.
* @return an {@link Iterable} containing the duplicate elements of the given one. If no duplicates are found, an
* empty {@link Iterable} is returned.
*/
// overridden to write javadoc.
@Override
public Iterable<?> duplicatesFrom(Iterable<?> iterable) {
return super.duplicatesFrom(iterable);
}
@Override
public boolean stringStartsWith(String string, String prefix) {
return string.startsWith(prefix);
}
@Override
public boolean stringEndsWith(String string, String suffix) {
return string.endsWith(suffix);
}
@Override
public boolean stringContains(String string, String sequence) {
return string.contains(sequence);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public boolean isGreaterThan(Object actual, Object other) {
checkArgumentIsComparable(actual);
return ((Comparable) actual).compareTo(other) > 0;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public boolean isLessThan(Object actual, Object other) {
checkArgumentIsComparable(actual);
return ((Comparable) actual).compareTo(other) < 0;
}
private void checkArgumentIsComparable(Object actual) {
checkArgument(actual instanceof Comparable, "argument '%s' should be Comparable but is not", actual);
}
@Override
public boolean isStandard() {
return true;
}
}
|
if (actual == null) return other == null;
Class<?> actualClass = actual.getClass();
if (actualClass.isArray() && other != null) {
Class<?> otherClass = other.getClass();
if (otherClass.isArray()) {
if (actualClass.getComponentType().isPrimitive() && otherClass.getComponentType().isPrimitive()) {
if (actual instanceof byte[] && other instanceof byte[])
return java.util.Arrays.equals((byte[]) actual, (byte[]) other);
if (actual instanceof short[] && other instanceof short[])
return java.util.Arrays.equals((short[]) actual, (short[]) other);
if (actual instanceof int[] && other instanceof int[])
return java.util.Arrays.equals((int[]) actual, (int[]) other);
if (actual instanceof long[] && other instanceof long[])
return java.util.Arrays.equals((long[]) actual, (long[]) other);
if (actual instanceof char[] && other instanceof char[])
return java.util.Arrays.equals((char[]) actual, (char[]) other);
if (actual instanceof float[] && other instanceof float[])
return java.util.Arrays.equals((float[]) actual, (float[]) other);
if (actual instanceof double[] && other instanceof double[])
return java.util.Arrays.equals((double[]) actual, (double[]) other);
if (actual instanceof boolean[] && other instanceof boolean[])
return java.util.Arrays.equals((boolean[]) actual, (boolean[]) other);
}
if (actual instanceof Object[] && other instanceof Object[])
return java.util.Arrays.deepEquals((Object[]) actual, (Object[]) other);
}
}
return actual.equals(other);
| 1,540
| 453
| 1,993
|
<methods>public non-sealed void <init>() ,public boolean arrayContains(java.lang.Object, java.lang.Object) ,public Iterable<?> duplicatesFrom(Iterable<?>) ,public boolean isGreaterThanOrEqualTo(java.lang.Object, java.lang.Object) ,public boolean isLessThan(java.lang.Object, java.lang.Object) ,public boolean isLessThanOrEqualTo(java.lang.Object, java.lang.Object) ,public boolean isStandard() <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/TypeComparators.java
|
TypeComparators
|
defaultTypeComparators
|
class TypeComparators extends TypeHolder<Comparator<?>> {
private static final double DOUBLE_COMPARATOR_PRECISION = 1e-15;
private static final DoubleComparator DEFAULT_DOUBLE_COMPARATOR = new DoubleComparator(DOUBLE_COMPARATOR_PRECISION);
private static final float FLOAT_COMPARATOR_PRECISION = 1e-6f;
private static final FloatComparator DEFAULT_FLOAT_COMPARATOR = new FloatComparator(FLOAT_COMPARATOR_PRECISION);
private static final Comparator<Path> DEFAULT_PATH_COMPARATOR = PathNaturalOrderComparator.INSTANCE;
public static TypeComparators defaultTypeComparators() {<FILL_FUNCTION_BODY>}
/**
* This method returns the most relevant comparator for the given class. The most relevant comparator is the
* comparator which is registered for the class that is closest in the inheritance chain of the given {@code clazz}.
* The order of checks is the following:
* 1. If there is a registered comparator for {@code clazz} then this one is used
* 2. We check if there is a registered comparator for a superclass of {@code clazz}
* 3. We check if there is a registered comparator for an interface of {@code clazz}
*
* @param clazz the class for which to find a comparator
* @return the most relevant comparator, or {@code null} if no comparator could be found
*/
public Comparator<?> getComparatorForType(Class<?> clazz) {
return super.get(clazz);
}
/**
* Checks, whether an any custom comparator is associated with the giving type.
*
* @param type the type for which to check a comparator
* @return is the giving type associated with any custom comparator
*/
public boolean hasComparatorForType(Class<?> type) {
return super.hasEntity(type);
}
/**
* Puts the {@code comparator} for the given {@code clazz}.
*
* @param clazz the class for the comparator
* @param comparator the comparator itself
* @param <T> the type of the objects for the comparator
*/
public <T> void registerComparator(Class<T> clazz, Comparator<? super T> comparator) {
super.put(clazz, comparator);
}
/**
* Returns a sequence of all type-comparator pairs which the current holder supplies.
*
* @return sequence of field-comparator pairs
*/
public Stream<Entry<Class<?>, Comparator<?>>> comparatorByTypes() {
return super.entityByTypes();
}
}
|
TypeComparators comparatorByType = new TypeComparators();
comparatorByType.registerComparator(Double.class, DEFAULT_DOUBLE_COMPARATOR);
comparatorByType.registerComparator(Float.class, DEFAULT_FLOAT_COMPARATOR);
comparatorByType.registerComparator(Path.class, DEFAULT_PATH_COMPARATOR);
return comparatorByType;
| 713
| 104
| 817
|
<methods>public void <init>() ,public void <init>(Comparator<Class<?>>) ,public void clear() ,public Stream<Entry<Class<?>,Comparator<?>>> entityByTypes() ,public boolean equals(java.lang.Object) ,public Comparator<?> get(Class<?>) ,public boolean hasEntity(Class<?>) ,public int hashCode() ,public boolean isEmpty() ,public void put(Class<?>, Comparator<?>) ,public java.lang.String toString() <variables>private static final Comparator<Class<?>> DEFAULT_CLASS_COMPARATOR,protected final non-sealed Map<Class<?>,Comparator<?>> typeHolder
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Uris.java
|
Uris
|
assertHasNoParameters
|
class Uris {
private static final String UTF_8 = "UTF-8";
private static final String EQUAL = "=";
private static final String AND = "&";
private static final Uris INSTANCE = new Uris();
@VisibleForTesting
Failures failures = Failures.instance();
public static Uris instance() {
return INSTANCE;
}
Uris() {}
public void assertHasScheme(final AssertionInfo info, final URI actual, final String scheme) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getScheme(), scheme)) throw failures.failure(info, shouldHaveScheme(actual, scheme));
}
public void assertHasPath(AssertionInfo info, URI actual, String path) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getPath(), path)) throw failures.failure(info, shouldHavePath(actual, path));
}
public void assertHasPort(AssertionInfo info, URI actual, Integer expected) {
assertNotNull(info, actual);
if (actual.getPort() != expected) throw failures.failure(info, shouldHavePort(actual, expected));
}
public void assertHasHost(AssertionInfo info, URI actual, String expected) {
assertNotNull(info, actual);
requireNonNull(expected, "The expected host should not be null");
if (!Objects.equals(actual.getHost(), expected)) throw failures.failure(info, shouldHaveHost(actual, expected));
}
public void assertHasNoHost(AssertionInfo info, URI actual) {
assertNotNull(info, actual);
if (actual.getHost() != null) throw failures.failure(info, shouldHaveNoHost(actual));
}
public void assertHasAuthority(AssertionInfo info, URI actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getAuthority(), expected))
throw failures.failure(info, shouldHaveAuthority(actual, expected));
}
public void assertHasFragment(AssertionInfo info, URI actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getFragment(), expected)) throw failures.failure(info, shouldHaveFragment(actual, expected));
}
public void assertHasQuery(AssertionInfo info, URI actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getQuery(), expected)) throw failures.failure(info, shouldHaveQuery(actual, expected));
}
public void assertHasUserInfo(AssertionInfo info, URI actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getUserInfo(), expected)) throw failures.failure(info, shouldHaveUserInfo(actual, expected));
}
static Map<String, List<String>> getParameters(String query) {
Map<String, List<String>> parameters = new LinkedHashMap<>();
if (query != null && !query.isEmpty()) {
for (String pair : query.split(AND)) {
int equalIndex = pair.indexOf(EQUAL);
String key = equalIndex == -1 ? pair : pair.substring(0, equalIndex);
String value = equalIndex == -1 ? null : pair.substring(equalIndex + 1);
try {
key = URLDecoder.decode(key, UTF_8);
} catch (UnsupportedEncodingException ex) {
// UTF-8 is missing? Allow the key to remain encoded (no reasonable alternative).
}
if (value != null) {
try {
value = URLDecoder.decode(value, UTF_8);
} catch (UnsupportedEncodingException ex) {
// UTF-8 is missing? Allow the value to remain encoded (no reasonable alternative).
}
}
if (!parameters.containsKey(key)) {
parameters.put(key, new ArrayList<>());
}
parameters.get(key).add(value);
}
}
return parameters;
}
public void assertHasParameter(AssertionInfo info, URI actual, String name) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getRawQuery());
if (!parameters.containsKey(name)) throw failures.failure(info, shouldHaveParameter(actual, name));
}
public void assertHasParameter(AssertionInfo info, URI actual, String expectedParameterName,
String expectedParameterValue) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getRawQuery());
if (!parameters.containsKey(expectedParameterName))
throw failures.failure(info, shouldHaveParameter(actual, expectedParameterName, expectedParameterValue));
List<String> values = parameters.get(expectedParameterName);
if (!values.contains(expectedParameterValue))
throw failures.failure(info, shouldHaveParameter(actual, expectedParameterName, expectedParameterValue, values));
}
public void assertHasNoParameters(AssertionInfo info, URI actual) {<FILL_FUNCTION_BODY>}
public void assertHasNoParameter(AssertionInfo info, URI actual, String name) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getRawQuery());
if (parameters.containsKey(name))
throw failures.failure(info, shouldHaveNoParameter(actual, name, parameters.get(name)));
}
public void assertHasNoParameter(AssertionInfo info, URI actual, String name, String unwantedValue) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getRawQuery());
if (parameters.containsKey(name)) {
List<String> values = parameters.get(name);
if (values.contains(unwantedValue))
throw failures.failure(info, shouldHaveNoParameter(actual, name, unwantedValue, values));
}
}
}
|
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getRawQuery());
if (!parameters.isEmpty()) throw failures.failure(info, shouldHaveNoParameters(actual, parameters.keySet()));
| 1,518
| 62
| 1,580
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/internal/Urls.java
|
Urls
|
assertHasParameter
|
class Urls {
private static final Urls INSTANCE = new Urls();
@VisibleForTesting
Failures failures = Failures.instance();
public static Urls instance() {
return INSTANCE;
}
Urls() {}
private static String extractNonQueryParams(URL url) {
String queryPart = url.getQuery() == null ? "" : url.getQuery();
return url.toString().replace(queryPart, " ");
}
private static String[] extractSortedQueryParams(URL url) {
String[] queryParams = (url.getQuery() == null ? "" : url.getQuery()).split("&");
Arrays.sort(queryParams);
return queryParams;
}
public void assertHasProtocol(final AssertionInfo info, final URL actual, final String protocol) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getProtocol(), protocol)) throw failures.failure(info, shouldHaveProtocol(actual, protocol));
}
public void assertHasPath(AssertionInfo info, URL actual, String path) {
assertNotNull(info, actual);
checkArgument(path != null, "Expecting given path not to be null");
if (!Objects.equals(actual.getPath(), path)) throw failures.failure(info, shouldHavePath(actual, path));
}
public void assertHasPort(AssertionInfo info, URL actual, int expected) {
assertNotNull(info, actual);
if (actual.getPort() != expected) throw failures.failure(info, shouldHavePort(actual, expected));
}
public void assertHasHost(AssertionInfo info, URL actual, String expected) {
assertNotNull(info, actual);
requireNonNull(expected, "The expected host should not be null");
if (!Objects.equals(actual.getHost(), expected)) throw failures.failure(info, shouldHaveHost(actual, expected));
}
public void assertHasNoHost(AssertionInfo info, URL actual) {
assertNotNull(info, actual);
if (actual.getHost() != null && !actual.getHost().isEmpty()) throw failures.failure(info, shouldHaveNoHost(actual));
}
public void assertHasAuthority(AssertionInfo info, URL actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getAuthority(), expected))
throw failures.failure(info, shouldHaveAuthority(actual, expected));
}
public void assertHasQuery(AssertionInfo info, URL actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getQuery(), expected)) throw failures.failure(info, shouldHaveQuery(actual, expected));
}
public void assertHasAnchor(AssertionInfo info, URL actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getRef(), expected)) throw failures.failure(info, shouldHaveAnchor(actual, expected));
}
public void assertHasUserInfo(AssertionInfo info, URL actual, String expected) {
assertNotNull(info, actual);
if (!Objects.equals(actual.getUserInfo(), expected)) throw failures.failure(info, shouldHaveUserInfo(actual, expected));
}
public void assertHasParameter(AssertionInfo info, URL actual, String name) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getQuery());
if (!parameters.containsKey(name)) throw failures.failure(info, shouldHaveParameter(actual, name));
}
public void assertHasParameter(AssertionInfo info, URL actual, String expectedParameterName,
String expectedParameterValue) {<FILL_FUNCTION_BODY>}
public void assertHasNoParameters(AssertionInfo info, URL actual) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getQuery());
if (!parameters.isEmpty()) throw failures.failure(info, shouldHaveNoParameters(actual, parameters.keySet()));
}
public void assertHasNoParameter(AssertionInfo info, URL actual, String name) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getQuery());
if (parameters.containsKey(name))
throw failures.failure(info, shouldHaveNoParameter(actual, name, parameters.get(name)));
}
public void assertHasNoParameter(AssertionInfo info, URL actual, String name, String unwantedValue) {
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getQuery());
if (parameters.containsKey(name)) {
List<String> values = parameters.get(name);
if (values.contains(unwantedValue))
throw failures.failure(info, shouldHaveNoParameter(actual, name, unwantedValue, values));
}
}
public void assertIsEqualToWithSortedQueryParameters(AssertionInfo info, URL actual, URL expected) {
assertNotNull(info, actual);
boolean differentNonQueryParams = !extractNonQueryParams(expected).equals(extractNonQueryParams(actual));
boolean differentSortedQueryParams = !deepEquals(extractSortedQueryParams(expected), extractSortedQueryParams(actual));
if (differentNonQueryParams || differentSortedQueryParams)
throw failures.failure(info, shouldBeEqualToWithSortedQueryParameters(actual, expected));
}
}
|
assertNotNull(info, actual);
Map<String, List<String>> parameters = getParameters(actual.getQuery());
if (!parameters.containsKey(expectedParameterName))
throw failures.failure(info, shouldHaveParameter(actual, expectedParameterName, expectedParameterValue));
List<String> values = parameters.get(expectedParameterName);
if (!values.contains(expectedParameterValue))
throw failures.failure(info, shouldHaveParameter(actual, expectedParameterName, expectedParameterValue, values));
| 1,372
| 126
| 1,498
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/matcher/AssertionMatcher.java
|
AssertionMatcher
|
matches
|
class AssertionMatcher<T> extends BaseMatcher<T> {
private AssertionError firstError;
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public boolean matches(Object argument) {<FILL_FUNCTION_BODY>}
/**
* Perform the assertions implemented in this method when the {@link AssertionMatcher} is used as an Hamcrest {@link Matcher}.
*
* If the matcher fails, the description will contain the stacktrace of the first failed assertion.
* <p>
* Example with Mockito:
* <pre><code class='java'> verify(customerRepository).save(argThat(new AssertionMatcher<Customer>() {
* @Override
* public void assertion(Customer actual) throws AssertionError {
* assertThat(actual).hasName("John")
* .hasAge(30);
* }
* })
* );</code></pre>
*
* @param actual assertion object
* @throws AssertionError if the assertion object fails assertion
*/
public abstract void assertion(T actual) throws AssertionError;
/**
* {@inheritDoc}
*/
@Override
public void describeTo(Description description) {
if (firstError != null) {
description.appendText("AssertionError with message: ");
description.appendText(firstError.getMessage());
description.appendText(String.format("%n%nStacktrace was: "));
description.appendText(Throwables.getStackTrace(firstError));
}
}
}
|
T actual = (T) argument;
try {
assertion(actual);
return true;
} catch (AssertionError e) {
firstError = e;
return false;
}
| 421
| 54
| 475
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/presentation/BinaryRepresentation.java
|
BinaryRepresentation
|
toStringOf
|
class BinaryRepresentation extends StandardRepresentation {
public static final BinaryRepresentation BINARY_REPRESENTATION = new BinaryRepresentation();
public static final String BYTE_PREFIX = "0b";
/**
* Returns binary the {@code toString} representation of the given object. It may or not the object's own
* implementation of {@code toString}.
*
* @param object the given object.
* @return the {@code toString} representation of the given object.
*/
@Override
public String toStringOf(Object object) {
if (hasCustomFormatterFor(object)) return customFormat(object);
if (object instanceof Character) return toStringOf((Character) object);
if (object instanceof Number) return toStringOf((Number) object);
if (object instanceof String) return toStringOf(this, (String) object);
return super.toStringOf(object);
}
protected String toStringOf(Representation representation, String s) {
return concat("\"", representation.toStringOf(s.toCharArray()), "\"");
}
@Override
protected String toStringOf(Number number) {<FILL_FUNCTION_BODY>}
protected String toStringOf(Byte b) {
return toGroupedBinary(Integer.toBinaryString(b & 0xFF), 8);
}
protected String toStringOf(Short s) {
return toGroupedBinary(Integer.toBinaryString(s & 0xFFFF), 16);
}
protected String toStringOf(Integer i) {
return toGroupedBinary(Integer.toBinaryString(i), 32);
}
@Override
protected String toStringOf(Long l) {
return toGroupedBinary(Long.toBinaryString(l), 64);
}
@Override
protected String toStringOf(Float f) {
return toGroupedBinary(Integer.toBinaryString(Float.floatToIntBits(f)), 32);
}
protected String toStringOf(Double d) {
return toGroupedBinary(Long.toBinaryString(Double.doubleToRawLongBits(d)), 64);
}
@Override
protected String toStringOf(Character character) {
return concat("'", toStringOf((short) (int) character), "'");
}
private static String toGroupedBinary(String value, int size) {
return BYTE_PREFIX + NumberGrouping.toBinaryLiteral(toBinary(value, size));
}
private static String toBinary(String value, int size) {
return String.format("%" + size + "s", value).replace(' ', '0');
}
}
|
if (number instanceof Byte) return toStringOf((Byte) number);
if (number instanceof Short) return toStringOf((Short) number);
if (number instanceof Integer) return toStringOf((Integer) number);
if (number instanceof Long) return toStringOf((Long) number);
if (number instanceof Float) return toStringOf((Float) number);
if (number instanceof Double) return toStringOf((Double) number);
return number == null ? null : number.toString();
| 684
| 119
| 803
|
<methods>public non-sealed void <init>() ,public static int getMaxElementsForPrinting() ,public static int getMaxLengthForSingleLineDescription() ,public static int getMaxStackTraceElementsDisplayed() ,public static void registerFormatterForType(Class<T>, Function<T,java.lang.String>) ,public static void removeAllRegisteredFormatters() ,public static void resetDefaults() ,public static void setMaxElementsForPrinting(int) ,public static void setMaxLengthForSingleLineDescription(int) ,public static void setMaxStackTraceElementsDisplayed(int) ,public java.lang.String toString() ,public java.lang.String toStringOf(java.lang.Object) ,public java.lang.String unambiguousToStringOf(java.lang.Object) <variables>private static final Class<?>[] BLACKLISTED_ITERABLE_CLASSES,private static final java.lang.String DEFAULT_END,private static final java.lang.String DEFAULT_MAX_ELEMENTS_EXCEEDED,private static final java.lang.String DEFAULT_START,public static final java.lang.String ELEMENT_SEPARATOR,public static final java.lang.String ELEMENT_SEPARATOR_WITH_NEWLINE,static final java.lang.String INDENTATION_AFTER_NEWLINE,static final java.lang.String INDENTATION_FOR_SINGLE_LINE,private static final java.lang.String NULL,public static final org.assertj.core.presentation.StandardRepresentation STANDARD_REPRESENTATION,private static final java.lang.String TUPLE_END,private static final java.lang.String TUPLE_START,private static final Class<?>[] TYPE_WITH_UNAMBIGUOUS_REPRESENTATION,private static final Map<Class<?>,Function<?,? extends java.lang.CharSequence>> customFormatterByType,private static int maxElementsForPrinting,private static int maxLengthForSingleLineDescription,private static int maxStackTraceElementsDisplayed
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/presentation/CompositeRepresentation.java
|
CompositeRepresentation
|
toStringOf
|
class CompositeRepresentation implements Representation {
private final List<Representation> representations;
public CompositeRepresentation(List<Representation> representations) {
if (representations == null) throw new IllegalArgumentException("The given representations should not be null");
this.representations = representations.stream()
.sorted(comparingInt(Representation::getPriority).reversed())
.collect(toList());
}
@Override
public String toStringOf(Object object) {<FILL_FUNCTION_BODY>}
@Override
public String unambiguousToStringOf(Object object) {
// don't create streams for performance reasons and because this code is simple enough (even not as elegant as with stream)
for (Representation representation : representations) {
String value = representation.unambiguousToStringOf(object);
if (value != null) return value;
}
return STANDARD_REPRESENTATION.unambiguousToStringOf(object);
}
@Override
public String toString() {
return representations.isEmpty() ? STANDARD_REPRESENTATION.toString() : representations.toString();
}
public List<Representation> getAllRepresentationsOrderedByPriority() {
List<Representation> representationsOrderedByPriority = new ArrayList<>(representations);
representationsOrderedByPriority.add(STANDARD_REPRESENTATION);
return representationsOrderedByPriority;
}
}
|
// don't create streams for performance reasons and because this code is simple enough (even not as elegant as with stream)
for (Representation representation : representations) {
String value = representation.toStringOf(object);
if (value != null) return value;
}
return STANDARD_REPRESENTATION.toStringOf(object);
| 369
| 87
| 456
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/presentation/HexadecimalRepresentation.java
|
HexadecimalRepresentation
|
toStringOf
|
class HexadecimalRepresentation extends StandardRepresentation {
public static final HexadecimalRepresentation HEXA_REPRESENTATION = new HexadecimalRepresentation();
public static final String PREFIX = "0x";
public static final int NIBBLE_SIZE = 4;
/**
* Returns hexadecimal the {@code toString} representation of the given object. It may or not the object's own
* implementation of {@code toString}.
*
* @param object the given object.
* @return the {@code toString} representation of the given object.
*/
@Override
public String toStringOf(Object object) {<FILL_FUNCTION_BODY>}
@Override
protected String toStringOf(Number number) {
if (number instanceof Byte) return toStringOf((Byte) number);
else if (number instanceof Short) return toStringOf((Short) number);
else if (number instanceof Integer) return toStringOf((Integer) number);
else if (number instanceof Long) return toStringOf((Long) number);
else if (number instanceof Float) return toStringOf((Float) number);
else if (number instanceof Double) return toStringOf((Double) number);
else return number.toString();
}
protected String toStringOf(Byte b) {
return toGroupedHex(b, 8);
}
protected String toStringOf(Short s) {
return toGroupedHex(s, 16);
}
protected String toStringOf(Integer i) {
return toGroupedHex(i, 32);
}
@Override
protected String toStringOf(Long l) {
return toGroupedHex(l, 64);
}
@Override
protected String toStringOf(Float f) {
return toGroupedHex(Float.floatToIntBits(f), 32);
}
protected String toStringOf(Double d) {
return toGroupedHex(Double.doubleToRawLongBits(d), 64);
}
@Override
protected String toStringOf(Character character) {
return concat("'", toStringOf((short) (int) character), "'");
}
protected String toStringOf(Representation representation, String s) {
return concat("\"", representation.toStringOf(s.toCharArray()), "\"");
}
private static String toGroupedHex(Number value, int size) {
return PREFIX + NumberGrouping.toHexLiteral(toHex(value, size));
}
private static String toHex(Number value, int sizeInBits) {
return String.format("%0" + sizeInBits / NIBBLE_SIZE + "X", value);
}
}
|
if (hasCustomFormatterFor(object)) return customFormat(object);
if (object instanceof Number) return toStringOf((Number) object);
else if (object instanceof String) return toStringOf(this, (String) object);
else if (object instanceof Character) return toStringOf((Character) object);
return super.toStringOf(object);
| 713
| 87
| 800
|
<methods>public non-sealed void <init>() ,public static int getMaxElementsForPrinting() ,public static int getMaxLengthForSingleLineDescription() ,public static int getMaxStackTraceElementsDisplayed() ,public static void registerFormatterForType(Class<T>, Function<T,java.lang.String>) ,public static void removeAllRegisteredFormatters() ,public static void resetDefaults() ,public static void setMaxElementsForPrinting(int) ,public static void setMaxLengthForSingleLineDescription(int) ,public static void setMaxStackTraceElementsDisplayed(int) ,public java.lang.String toString() ,public java.lang.String toStringOf(java.lang.Object) ,public java.lang.String unambiguousToStringOf(java.lang.Object) <variables>private static final Class<?>[] BLACKLISTED_ITERABLE_CLASSES,private static final java.lang.String DEFAULT_END,private static final java.lang.String DEFAULT_MAX_ELEMENTS_EXCEEDED,private static final java.lang.String DEFAULT_START,public static final java.lang.String ELEMENT_SEPARATOR,public static final java.lang.String ELEMENT_SEPARATOR_WITH_NEWLINE,static final java.lang.String INDENTATION_AFTER_NEWLINE,static final java.lang.String INDENTATION_FOR_SINGLE_LINE,private static final java.lang.String NULL,public static final org.assertj.core.presentation.StandardRepresentation STANDARD_REPRESENTATION,private static final java.lang.String TUPLE_END,private static final java.lang.String TUPLE_START,private static final Class<?>[] TYPE_WITH_UNAMBIGUOUS_REPRESENTATION,private static final Map<Class<?>,Function<?,? extends java.lang.CharSequence>> customFormatterByType,private static int maxElementsForPrinting,private static int maxLengthForSingleLineDescription,private static int maxStackTraceElementsDisplayed
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/presentation/NumberGrouping.java
|
NumberGrouping
|
toHexLiteral
|
class NumberGrouping {
private static final String UNDERSCORE_SEPARATOR = "_";
private static Pattern hexGroupPattern = Pattern.compile("([0-9|A-Z]{4})");
private static Pattern binaryGroupPattern = Pattern.compile("([0-1]{8})");
static String toHexLiteral(String value) {
return value.length() > 4 ? toHexLiteral(hexGroupPattern, value) : value;
}
static String toBinaryLiteral(String value) {
return toHexLiteral(binaryGroupPattern, value);
}
private static String toHexLiteral(Pattern pattern, String value) {<FILL_FUNCTION_BODY>}
private static boolean notEmpty(StringBuilder sb) {
return sb.length() != 0;
}
private NumberGrouping() {}
}
|
Matcher matcher = pattern.matcher(value);
StringBuilder literalBuilder = new StringBuilder();
while (matcher.find()) {
String byteGroup = matcher.group(1);
if (notEmpty(literalBuilder)) {
literalBuilder.append(UNDERSCORE_SEPARATOR);
}
literalBuilder.append(byteGroup);
}
return literalBuilder.toString();
| 216
| 105
| 321
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/presentation/PredicateDescription.java
|
PredicateDescription
|
equals
|
class PredicateDescription {
private static final String DEFAULT = "given";
public static final PredicateDescription GIVEN = new PredicateDescription(DEFAULT);
// can be public as it is immutable, never null
public final String description;
/**
* Build a {@link PredicateDescription}.
*
* @param description must not be null
*/
public PredicateDescription(String description) {
requireNonNull(description, "The predicate description must not be null");
this.description = description;
}
public boolean isDefault() {
return DEFAULT.equals(description);
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return HASH_CODE_PRIME * hashCodeFor(description);
}
}
|
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
PredicateDescription description = (PredicateDescription) obj;
return deepEquals(this.description, description.description);
| 211
| 76
| 287
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/presentation/RotatingQueue.java
|
RotatingQueue
|
offer
|
class RotatingQueue<T> extends AbstractQueue<T> {
/** The array to provide a view of. */
private final Queue<T> data;
/** The maximum number of elements that can be present. */
private final int capacity;
/**
* Creates a new {@link RotatingQueue}.
*
* @param capacity the maximum number of elements the queue can hold
* @throws IllegalArgumentException if the capacity is negative
*/
RotatingQueue(int capacity) {
checkArgument(capacity >= 0, "capacity must be non-negative but was %d", capacity);
this.capacity = capacity;
this.data = new LinkedList<>();
}
@Override
public Iterator<T> iterator() {
return data.iterator();
}
@Override
public int size() {
return data.size();
}
@Override
public boolean offer(T element) {<FILL_FUNCTION_BODY>}
@Override
public T poll() {
return data.poll();
}
@Override
public T peek() {
return data.peek();
}
}
|
if (capacity == 0) return false;
if (data.size() == capacity) data.remove();
return data.add(element);
| 293
| 39
| 332
|
<methods>public boolean add(T) ,public boolean addAll(Collection<? extends T>) ,public void clear() ,public T element() ,public T remove() <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/presentation/UnicodeRepresentation.java
|
UnicodeRepresentation
|
escapeUnicode
|
class UnicodeRepresentation extends StandardRepresentation {
public static final UnicodeRepresentation UNICODE_REPRESENTATION = new UnicodeRepresentation();
/**
* Returns hexadecimal the {@code toString} representation of the given String or Character.
*
* @param object the given object.
* @return the {@code toString} representation of the given object.
*/
@Override
public String toStringOf(Object object) {
if (hasCustomFormatterFor(object)) return customFormat(object);
if (object instanceof String) return toStringOf((String) object);
if (object instanceof Character) return toStringOf((Character) object);
return super.toStringOf(object);
}
@Override
protected String toStringOf(Character string) {
return escapeUnicode(string.toString());
}
@Override
protected String toStringOf(String string) {
return escapeUnicode(string);
}
private static String escapeUnicode(String input) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder b = new StringBuilder(input.length());
Formatter formatter = new Formatter(b);
for (char c : input.toCharArray()) {
if (c < 128) {
b.append(c);
} else {
formatter.format("\\u%04x", (int) c);
}
}
formatter.close();
return b.toString();
| 270
| 107
| 377
|
<methods>public non-sealed void <init>() ,public static int getMaxElementsForPrinting() ,public static int getMaxLengthForSingleLineDescription() ,public static int getMaxStackTraceElementsDisplayed() ,public static void registerFormatterForType(Class<T>, Function<T,java.lang.String>) ,public static void removeAllRegisteredFormatters() ,public static void resetDefaults() ,public static void setMaxElementsForPrinting(int) ,public static void setMaxLengthForSingleLineDescription(int) ,public static void setMaxStackTraceElementsDisplayed(int) ,public java.lang.String toString() ,public java.lang.String toStringOf(java.lang.Object) ,public java.lang.String unambiguousToStringOf(java.lang.Object) <variables>private static final Class<?>[] BLACKLISTED_ITERABLE_CLASSES,private static final java.lang.String DEFAULT_END,private static final java.lang.String DEFAULT_MAX_ELEMENTS_EXCEEDED,private static final java.lang.String DEFAULT_START,public static final java.lang.String ELEMENT_SEPARATOR,public static final java.lang.String ELEMENT_SEPARATOR_WITH_NEWLINE,static final java.lang.String INDENTATION_AFTER_NEWLINE,static final java.lang.String INDENTATION_FOR_SINGLE_LINE,private static final java.lang.String NULL,public static final org.assertj.core.presentation.StandardRepresentation STANDARD_REPRESENTATION,private static final java.lang.String TUPLE_END,private static final java.lang.String TUPLE_START,private static final Class<?>[] TYPE_WITH_UNAMBIGUOUS_REPRESENTATION,private static final Map<Class<?>,Function<?,? extends java.lang.CharSequence>> customFormatterByType,private static int maxElementsForPrinting,private static int maxLengthForSingleLineDescription,private static int maxStackTraceElementsDisplayed
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/ArrayWrapperList.java
|
ArrayWrapperList
|
wrap
|
class ArrayWrapperList extends AbstractList<Object> {
/**
* Wraps a given array with a <code>{@link ArrayWrapperList}</code>
*
* @param array the array to wrap.
* @return the wrapped array or {@code null} if the given array was already {@code null}.
* @throws IllegalArgumentException if the {@code array} is not an array.
*/
public static ArrayWrapperList wrap(Object array) {<FILL_FUNCTION_BODY>}
@VisibleForTesting
final Object array;
@VisibleForTesting
ArrayWrapperList(Object array) {
this.array = array;
}
/**
* {@inheritDoc}
*/
@Override
public Object get(int index) {
checkIsInRange(index);
return Array.get(array, index);
}
private void checkIsInRange(int index) {
int size = size();
if (index >= 0 && index < size()) {
return;
}
String message = String.format("Index should be between 0 and %d (inclusive) but was %d", size - 1, index);
throw new IndexOutOfBoundsException(message);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return Array.getLength(array);
}
/**
* Returns the component type of the wrapped array.
*
* @return the component type of the wrapped array.
*/
public Class<?> getComponentType() {
return array.getClass().getComponentType();
}
}
|
if (array == null) {
return null;
}
checkArgument(array.getClass().isArray(), "The object to wrap should be an array");
return new ArrayWrapperList(array);
| 410
| 53
| 463
|
<methods>public boolean add(java.lang.Object) ,public void add(int, java.lang.Object) ,public boolean addAll(int, Collection<? extends java.lang.Object>) ,public void clear() ,public boolean equals(java.lang.Object) ,public abstract java.lang.Object get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public Iterator<java.lang.Object> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<java.lang.Object> listIterator() ,public ListIterator<java.lang.Object> listIterator(int) ,public java.lang.Object remove(int) ,public java.lang.Object set(int, java.lang.Object) ,public List<java.lang.Object> subList(int, int) <variables>protected transient int modCount
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Arrays.java
|
Arrays
|
sizeOf
|
class Arrays {
/**
* Indicates whether the given object is not {@code null} and is an array.
*
* @param o the given object.
* @return {@code true} if the given object is not {@code null} and is an array, otherwise {@code false}.
*/
public static boolean isArray(Object o) {
return o != null && o.getClass().isArray();
}
/**
* Get the values of any array (primitive or not) into a {@code Object[]}.
*
* @param array array passed as an object to support both primitive and Object array
* @return the values of the given Object as a {@code Object[]}.
* @throws IllegalArgumentException it the given Object is not an array.
*/
public static Object[] asObjectArray(Object array) {
checkArgument(isArray(array), "Given object %s is not an array", array);
int length = Array.getLength(array);
Object[] objectArray = new Object[length];
for (int i = 0; i < length; i++) {
objectArray[i] = Array.get(array, i);
}
return objectArray;
}
/**
* Get the values of any array (primitive or not) into a {@code List<Object>}.
*
* @param array array passed as an object to support both primitive and Object array
* @return the values of the given Object as a {@code List<Object>}.
* @throws IllegalArgumentException it the given Object is not an array.
*/
public static List<Object> asList(Object array) {
return newArrayList(asObjectArray(array));
}
/**
* Indicates whether the given array is {@code null} or empty.
*
* @param <T> the type of elements of the array.
* @param array the array to check.
* @return {@code true} if the given array is {@code null} or empty, otherwise {@code false}.
*/
public static <T> boolean isNullOrEmpty(T[] array) {
return array == null || isEmpty(array);
}
/**
* Returns an array containing the given arguments.
*
* @param <T> the type of the array to return.
* @param values the values to store in the array.
* @return an array containing the given arguments.
*/
@SafeVarargs
public static <T> T[] array(T... values) {
return values;
}
/**
* Returns an int[] from the {@link AtomicIntegerArray}, null if the given atomic array is null.
*
* @param atomicIntegerArray the {@link AtomicIntegerArray} to convert to int[].
* @return an int[].
*/
public static int[] array(AtomicIntegerArray atomicIntegerArray) {
if (atomicIntegerArray == null) return null;
int[] array = new int[atomicIntegerArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = atomicIntegerArray.get(i);
}
return array;
}
/**
* Returns an long[] from the {@link AtomicLongArray}, null if the given atomic array is null.
*
* @param atomicLongArray the {@link AtomicLongArray} to convert to long[].
* @return an long[].
*/
public static long[] array(AtomicLongArray atomicLongArray) {
if (atomicLongArray == null) return null;
long[] array = new long[atomicLongArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = atomicLongArray.get(i);
}
return array;
}
/**
* Returns an T[] from the {@link AtomicReferenceArray}, null if the given atomic array is null.
*
* @param <T> the type of elements of the array.
* @param atomicReferenceArray the {@link AtomicReferenceArray} to convert to T[].
* @return an T[].
*/
@SuppressWarnings("unchecked")
public static <T> T[] array(AtomicReferenceArray<T> atomicReferenceArray) {
if (atomicReferenceArray == null) return null;
int length = atomicReferenceArray.length();
if (length == 0) return array();
List<T> list = newArrayList();
for (int i = 0; i < length; i++) {
list.add(atomicReferenceArray.get(i));
}
return list.toArray((T[]) Array.newInstance(Object.class, length));
}
/**
* Returns all the non-{@code null} elements in the given array.
*
* @param <T> the type of elements of the array.
* @param array the given array.
* @return all the non-{@code null} elements in the given array. An empty list is returned if the given array is
* {@code null}.
*/
public static <T> List<T> nonNullElementsIn(T[] array) {
if (array == null) return emptyList();
return stream(array).filter(Objects::nonNull).collect(toList());
}
/**
* Returns {@code true} if the given array has only {@code null} elements, {@code false} otherwise. If given array is
* empty, this method returns {@code true}.
*
* @param <T> the type of elements of the array.
* @param array the given array. <b>It must not be null</b>.
* @return {@code true} if the given array has only {@code null} elements or is empty, {@code false} otherwise.
* @throws NullPointerException if the given array is {@code null}.
*/
public static <T> boolean hasOnlyNullElements(T[] array) {
requireNonNull(array);
if (isEmpty(array)) return false;
for (T o : array) {
if (o != null) return false;
}
return true;
}
private static <T> boolean isEmpty(T[] array) {
return array.length == 0;
}
public static boolean isObjectArray(Object o) {
return isArray(o) && !isArrayTypePrimitive(o);
}
public static boolean isArrayTypePrimitive(Object o) {
return isArray(o) && o.getClass().getComponentType().isPrimitive();
}
public static IllegalArgumentException notAnArrayOfPrimitives(Object o) {
return new IllegalArgumentException(format("<%s> is not an array of primitives", o));
}
@SuppressWarnings("unchecked")
public static <T> T[] prepend(T first, T... rest) {
T[] result = (T[]) new Object[1 + rest.length];
result[0] = first;
System.arraycopy(rest, 0, result, 1, rest.length);
return result;
}
public static int sizeOf(Object array) {<FILL_FUNCTION_BODY>}
public static boolean isArrayEmpty(Object array) {
return sizeOf(array) == 0;
}
private Arrays() {}
}
|
if (!isArray(array)) throw new IllegalArgumentException(format("expecting %s to be an array", array));
if (array instanceof Object[]) return ((Object[]) array).length;
return getLength(array);
| 1,814
| 56
| 1,870
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Closeables.java
|
Closeables
|
closeCloseable
|
class Closeables {
private static final Logger logger = Logger.getLogger(Closeables.class.getCanonicalName());
/**
* Closes the given {@link Closeable}s, ignoring any thrown exceptions.
*
* @param closeables the {@code Closeable}s to close.
*/
public static void closeQuietly(Closeable... closeables) {
for (Closeable c : closeables) {
closeCloseable(c);
}
}
private static void closeCloseable(Closeable c) {<FILL_FUNCTION_BODY>}
private Closeables() {}
}
|
if (c == null) {
return;
}
try {
c.close();
} catch (Throwable t) {
logger.log(Level.WARNING, "Error occurred while closing " + c, t);
}
| 158
| 63
| 221
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/DoubleComparator.java
|
DoubleComparator
|
equals
|
class DoubleComparator extends NullSafeComparator<Double> {
private double precision;
public DoubleComparator(double epsilon) {
this.precision = epsilon;
}
@Override
protected int compareNonNull(Double x, Double y) {
if (closeEnough(x, y, precision)) return 0;
return x < y ? -1 : 1;
}
public double getEpsilon() {
return precision;
}
private static boolean closeEnough(Double x, Double y, double epsilon) {
return x.doubleValue() == y.doubleValue() || Math.abs(x - y) <= epsilon;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp = Double.doubleToLongBits(precision);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return format("DoubleComparator[precision=%s]", precision);
}
}
|
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof DoubleComparator)) return false;
DoubleComparator other = (DoubleComparator) obj;
return Double.doubleToLongBits(precision) == Double.doubleToLongBits(other.precision);
| 313
| 84
| 397
|
<methods>public int compare(java.lang.Double, java.lang.Double) <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/FloatComparator.java
|
FloatComparator
|
closeEnough
|
class FloatComparator extends NullSafeComparator<Float> {
private float precision;
public FloatComparator(float epsilon) {
this.precision = epsilon;
}
public float getEpsilon() {
return precision;
}
@Override
public int compareNonNull(Float x, Float y) {
if (closeEnough(x, y, precision)) return 0;
return x < y ? -1 : 1;
}
private boolean closeEnough(Float x, Float y, float epsilon) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return 31 + Float.floatToIntBits(precision);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof FloatComparator)) return false;
FloatComparator other = (FloatComparator) obj;
return Float.floatToIntBits(precision) == Float.floatToIntBits(other.precision);
}
@Override
public String toString() {
return format("FloatComparator[precision=%s]", precision);
}
}
|
return x.floatValue() == y.floatValue() || Math.abs(x - y) <= epsilon;
| 333
| 30
| 363
|
<methods>public int compare(java.lang.Float, java.lang.Float) <variables>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Hexadecimals.java
|
Hexadecimals
|
byteToHexString
|
class Hexadecimals {
protected static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String byteToHexString(byte b) {<FILL_FUNCTION_BODY>}
public static String toHexString(byte... bytes) {
StringBuilder stringBuilder = new StringBuilder();
for (byte b : bytes)
stringBuilder.append(byteToHexString(b));
return stringBuilder.toString();
}
private Hexadecimals() {}
}
|
int v = b & 0xFF;
return new String(new char[] { HEX_ARRAY[v >>> 4], HEX_ARRAY[v & 0x0F] });
| 147
| 52
| 199
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/IterableUtil.java
|
IterableUtil
|
isNullOrEmpty
|
class IterableUtil {
/**
* Indicates whether the given {@link Iterable} is {@code null} or empty.
*
* @param iterable the given {@code Iterable} to check.
* @return {@code true} if the given {@code Iterable} is {@code null} or empty, otherwise {@code false}.
*/
public static boolean isNullOrEmpty(Iterable<?> iterable) {<FILL_FUNCTION_BODY>}
/**
* Returns the size of the given {@link Iterable}.
*
* @param iterable the {@link Iterable} to get size.
* @return the size of the given {@link Iterable}.
* @throws NullPointerException if given {@link Iterable} is null.
*/
public static int sizeOf(Iterable<?> iterable) {
requireNonNull(iterable, "Iterable must not be null");
if (iterable instanceof Collection) return ((Collection<?>) iterable).size();
return Math.toIntExact(Streams.stream(iterable).count());
}
/**
* Returns all the non-{@code null} elements in the given {@link Iterable}.
*
* @param <T> the type of elements of the {@code Iterable}.
* @param i the given {@code Iterable}.
* @return all the non-{@code null} elements in the given {@code Iterable}. An empty list is returned if the given
* {@code Iterable} is {@code null}.
*/
public static <T> List<T> nonNullElementsIn(Iterable<? extends T> i) {
if (isNullOrEmpty(i)) return emptyList();
return Streams.stream(i).filter(Objects::nonNull).collect(toList());
}
/**
* Create an array from an {@link Iterable}.
* <p>
* Note: this method will return Object[]. If you require a typed array please use {@link #toArray(Iterable, Class)}.
* It's main usage is to keep the generic type for chaining call like in:
* <pre><code class='java'> public S containsOnlyElementsOf(Iterable<? extends T> iterable) {
* return containsOnly(toArray(iterable));
* }</code></pre>
*
* @param iterable an {@link Iterable} to translate in an array.
* @param <T> the type of elements of the {@code Iterable}.
* @return all the elements from the given {@link Iterable} in an array. {@code null} if given {@link Iterable} is
* null.
*/
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Iterable<? extends T> iterable) {
if (iterable == null) return null;
return (T[]) newArrayList(iterable).toArray();
}
/**
* Create an typed array from an {@link Iterable}.
*
* @param iterable an {@link Iterable} to translate in an array.
* @param type the type of the resulting array.
* @param <T> the type of elements of the {@code Iterable}.
* @return all the elements from the given {@link Iterable} in an array. {@code null} if given {@link Iterable} is
* null.
*/
public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
if (iterable == null) return null;
Collection<? extends T> collection = toCollection(iterable);
T[] array = newArray(type, collection.size());
return collection.toArray(array);
}
public static <T> Collection<T> toCollection(Iterable<T> iterable) {
return iterable instanceof Collection ? (Collection<T>) iterable : newArrayList(iterable);
}
@SafeVarargs
public static <T> Iterable<T> iterable(T... elements) {
if (elements == null) return null;
ArrayList<T> list = newArrayList();
java.util.Collections.addAll(list, elements);
return list;
}
@SafeVarargs
public static <T> Iterator<T> iterator(T... elements) {
if (elements == null) return null;
return iterable(elements).iterator();
}
@SuppressWarnings("unchecked")
private static <T> T[] newArray(Class<T> type, int length) {
return (T[]) Array.newInstance(type, length);
}
private IterableUtil() {}
}
|
if (iterable == null) return true;
if (iterable instanceof Collection && ((Collection<?>) iterable).isEmpty()) return true;
return !iterable.iterator().hasNext();
| 1,167
| 50
| 1,217
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Lists.java
|
Lists
|
newArrayList
|
class Lists {
@SafeVarargs
public static <T> List<T> list(T... elements) {
return newArrayList(elements);
}
/**
* Creates a <em>mutable</em> {@link ArrayList} containing the given elements.
*
* @param <T> the generic type of the {@code ArrayList} to create.
* @param elements the elements to store in the {@code ArrayList}.
* @return the created {@code ArrayList}, of {@code null} if the given array of elements is {@code null}.
*/
@SafeVarargs
public static <T> ArrayList<T> newArrayList(T... elements) {
if (elements == null) {
return null;
}
ArrayList<T> list = newArrayList();
Collections.addAll(list, elements);
return list;
}
/**
* Creates a <em>mutable</em> {@link ArrayList} containing the given elements.
*
* @param <T> the generic type of the {@code ArrayList} to create.
* @param elements the elements to store in the {@code ArrayList}.
* @return the created {@code ArrayList}, or {@code null} if the given {@code Iterable} is {@code null}.
*/
public static <T> ArrayList<T> newArrayList(Iterable<? extends T> elements) {<FILL_FUNCTION_BODY>}
/**
* Creates a <em>mutable</em> {@link ArrayList} containing the given elements.
*
* @param <T> the generic type of the {@code ArrayList} to create.
* @param elements the elements to store in the {@code ArrayList}.
* @return the created {@code ArrayList}, or {@code null} if the given {@code Iterator} is {@code null}.
*/
public static <T> ArrayList<T> newArrayList(Iterator<? extends T> elements) {
if (elements == null) {
return null;
}
return Streams.stream(elements).collect(toCollection(ArrayList::new));
}
/**
* Creates a <em>mutable</em> {@link ArrayList}.
*
* @param <T> the generic type of the {@code ArrayList} to create.
* @return the created {@code ArrayList}, of {@code null} if the given array of elements is {@code null}.
*/
public static <T> ArrayList<T> newArrayList() {
return new ArrayList<>();
}
/**
* @deprecated use {@link Collections#emptyList()} instead.
*
* @param <T> the generic type of the {@code List}.
* @return an empty, <em>immutable</em> {@code List}.
*/
@Deprecated
public static <T> List<T> emptyList() {
return Collections.emptyList();
}
private Lists() {}
}
|
if (elements == null) {
return null;
}
return Streams.stream(elements).collect(toCollection(ArrayList::new));
| 711
| 39
| 750
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Maps.java
|
Maps
|
newHashMap
|
class Maps {
/**
* Returns the {@code String} {@link org.assertj.core.presentation.StandardRepresentation standard representation} of
* the given map, or {@code null} if the given map is {@code null}.
*
* @param map the map to format.
* @return the {@code String} representation of the given map.
*
* @deprecated use {@link StandardRepresentation#toStringOf(Map)} instead.
*/
@Deprecated
public static String format(Map<?, ?> map) {
return CONFIGURATION_PROVIDER.representation().toStringOf(map);
}
/**
* Returns the {@code String} representation of the given map, or {@code null} if the given map is {@code null}.
*
* @param p the {@link Representation} to use.
* @param map the map to format.
* @return the {@code String} representation of the given map.
*
* @deprecated use {@link StandardRepresentation#toStringOf(Map)} instead.
*/
@Deprecated
public static String format(Representation p, Map<?, ?> map) {
return CONFIGURATION_PROVIDER.representation().toStringOf(map);
}
public static <K, V> Map<K, V> newHashMap(K key, V value) {<FILL_FUNCTION_BODY>}
private Maps() {}
}
|
Map<K, V> map = new HashMap<>();
map.put(key, value);
return map;
| 362
| 33
| 395
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/NullSafeComparator.java
|
NullSafeComparator
|
compare
|
class NullSafeComparator<T> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {<FILL_FUNCTION_BODY>}
protected abstract int compareNonNull(T o1, T o2);
}
|
if (o1 == o2) return 0;
if (o1 == null) return -1;
if (o2 == null) return 1;
return compareNonNull(o1, o2);
| 70
| 57
| 127
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Objects.java
|
Objects
|
namesOf
|
class Objects {
/** Prime number used to calculate the hash code of objects. */
public static final int HASH_CODE_PRIME = 31;
/**
* Returns {@code true} if the arguments are deeply equal to each other, {@code false} otherwise.
* <p>
* Two {@code null} values are deeply equal. If both arguments are arrays, the algorithm in
* {@link java.util.Arrays#deepEquals} is used to determine equality.
* Otherwise, equality is determined by using the {@link Object#equals} method of the first argument.
*
* @param o1 an object.
* @param o2 an object to be compared with {@code o1} for deep equality.
* @return {@code true} if the arguments are deeply equal to each other, {@code false} otherwise.
*
* @deprecated Use {@link java.util.Objects#deepEquals(Object, Object)} instead.
*/
@Deprecated
public static boolean areEqual(Object o1, Object o2) {
return java.util.Objects.deepEquals(o1, o2);
}
/**
* Returns {@code true} if the arguments are arrays and deeply equal to each other, {@code false} otherwise.
* <p>
* Once verified that the arguments are arrays, the algorithm in {@link java.util.Arrays#deepEquals} is used
* to determine equality.
*
* @param o1 an object.
* @param o2 an object to be compared with {@code o1} for deep equality.
* @return {@code true} if the arguments are arrays and deeply equal to each other, {@code false} otherwise.
*
* @deprecated Use either {@link java.util.Objects#deepEquals(Object, Object)} or
* {@link java.util.Arrays#deepEquals(Object[], Object[])}.
*/
@Deprecated
public static boolean areEqualArrays(Object o1, Object o2) {
if (!isArray(o1) || !isArray(o2)) {
return false;
}
return java.util.Objects.deepEquals(o1, o2);
}
/**
* Returns an array containing the names of the given types.
*
* @param types the given types.
* @return the names of the given types stored in an array.
*/
public static String[] namesOf(Class<?>... types) {<FILL_FUNCTION_BODY>}
/**
* Returns the hash code for the given object. If the object is {@code null}, this method returns zero. Otherwise
* calls the method {@code hashCode} of the given object.
*
* @param o the given object.
* @return the hash code for the given object
*/
public static int hashCodeFor(Object o) {
if (o == null) return 0;
return isArray(o) && !o.getClass().getComponentType().isPrimitive()
? java.util.Arrays.deepHashCode((Object[]) o)
: o.hashCode();
}
/**
* Casts the given object to the given type only if the object is of the given type. If the object is not of the given
* type, this method returns {@code null}.
*
* @param <T> the generic type to cast the given object to.
* @param o the object to cast.
* @param type the given type.
* @return the casted object, or {@code null} if the given object is not to the given type.
*/
public static <T> T castIfBelongsToType(Object o, Class<T> type) {
if (o != null && type.isAssignableFrom(o.getClass())) {
return type.cast(o);
}
return null;
}
private Objects() {}
}
|
if (isNullOrEmpty(types)) {
return new String[0];
}
String[] names = new String[types.length];
for (int i = 0; i < types.length; i++) {
names[i] = types[i].getName();
}
return names;
| 953
| 79
| 1,032
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Preconditions.java
|
Preconditions
|
checkNotNullOrEmpty
|
class Preconditions {
public static final String ARGUMENT_EMPTY = "Argument expected not to be empty!";
/**
* Verifies that the given {@code CharSequence} is not {@code null} or empty.
*
* @param s the given {@code CharSequence}.
* @return the validated {@code CharSequence}.
* @throws NullPointerException if the given {@code CharSequence} is {@code null}.
* @throws IllegalArgumentException if the given {@code CharSequence} is empty.
*/
public static CharSequence checkNotNullOrEmpty(CharSequence s) {
return checkNotNullOrEmpty(s, ARGUMENT_EMPTY);
}
/**
* Verifies that the given {@code CharSequence} is not {@code null} or empty.
*
* @param s the given {@code CharSequence}.
* @param message error message in case of empty {@code String}.
* @return the validated {@code CharSequence}.
* @throws NullPointerException if the given {@code CharSequence} is {@code null}.
* @throws IllegalArgumentException if the given {@code CharSequence} is empty.
*/
public static CharSequence checkNotNullOrEmpty(CharSequence s, String message) {<FILL_FUNCTION_BODY>}
/**
* Verifies that the given array is not {@code null} or empty.
*
* @param <T> the type of elements of the array.
* @param array the given array.
* @return the validated array.
* @throws NullPointerException if the given array is {@code null}.
* @throws IllegalArgumentException if the given array is empty.
*/
public static <T> T[] checkNotNullOrEmpty(T[] array) {
T[] checked = requireNonNull(array);
if (checked.length == 0) throwExceptionForBeingEmpty();
return checked;
}
/**
* Verifies that the given object reference is not {@code null}.
*
* @param <T> the type of the reference to check.
* @param reference the given object reference.
* @return the non-{@code null} reference that was validated.
* @throws NullPointerException if the given object reference is {@code null}.
*
* @deprecated use {@link java.util.Objects#requireNonNull(Object)} instead.
*/
@Deprecated
public static <T> T checkNotNull(T reference) {
if (reference == null) throw new NullPointerException();
return reference;
}
/**
* Verifies that the given object reference is not {@code null}.
*
* @param <T> the type of the reference to check.
* @param reference the given object reference.
* @param message error message in case of null reference.
* @return the non-{@code null} reference that was validated.
* @throws NullPointerException if the given object reference is {@code null}.
*
* @deprecated use {@link java.util.Objects#requireNonNull(Object, String)} instead.
*/
@Deprecated
public static <T> T checkNotNull(T reference, String message) {
if (reference == null) throw new NullPointerException(message);
return reference;
}
/**
* Verifies that the given {@link FilterOperator} reference is not {@code null}.
*
* @param <T> the type of the FilterOperator to check.
* @param filterOperator the given {@link FilterOperator} reference.
* @throws IllegalArgumentException if the given {@link FilterOperator} reference is {@code null}.
*/
public static <T> void checkNotNull(FilterOperator<T> filterOperator) {
checkArgument(filterOperator != null, "The expected value should not be null.%n"
+ "If you were trying to filter on a null value, please use filteredOnNull(String propertyOrFieldName) instead");
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
* <p>
* Borrowed from Guava.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by calling {@link String#format(String, Object...)} with the given parameters.
* @param errorMessageArgs the arguments to be substituted into the message template.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
/**
* Ensures the truth of an expression using a supplier to fetch the error message in case of a failure.
*
* @param expression a boolean expression
* @param errorMessage a supplier to build the error message in case of failure. Must not be null.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and {@code errorMessage} is null (don't let this happen).
*/
public static void checkArgument(boolean expression, Supplier<String> errorMessage) {
if (!expression) throw new IllegalArgumentException(errorMessage.get());
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
* <p>
* Borrowed from Guava.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail.The
* message is formed by calling {@link String#format(String, Object...)} with the given parameters.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
}
}
private Preconditions() {}
private static void throwExceptionForBeingEmpty() {
throwExceptionForBeingEmpty(ARGUMENT_EMPTY);
}
private static void throwExceptionForBeingEmpty(String message) {
throw new IllegalArgumentException(message);
}
}
|
requireNonNull(s, message);
if (s.length() == 0) throwExceptionForBeingEmpty(message);
return s;
| 1,663
| 37
| 1,700
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Sets.java
|
Sets
|
newHashSet
|
class Sets {
/**
* Creates a <em>mutable</em> {@link LinkedHashSet} containing the given elements.
*
* @param <T> the generic type of the {@code HashSet} to create.
* @param elements the elements to store in the {@code HashSet}.
* @return the created {@code HashSet}, or {@code null} if the given array of elements is {@code null}.
*/
@SafeVarargs
public static <T> Set<T> set(T... elements) {
return newLinkedHashSet(elements);
}
/**
* Creates a <em>mutable</em> {@code HashSet}.
*
* @param <T> the generic type of the {@code HashSet} to create.
* @return the created {@code HashSet}.
*/
public static <T> HashSet<T> newHashSet() {
return new HashSet<>();
}
/**
* Creates a <em>mutable</em> {@code HashSet} containing the given elements.
*
* @param <T> the generic type of the {@code HashSet} to create.
* @param elements the elements to store in the {@code HashSet}.
* @return the created {@code HashSet}, or {@code null} if the given array of elements is {@code null}.
*/
public static <T> HashSet<T> newHashSet(Iterable<? extends T> elements) {<FILL_FUNCTION_BODY>}
/**
* Creates a <em>mutable</em> {@code LinkedHashSet}.
*
* @param <T> the generic type of the {@code LinkedHashSet} to create.
* @return the created {@code LinkedHashSet}.
*/
public static <T> LinkedHashSet<T> newLinkedHashSet() {
return new LinkedHashSet<>();
}
/**
* Creates a <em>mutable</em> {@link LinkedHashSet} containing the given elements.
*
* @param <T> the generic type of the {@code LinkedHashSet} to create.
* @param elements the elements to store in the {@code LinkedHashSet}.
* @return the created {@code LinkedHashSet}, or {@code null} if the given array of elements is {@code null}.
*/
@SafeVarargs
public static <T> LinkedHashSet<T> newLinkedHashSet(T... elements) {
if (elements == null) {
return null;
}
LinkedHashSet<T> set = newLinkedHashSet();
java.util.Collections.addAll(set, elements);
return set;
}
/**
* Creates a <em>mutable</em> {@link TreeSet}.
*
* @param <T> the generic type of the {@link TreeSet} to create.
* @return the created {@link TreeSet}.
*/
public static <T> TreeSet<T> newTreeSet() {
return new TreeSet<>();
}
/**
* Creates a <em>mutable</em> {@link TreeSet} containing the given elements.
*
* @param <T> the generic type of the {@link TreeSet} to create.
* @param elements the elements to store in the {@link TreeSet}.
* @return the created {@link TreeSet}, or {@code null} if the given array of elements is {@code null}.
*/
@SafeVarargs
public static <T> TreeSet<T> newTreeSet(T... elements) {
if (elements == null) {
return null;
}
TreeSet<T> set = newTreeSet();
java.util.Collections.addAll(set, elements);
return set;
}
private Sets() {}
}
|
if (elements == null) {
return null;
}
return Streams.stream(elements).collect(toCollection(HashSet::new));
| 937
| 40
| 977
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/Streams.java
|
Streams
|
stream
|
class Streams {
/**
* Returns a sequential {@link Stream} of the contents of {@code iterable}, delegating to {@link
* Collection#stream} if possible.
* @param <T> the stream type
* @param iterable the iterable to built the stream from
* @return the stream built from the given {@link Iterable}
*/
public static <T> Stream<T> stream(Iterable<T> iterable) {<FILL_FUNCTION_BODY>}
public static <T> Stream<T> stream(Iterator<T> iterator) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
}
}
|
return (iterable instanceof Collection)
? ((Collection<T>) iterable).stream()
: StreamSupport.stream(iterable.spliterator(), false);
| 175
| 42
| 217
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/TextFileWriter.java
|
TextFileWriter
|
write
|
class TextFileWriter {
private static final TextFileWriter INSTANCE = new TextFileWriter();
public static TextFileWriter instance() {
return INSTANCE;
}
public void write(File file, String... content) throws IOException {
write(file, Charset.defaultCharset(), content);
}
public void write(File file, Charset charset, String... content) throws IOException {<FILL_FUNCTION_BODY>}
private TextFileWriter() {}
}
|
try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), charset))) {
for (String line : content) {
writer.println(line);
}
}
| 123
| 53
| 176
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/URLs.java
|
URLs
|
contentOf
|
class URLs {
private URLs() {}
/**
* Loads the text content of a URL into a character string.
*
* @param url the URL.
* @param charsetName the name of the character set to use.
* @return the content of the file.
* @throws IllegalArgumentException if the given character set is not supported on this platform.
* @throws UncheckedIOException if an I/O exception occurs.
*/
public static String contentOf(URL url, String charsetName) {
checkArgumentCharsetIsSupported(charsetName);
return contentOf(url, Charset.forName(charsetName));
}
/**
* Loads the text content of a URL into a character string.
*
* @param url the URL.
* @param charset the character set to use.
* @return the content of the URL.
* @throws NullPointerException if the given charset is {@code null}.
* @throws UncheckedIOException if an I/O exception occurs.
*/
public static String contentOf(URL url, Charset charset) {<FILL_FUNCTION_BODY>}
/**
* Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are
* either \n, \r or \r\n.
*
* @param url the URL.
* @param charset the character set to use.
* @return the content of the URL.
* @throws NullPointerException if the given charset is {@code null}.
* @throws UncheckedIOException if an I/O exception occurs.
*/
public static List<String> linesOf(URL url, Charset charset) {
requireNonNull(charset, "The charset should not be null");
try {
return loadLines(url.openStream(), charset);
} catch (IOException e) {
throw new UncheckedIOException("Unable to read " + url, e);
}
}
/**
* Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are
* either \n, \r or \r\n.
*
* @param url the URL.
* @param charsetName the name of the character set to use.
* @return the content of the URL.
* @throws NullPointerException if the given charset is {@code null}.
* @throws UncheckedIOException if an I/O exception occurs.
*/
public static List<String> linesOf(URL url, String charsetName) {
checkArgumentCharsetIsSupported(charsetName);
return linesOf(url, Charset.forName(charsetName));
}
private static String loadContents(InputStream stream, Charset charset) throws IOException {
try (StringWriter writer = new StringWriter();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
int c;
while ((c = reader.read()) != -1) {
writer.write(c);
}
return writer.toString();
}
}
private static List<String> loadLines(InputStream stream, Charset charset) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
return reader.lines().collect(Collectors.toList());
}
}
private static void checkArgumentCharsetIsSupported(String charsetName) {
checkArgument(Charset.isSupported(charsetName), "Charset:<'%s'> is not supported on this system", charsetName);
}
}
|
requireNonNull(charset, "The charset should not be null");
try {
return loadContents(url.openStream(), charset);
} catch (IOException e) {
throw new UncheckedIOException("Unable to read " + url, e);
}
| 895
| 68
| 963
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.