focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
UnixUser user;
try {
user = (new PAM(this.getService()))
.authenticate(userToken.getUsernam... | @Test
public void testDoGetAuthenticationInfo() {
PamRealm realm = new PamRealm();
realm.setService("sshd");
String pamUser = System.getenv("PAM_USER");
String pamPass = System.getenv("PAM_PASS");
assumeTrue(pamUser != null);
assumeTrue(pamPass != null);
// mock shiro auth token
User... |
@Override
public String getMediaType() {
return firstNonNull(
mediaTypeFromUrl(source.getRequestURI()),
firstNonNull(
acceptedContentTypeInResponse(),
MediaTypes.DEFAULT));
} | @Test
public void getMediaType() {
when(source.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaTypes.JSON);
when(source.getRequestURI()).thenReturn("/path/to/resource/search");
assertThat(underTest.getMediaType()).isEqualTo(MediaTypes.JSON);
} |
@Override
public void e(String tag, String message, Object... args) {
Log.e(tag, formatString(message, args));
} | @Test
public void errorWithThrowableLoggedCorrectly() {
String expectedMessage = "Hello World";
Throwable t = new Throwable("Test Throwable");
logger.e(t, tag, "Hello %s", "World");
assertLogged(ERROR, tag, expectedMessage, t);
} |
public ClientConfig build() {
return build(Thread.currentThread().getContextClassLoader());
} | @Override
@Test
public void loadingThroughSystemProperty_existingClasspathResource() {
System.setProperty("hazelcast.client.config", "classpath:test-hazelcast-client.xml");
XmlClientConfigBuilder configBuilder = new XmlClientConfigBuilder();
ClientConfig config = configBuilder.build();
... |
@Nonnull
@Override
public CpcSketch getResult() {
return unionAll();
} | @Test
public void testUnionWithEmptyInput() {
CpcSketchAccumulator accumulator = new CpcSketchAccumulator(_lgNominalEntries, 3);
CpcSketchAccumulator emptyAccumulator = new CpcSketchAccumulator(_lgNominalEntries, 3);
accumulator.merge(emptyAccumulator);
Assert.assertTrue(accumulator.isEmpty());
... |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the number of days since 1970-01-01 00:00:00 UTC/GMT.")
public int stringToDate(
@UdfParameter(
description = "The string representation of a date.") final String formattedDate,
@UdfParameter(
... | @Test
public void shouldBeThreadSafeAndWorkWithManyDifferentFormatters() {
IntStream.range(0, 10_000)
.parallel()
.forEach(idx -> {
try {
final String sourceDate = "2021-12-01X" + idx;
final String pattern = "yyyy-MM-dd'X" + idx + "'";
final int result... |
public static boolean isRoute(URL url) {
return ROUTE_PROTOCOL.equals(url.getProtocol()) || ROUTERS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY));
} | @Test
public void testIsRoute() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "route://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "http://example.com?category=routers";
URL ... |
@Override
public void setPermission(final Path file, final TransferStatus status) throws BackgroundException {
try {
final Path bucket = containerService.getContainer(file);
if(containerService.isContainer(file)) {
final List<BucketAccessControl> bucketAccessControls ... | @Test(expected = NotfoundException.class)
public void testWriteNotFound() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
... |
public static void copyFile(File src, File target) throws IOException {
FileUtils.copyFile(src, target);
} | @Test
void testCopyFile() throws IOException {
File nacos = DiskUtils.createTmpFile("nacos", ".ut");
DiskUtils.copyFile(testFile, nacos);
assertEquals(DiskUtils.readFile(testFile), DiskUtils.readFile(nacos));
nacos.deleteOnExit();
} |
@VisibleForTesting
static List<Tuple2<ConfigGroup, String>> generateTablesForClass(
Class<?> optionsClass, Collection<OptionWithMetaInfo> optionWithMetaInfos) {
ConfigGroups configGroups = optionsClass.getAnnotation(ConfigGroups.class);
List<OptionWithMetaInfo> allOptions = selectOptions... | @Test
void testCreatingMultipleGroups() {
final List<Tuple2<ConfigGroup, String>> tables =
ConfigOptionsDocGenerator.generateTablesForClass(
TestConfigMultipleSubGroup.class,
ConfigurationOptionLocator.extractConfigOptions(
... |
public static <T> Values<T> of(Iterable<T> elems) {
return new Values<>(elems, Optional.absent(), Optional.absent(), false);
} | @Test
@Category(ValidatesRunner.class)
public void testCreate() {
PCollection<String> output = p.apply(Create.of(LINES));
PAssert.that(output).containsInAnyOrder(LINES_ARRAY);
p.run();
} |
public static Coin ofBtc(BigDecimal coins) throws ArithmeticException {
return Coin.valueOf(btcToSatoshi(coins));
} | @Test
public void testOfBtc() {
assertEquals(Coin.valueOf(Long.MIN_VALUE), Coin.ofBtc(new BigDecimal("-92233720368.54775808")));
assertEquals(ZERO, Coin.ofBtc(BigDecimal.ZERO));
assertEquals(COIN, Coin.ofBtc(BigDecimal.ONE));
assertEquals(Coin.valueOf(Long.MAX_VALUE), Coin.ofBtc(new ... |
public void createUsersWithArrayInput(List<User> body) throws RestClientException {
createUsersWithArrayInputWithHttpInfo(body);
} | @Test
public void createUsersWithArrayInputTest() {
List<User> body = null;
api.createUsersWithArrayInput(body);
// TODO: test validations
} |
@Override
public String toString() {
return "EntryView{"
+ "key=" + key
+ ", value=" + value
+ ", cost=" + cost
+ ", creationTime=" + creationTime
+ ", expirationTime=" + expirationTime
+ ", hits=" + hits
... | @Test
public void test_toString() throws Exception {
HazelcastInstance instance = createHazelcastInstance();
IMap<Integer, Integer> map = instance.getMap("test");
map.put(1, 1);
EntryView<Integer, Integer> entryView = map.getEntryView(1);
assertEquals(stringify(entryView), ... |
@Nonnull
public static Number mul(@Nonnull Number first, @Nonnull Number second) {
// Check for widest types first, go down the type list to narrower types until reaching int.
if (second instanceof Double || first instanceof Double) {
return first.doubleValue() * second.doubleValue();
} else if (second instan... | @Test
void testMul() {
assertEquals(21, NumberUtil.mul(3, 7));
assertEquals(21D, NumberUtil.mul(3, 7.0D));
assertEquals(21F, NumberUtil.mul(3, 7.0F));
assertEquals(21L, NumberUtil.mul(3, 7L));
} |
@Override
public Map<String, Boolean> getProjectUuidToManaged(DbSession dbSession, Set<String> projectUuids) {
return findManagedProjectService()
.map(managedProjectService -> managedProjectService.getProjectUuidToManaged(dbSession, projectUuids))
.orElse(returnNonManagedForAll(projectUuids));
} | @Test
public void getProjectUuidToManaged_whenNoDelegates_setAllProjectsAsNonManaged() {
Set<String> projectUuids = Set.of("a", "b");
DelegatingManagedServices managedInstanceService = NO_MANAGED_SERVICES;
Map<String, Boolean> projectUuidToManaged = managedInstanceService.getProjectUuidToManaged(dbSessio... |
public static void copyFile(String source, String target) throws IOException {
File sf = new File(source);
if (!sf.exists()) {
throw new IllegalArgumentException("source file does not exist.");
}
File tf = new File(target);
if (!tf.getParentFile().mkdirs()) {
... | @Test
public void testCopyFile() throws Exception {
String sourcePath = sourceFile.getAbsolutePath();
String targetPath = sourceFile.getParent() + File.separator + "copy" + File.separator + "target.txt";
IoUtil.copyFile(sourcePath, targetPath);
File targetFile = new File(targetPath);... |
public static void addShutdownHook(String name, Runnable runnable) {
shutdownHookAdder.addShutdownHook(name, runnable);
} | @Test
public void shouldNotInvokeShutdownHookImmediately() {
List<Object> list = new ArrayList<>();
Runnable runnable = () -> list.add(this);
Exit.addShutdownHook("message", runnable);
assertEquals(0, list.size());
} |
public List<String> deprecationPaths(Flow flow) {
return deprecationTraversal("", flow).toList();
} | @SuppressWarnings("deprecation")
@Test
void propertyRenamingDeprecation() {
Flow flow = Flow.builder()
.id("flowId")
.namespace("io.kestra.unittest")
.inputs(List.of(
StringInput.builder()
.id("inputWithId")
.typ... |
protected void logEdit(short op, Writable writable) {
JournalTask task = submitLog(op, writable, -1);
waitInfinity(task);
} | @Test
public void testInterrupt() throws Exception {
// block if more than one task is put
BlockingQueue<JournalTask> journalQueue = new ArrayBlockingQueue<>(1);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
EditLog editLog = ne... |
@Override
public void appendDataInfluence(String entityName, String entityId, String fieldName,
String fieldCurrentValue) {
// might be
if (traceContext.tracer() == null) {
return;
}
if (traceContext.tracer().getActiveSpan() == null) {
return;
}
String spanId = traceContext.t... | @Test
public void testAppendDataInfluenceCaseDelete() {
{
ApolloAuditSpan span = Mockito.mock(ApolloAuditSpan.class);
Mockito.when(tracer.getActiveSpan()).thenReturn(span);
Mockito.when(span.spanId()).thenReturn(spanId);
Mockito.when(span.getOpType()).thenReturn(delete);
}
api.app... |
@Override
public int getOrder() {
return 0;
} | @Test
void testGetOrder() {
int order = configEncryptionFilter.getOrder();
assertEquals(0, order);
} |
public void add(TProtocol p) {
events.addLast(p);
} | @Test
public void testList() throws TException {
final List<String> names = new ArrayList<String>();
names.add("John");
names.add("Jack");
final TestNameList o = new TestNameList("name", names);
validate(o);
} |
private boolean init() {
// Check and create backup dir if necessarily
File backupDir = new File(BACKUP_ROOT_DIR.toString());
if (!backupDir.exists()) {
if (!backupDir.mkdirs()) {
LOG.warn("failed to create backup dir: " + BACKUP_ROOT_DIR);
return fals... | @Test
public void testInit(@Mocked GlobalStateMgr globalStateMgr, @Mocked BrokerMgr brokerMgr, @Mocked EditLog editLog) {
setUpMocker(globalStateMgr, brokerMgr, editLog);
handler = new BackupHandler(globalStateMgr);
handler.runAfterCatalogReady();
File backupDir = new File(BackupHan... |
@Override
public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler,
Metadata metadata, ParseContext context)
throws IOException, SAXException, TikaException {
INDArray image = imageLoader.asMatrix(stream);
preProcessor... | @Test
public void recognise() throws Exception {
assumeFalse(SystemUtils.OS_ARCH.equals("aarch64"), "doesn't yet work on aarch64");
TikaConfig config = null;
try (InputStream is = getClass().getResourceAsStream("dl4j-vgg16-config.xml")) {
config = new TikaConfig(is);
} ca... |
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof EipAttribute)) {
return false;
}
return id.equals(((EipAttribute) o).id);
} | @Test
public void testEquals() {
EipAttribute attribute1 = getInstance();
EipAttribute attribute2 = getInstance();
boolean result = attribute1.equals(attribute1);
assertTrue(result);
result = attribute1.equals(attribute2);
assertTrue(result);
result = att... |
@Override
public Set<String> initialize() {
try {
checkpointFileCache.putAll(checkpointFile.read());
} catch (final IOException e) {
throw new StreamsException("Failed to read checkpoints for global state globalStores", e);
}
final Set<String> changelogTopics... | @Test
public void shouldNotDeleteCheckpointFileAfterLoaded() throws IOException {
writeCheckpoint();
stateManager.initialize();
assertTrue(checkpointFile.exists());
} |
public MapConfig setAsyncBackupCount(int asyncBackupCount) {
this.asyncBackupCount = checkAsyncBackupCount(backupCount, asyncBackupCount);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setAsyncBackupCount_whenTooLarge() {
MapConfig config = new MapConfig();
// max allowed is 6
config.setAsyncBackupCount(200);
} |
public static List<String> split( String str, char delim ) {
return split( str, delim, false, false );
} | @Test
void split() {
// empty
assertEquals(
Arrays.asList( "" ),
StringUtils.split( "", ',' ) );
// not empty
assertEquals(
Arrays.asList( "a" ),
StringUtils.split( "a", ',' ) );
assertEquals(
Arrays.asList( "a", "b" ),
StringUtils.split( "a,b", ',' ) );
assertEquals(
Arrays.asList( "... |
@Override
@Deprecated
public void process(final org.apache.kafka.streams.processor.ProcessorSupplier<? super K, ? super V> processorSupplier,
final String... stateStoreNames) {
process(processorSupplier, Named.as(builder.newProcessorName(PROCESSOR_NAME)), stateStoreNames);
} | @Test
public void shouldNotAllowNullProcessSupplierOnProcessValuesWithNamedAndStores() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.process((ProcessorSupplier<? super String, ? super String, Void, Void>) null,
Nam... |
@Override
protected void runTask() {
LOGGER.debug("Updating currently processed jobs... ");
convertAndProcessJobs(new ArrayList<>(backgroundJobServer.getJobSteward().getJobsInProgress()), this::updateCurrentlyProcessingJob);
} | @Test
void evenWhenNoWorkCanBeOnboardedJobsThatAreProcessedAreBeingUpdatedWithAHeartbeat() {
// GIVEN
final Job job = anEnqueuedJob().withId().build();
startProcessingJob(job);
// WHEN
runTask(task);
// THEN
verify(storageProvider).save(singletonList(job));
... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
try {
for(final DavResource resource : this.list(file)) {
... | @Test
public void testFindFile() throws Exception {
final Path test = new DAVTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(),
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
final DAVAttributesFinde... |
public StreamDestinationFilterRuleDTO deleteFromStream(String streamId, String id) {
final var dto = utils.getById(id)
.orElseThrow(() -> new IllegalArgumentException(f("Couldn't find document with ID <%s> for deletion", id)));
if (collection.deleteOne(and(eq(FIELD_STREAM_ID, streamId),... | @Test
void deleteFromStreamWithInvalidID() {
assertThatThrownBy(() -> service.deleteFromStream("54e3deadbeefdeadbeef1000", "54e3deadbeefdeadbeef9999"))
.hasMessageContaining("54e3deadbeefdeadbeef9999")
.isInstanceOf(IllegalArgumentException.class);
} |
@Override
public void open(Configuration parameters) throws Exception {
this.rateLimiterTriggeredCounter =
getRuntimeContext()
.getMetricGroup()
.addGroup(
TableMaintenanceMetrics.GROUP_KEY, TableMaintenanceMetrics.GROUP_VALUE_DEFAULT)
.counter(TableMain... | @Test
void testEqDeleteRecordCount() throws Exception {
TriggerManager manager =
manager(
sql.tableLoader(TABLE_NAME),
new TriggerEvaluator.Builder().eqDeleteRecordCount(3).build());
try (KeyedOneInputStreamOperatorTestHarness<Boolean, TableChange, Trigger> testHarness =
... |
public PlanNode plan(Analysis analysis)
{
return planStatement(analysis, analysis.getStatement());
} | @Test
public void testSameScalarSubqueryIsAppliedOnlyOnce()
{
// three subqueries with two duplicates (coerced to two different types), only two scalar joins should be in plan
assertEquals(
countOfMatchingNodes(
plan("SELECT * FROM orders WHERE CAST(orderk... |
public static String password(String password) {
if (StrUtil.isBlank(password)) {
return StrUtil.EMPTY;
}
return StrUtil.repeat('*', password.length());
} | @Test
public void passwordTest() {
assertEquals("**********", DesensitizedUtil.password("1234567890"));
} |
public CoordinatorResult<DeleteGroupsResponseData.DeletableGroupResultCollection, CoordinatorRecord> deleteGroups(
RequestContext context,
List<String> groupIds
) throws ApiException {
final DeleteGroupsResponseData.DeletableGroupResultCollection resultCollection =
new DeleteGrou... | @Test
public void testDeleteGroups() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
GroupCoordinatorShard coordinator = new GroupCoordinatorShard(
new LogContext(),
... |
@Nullable static String lastStringHeader(Headers headers, String key) {
Header header = headers.lastHeader(key);
if (header == null || header.value() == null) return null;
return new String(header.value(), UTF_8);
} | @Test void lastStringHeader() {
record.headers().add("b3", new byte[] {'1'});
assertThat(KafkaHeaders.lastStringHeader(record.headers(), "b3"))
.isEqualTo("1");
} |
public static String join(CharSequence separator, Iterable<?> strings) {
Iterator<?> i = strings.iterator();
if (!i.hasNext()) {
return "";
}
StringBuilder sb = new StringBuilder(i.next().toString());
while (i.hasNext()) {
sb.append(separator);
sb.append(i.next().toString());
}... | @Test (timeout = 30000)
public void testJoin() {
List<String> s = new ArrayList<String>();
s.add("a");
s.add("b");
s.add("c");
assertEquals("", StringUtils.join(":", s.subList(0, 0)));
assertEquals("a", StringUtils.join(":", s.subList(0, 1)));
assertEquals("", StringUtils.join(':', s.subLi... |
private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder) {
if (jsonElement.isJsonObject()) {
parseObject(systemTs, result, builder, jsonElement.getAsJsonObject());
} else if (jsonElement.isJsonArray()) {... | @Test
public void testParseBigDecimalAsLong() {
var result = JsonConverter.convertToTelemetry(JsonParser.parseString("{\"meterReadingDelta\": 1E+1}"), 0L);
Assertions.assertEquals(10L, result.get(0L).get(0).getLongValue().get().longValue());
} |
static int readDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException {
// copy all the bytes that return immediately, stopping at the first
// read that doesn't return a full buffer.
int nextReadLength = Math.min(buf.remaining(), temp.length);
int totalBytesRead = 0;
int bytesR... | @Test
public void testDirectPositionAndLimit() throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocateDirect(20);
readBuffer.position(5);
readBuffer.limit(13);
readBuffer.mark();
MockInputStream stream = new MockInputStream(7);
int len = DelegatingSeekableInputStream.readDirectBuffer(... |
@Override
public Num calculate(BarSeries series, Position position) {
if (position == null || position.getEntry() == null || position.getExit() == null) {
return series.zero();
}
Returns returns = new Returns(series, position, Returns.ReturnType.LOG);
return calculateES(r... | @Test
public void calculateOnlyWithGainPositions() {
series = new MockBarSeries(numFunction, 100d, 105d, 106d, 107d, 108d, 115d);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, series));
... |
public ProviderBuilder telnet(String telnet) {
this.telnet = telnet;
return getThis();
} | @Test
void telnet() {
ProviderBuilder builder = ProviderBuilder.newBuilder();
builder.telnet("mocktelnethandler");
Assertions.assertEquals("mocktelnethandler", builder.build().getTelnet());
} |
public String getPackageWithoutClassName() {
if (className.contains(".")) {
return className.substring(0, className.lastIndexOf("."));
} else {
return "";
}
} | @Test
public void getPackageWithoutClassName() {
commonGetPackageWithoutClassName("test", "com.Test", "com");
} |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 1) {
if ("dateIntToTs".equals(methodName)) {
return dateIntToTs(args[0]);
} else if ("tsToDateInt".equals(methodName)) {
return tsToDateInt(args[0]);
}
} else if (args.length == 2) {
i... | @Test(expected = UnsupportedOperationException.class)
public void testCallTimeoutForDateTimeDeadlineInvalid() {
SelUtilFunc.INSTANCE.call("timeoutForDateTimeDeadline", new SelType[] {SelString.of("1 day")});
} |
@Override
public List<Pair<HoodieKey, Long>> fetchRecordKeysWithPositions(HoodieStorage storage, StoragePath filePath) {
return fetchRecordKeysWithPositions(storage, filePath, Option.empty());
} | @Test
public void testFetchRecordKeyPartitionPathVirtualKeysFromParquet() throws Exception {
List<String> rowKeys = new ArrayList<>();
List<HoodieKey> expected = new ArrayList<>();
String partitionPath = "path1";
for (int i = 0; i < 1000; i++) {
String rowKey = UUID.randomUUID().toString();
... |
public void unJar(File jarFile, File toDir) throws IOException {
unJar(jarFile, toDir, MATCH_ANY);
} | @Test
public void testUnJar2() throws IOException {
// make a simple zip
File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_NAME);
JarOutputStream jstream =
new JarOutputStream(new FileOutputStream(jarFile));
JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
byte[] data = "Manifest-Version:... |
static void replaceHeader(Headers headers, String key, String value) {
headers.remove(key);
headers.add(key, value.getBytes(UTF_8));
} | @Test void replaceHeader_replace() {
record.headers().add("b3", new byte[0]);
KafkaHeaders.replaceHeader(record.headers(), "b3", "1");
assertThat(record.headers().lastHeader("b3").value())
.containsExactly('1');
} |
@Override
public void blame(BlameInput input, BlameOutput output) {
File basedir = input.fileSystem().baseDir();
try (Repository repo = JGitUtils.buildRepository(basedir.toPath())) {
File gitBaseDir = repo.getWorkTree();
if (cloneIsInvalid(gitBaseDir)) {
return;
}
Profiler pro... | @Test
@UseDataProvider("blameAlgorithms")
public void blame_on_nested_module(BlameAlgorithmEnum strategy) throws IOException {
CompositeBlameCommand blameCommand = new CompositeBlameCommand(analysisWarnings, pathResolver, jGitBlameCommand, nativeGitBlameCommand, (p, f) -> strategy);
File projectDir = create... |
@Override
public synchronized Response handle(Request req) { // note the [synchronized]
if (corsEnabled && "OPTIONS".equals(req.getMethod())) {
Response response = new Response(200);
response.setHeader("Allow", ALLOWED_METHODS);
response.setHeader("Access-Control-Allow-Or... | @Test
void testUrlWithSpecialCharacters() {
background().scenario(
"pathMatches('/hello/{raw}')",
"def response = pathParams.raw"
);
request.path("/hello/�Ill~Formed@RequiredString!");
handle();
match(response.getBodyAsString(), "�Ill~Formed@Re... |
@Override
public int getDecimals(final int columnIndex) throws SQLException {
return resultSetMetaData.getScale(columnIndex);
} | @Test
void assertGetDecimals() throws SQLException {
assertThat(queryResultMetaData.getDecimals(1), is(0));
} |
public List<? extends COSBase> toList()
{
return new ArrayList<>(objects);
} | @Test
void testToList()
{
COSArray cosArray = COSArray
.ofCOSIntegers(Arrays.asList(0, 1, 2, 3, 4, 5));
List<? extends COSBase> list = cosArray.toList();
assertEquals(6, list.size());
assertEquals(COSInteger.get(0), list.get(0));
assertEquals(COSInteger.ge... |
@Override
public IcebergEnumeratorState snapshotState(long checkpointId) {
return new IcebergEnumeratorState(
enumeratorPosition.get(), assigner.state(), enumerationHistory.snapshot());
} | @Test
public void testRequestingReaderUnavailableWhenSplitDiscovered() throws Exception {
TestingSplitEnumeratorContext<IcebergSourceSplit> enumeratorContext =
new TestingSplitEnumeratorContext<>(4);
ScanContext scanContext =
ScanContext.builder()
.streaming(true)
.star... |
@Override
public Table getTable(String dbName, String tblName) {
Table table;
try {
table = hmsOps.getTable(dbName, tblName);
} catch (StarRocksConnectorException e) {
LOG.error("Failed to get hive table [{}.{}.{}]", catalogName, dbName, tblName, e);
throw... | @Test
public void testGetTableThrowConnectorException() {
new Expectations(hmsOps) {
{
hmsOps.getTable("acid_db", "acid_table");
result = new StarRocksConnectorException("hive acid table is not supported");
minTimes = 1;
}
};
... |
public static String getCharsetNameFromContentType(String contentType) {
// try optimized for direct match without using splitting
int pos = contentType.indexOf("charset=");
if (pos != -1) {
// special optimization for utf-8 which is a common charset
if (contentType.regio... | @Test
public void testCharset() {
assertEquals("UTF-8", IOHelper.getCharsetNameFromContentType("charset=utf-8"));
assertEquals("UTF-8", IOHelper.getCharsetNameFromContentType("charset=UTF-8"));
assertEquals("UTF-8", IOHelper.getCharsetNameFromContentType("text/plain; charset=UTF-8"));
... |
static void validateRegion(String region) {
if (region == null) {
throw new InvalidConfigurationException("The provided region is null.");
}
if (!AWS_REGION_PATTERN.matcher(region).matches()) {
String message = String.format("The provided region %s is not a valid AWS regi... | @Test
public void validateInvalidRegion() {
// given
String region = "us-wrong-1";
String expectedMessage = String.format("The provided region %s is not a valid AWS region.", region);
//when
ThrowingRunnable validateRegion = () -> RegionValidator.validateRegion(region);
... |
public int getNumber4()
{
checkAvailable(4);
return get(Wire::getUInt32, 4);
} | @Test(expected = IllegalArgumentException.class)
public void testGetIncorrectInt()
{
ZFrame frame = new ZFrame(new byte[3]);
ZNeedle needle = new ZNeedle(frame);
needle.getNumber4();
} |
@SuppressWarnings("unchecked")
@Override
public OUT extract(Object in) {
return (OUT) Array.get(in, fieldId);
} | @Test
void testStringArray() {
for (int i = 0; i < this.testStringArray.length; i++) {
assertThat(new FieldFromArray<String>(i).extract(testStringArray))
.isEqualTo(testStringArray[i]);
}
} |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testUnsupportedForMessageFormatInProduceRequest() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerId(producerId, Erro... |
public static boolean isDomain(String str) {
if (StringUtils.isBlank(str)) {
return false;
}
if (Objects.equals(str, LOCAL_HOST)) {
return true;
}
return DOMAIN_PATTERN.matcher(str).matches();
} | @Test
void testIsDomain() {
assertTrue(InternetAddressUtil.isDomain("localhost"));
assertTrue(InternetAddressUtil.isDomain("github.com"));
assertTrue(InternetAddressUtil.isDomain("prefix.infix.suffix"));
assertTrue(InternetAddressUtil.isDomain("p-hub.com"));
assertFa... |
public static long computeStartOfNextSecond(long now) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(now));
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.SECOND, 1);
return cal.getTime().getTime();
} | @Test
public void testSecond() {
// Mon Nov 20 18:05:17,522 CET 2006
long now = 1164042317522L;
// Mon Nov 20 18:05:18,000 CET 2006
long expected = 1164042318000L;
long computed = TimeUtil.computeStartOfNextSecond(now);
Assertions.assertEquals(expected - now, 478);
... |
public void createOperator(StreamOperatorParameters<RowData> parameters) {
checkArgument(wrapped == null, "This operator has been initialized");
if (factory instanceof ProcessingTimeServiceAware) {
((ProcessingTimeServiceAware) factory)
.setProcessingTimeService(parameter... | @Test
public void testCreateOperator() throws Exception {
TestingOneInputStreamOperator operator = new TestingOneInputStreamOperator();
TableOperatorWrapper<TestingOneInputStreamOperator> wrapper =
createOneInputOperatorWrapper(operator, "test");
StreamOperatorParameters<RowD... |
@Override
public AwsProxyResponse handle(Throwable ex) {
log.error("Called exception handler for:", ex);
// adding a print stack trace in case we have no appender or we are running inside SAM local, where need the
// output to go to the stderr.
ex.printStackTrace();
if (ex i... | @Test
void typedHandle_InternalServerErrorException_500State() {
// Needed to mock InternalServerErrorException because it leverages RuntimeDelegate to set an internal
// response object.
InternalServerErrorException mockInternalServerErrorException = Mockito.mock(InternalServerErrorExceptio... |
public static <T> void concat(T[] sourceFirst, T[] sourceSecond, T[] dest) {
System.arraycopy(sourceFirst, 0, dest, 0, sourceFirst.length);
System.arraycopy(sourceSecond, 0, dest, sourceFirst.length, sourceSecond.length);
} | @Test(expected = NullPointerException.class)
public void concat_whenFirstNull() {
Integer[] first = null;
Integer[] second = new Integer[]{4};
Integer[] concatenated = new Integer[4];
ArrayUtils.concat(first, second, concatenated);
fail();
} |
public static List<List<String>> dump(SetType type, SessionVariable sessionVar, PatternMatcher matcher) {
List<List<String>> rows = Lists.newArrayList();
// Hold the read lock when session dump, because this option need to access global variable.
RLOCK.lock();
try {
for (Map.... | @Test
public void testDumpInvisible() {
SessionVariable sv = new SessionVariable();
List<List<String>> vars = VariableMgr.dump(SetType.SESSION, sv, null);
Assert.assertFalse(vars.toString().contains("enable_show_all_variables"));
Assert.assertFalse(vars.toString().contains("cbo_use_c... |
public void triggerNextSuperstep() {
synchronized (monitor) {
if (terminated) {
throw new IllegalStateException("Already terminated.");
}
superstepNumber++;
monitor.notifyAll();
}
} | @Test
public void testWaitFromOne() {
try {
SuperstepKickoffLatch latch = new SuperstepKickoffLatch();
Waiter w = new Waiter(latch, 2);
Thread waiter = new Thread(w);
waiter.setDaemon(true);
waiter.start();
WatchDog wd = new WatchDog(... |
public long maxOffset(MessageQueue mq) throws MQClientException {
return this.mQClientFactory.getMQAdminImpl().maxOffset(mq);
} | @Test
public void testMaxOffset() throws MQClientException {
assertEquals(0, defaultMQPushConsumerImpl.maxOffset(createMessageQueue()));
} |
void makeAsFarAs(ExecNode<?> a, ExecNode<?> b) {
TopologyNode nodeA = getOrCreateTopologyNode(a);
TopologyNode nodeB = getOrCreateTopologyNode(b);
for (TopologyNode input : nodeB.inputs) {
link(input.execNode, nodeA.execNode);
}
} | @Test
void testMakeAsFarAs() {
Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildTopologyGraph();
TopologyGraph graph = tuple2.f0;
TestingBatchExecNode[] nodes = tuple2.f1;
graph.makeAsFarAs(nodes[4], nodes[7]);
Map<ExecNode<?>, Integer> distances = graph.calculate... |
public List<Stream> match(Message message) {
final Set<Stream> result = Sets.newHashSet();
final Set<String> blackList = Sets.newHashSet();
for (final Rule rule : rulesList) {
if (blackList.contains(rule.getStreamId())) {
continue;
}
final St... | @Test
public void testTestMatch() throws Exception {
final StreamMock stream = getStreamMock("test");
final StreamRuleMock rule1 = new StreamRuleMock(ImmutableMap.of(
"_id", new ObjectId(),
"field", "testfield1",
"type", StreamRuleType.PRESENCE.toInteg... |
@VisibleForTesting
Optional<Set<String>> getSchedulerResourceTypeNamesUnsafe(final Object response) {
if (getSchedulerResourceTypesMethod.isPresent() && response != null) {
try {
@SuppressWarnings("unchecked")
final Set<? extends Enum> schedulerResourceTypes =
... | @Test
void testCallsGetSchedulerResourceTypesMethodIfPresent() {
final RegisterApplicationMasterResponseReflector
registerApplicationMasterResponseReflector =
new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class);
final Optional<Set<String>> sc... |
public static CreateSourceProperties from(final Map<String, Literal> literals) {
try {
return new CreateSourceProperties(literals, DurationParser::parse, false);
} catch (final ConfigException e) {
final String message = e.getMessage().replace(
"configuration",
"property"
)... | @Test
public void shouldThrowOnInvalidSourceConnectorPropertyType() {
// Given:
final Map<String, Literal> props = ImmutableMap.<String, Literal>builder()
.putAll(MINIMUM_VALID_PROPS)
.put(CreateConfigs.SOURCED_BY_CONNECTOR_PROPERTY, new IntegerLiteral(1))
.build();
// When:
f... |
static boolean checkChunkSane(Chunk chunk)
{
if (chunk == null)
{
// If the chunk does not exist, it can not be wrong...
return true;
}
if (chunk.start + chunk.length > chunk.bytes.length)
{
return false;
}
if (chunk.start... | @Test
void testChunkSane()
{
PNGConverter.Chunk chunk = new PNGConverter.Chunk();
assertTrue(PNGConverter.checkChunkSane(null));
chunk.bytes = "IHDRsomedummyvaluesDummyValuesAtEnd".getBytes();
chunk.length = 19;
assertEquals(35, chunk.bytes.length);
assertEquals(... |
public static void processEnvVariables(Map<String, String> inputProperties) {
processEnvVariables(inputProperties, System.getenv());
} | @Test
void oldJsonEnvVariablesIsIgnoredIfNewIsDefinedAndLogAWarning() {
var inputProperties = new HashMap<String, String>();
EnvironmentConfig.processEnvVariables(inputProperties,
Map.of("SONARQUBE_SCANNER_PARAMS", "{\"key1\":\"should not override\", \"key3\":\"value3\"}",
"SONAR_SCANNER_JSON_PA... |
public static <T> T retryUntilTimeout(Callable<T> callable, Supplier<String> description, Duration timeoutDuration, long retryBackoffMs) throws Exception {
return retryUntilTimeout(callable, description, timeoutDuration, retryBackoffMs, Time.SYSTEM);
} | @Test
public void testWakeupException() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new WakeupException());
assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(50), 10, mockTime));
Mockito.verify(... |
@Override
public List<? extends Instance> listInstances(String namespaceId, String groupName, String serviceName,
String clusterName) throws NacosException {
Service service = Service.newService(namespaceId, groupName, serviceName);
if (!ServiceManager.getInstance().containSingleton(serv... | @Test
void testListInstances() throws NacosException {
Mockito.when(serviceStorage.getClusters(Mockito.any())).thenReturn(Collections.singleton("D"));
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setGroupName("B");
serviceInfo.setName("C");
Instance instance = new... |
public static void clear(Buffer buffer) {
buffer.clear();
} | @Test
public void testClear() {
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.putInt(1);
Assertions.assertDoesNotThrow(() -> BufferUtils.clear(byteBuffer));
} |
public static EnumMap<StepInstance.Status, WorkflowStepStatusSummary> toStepStatusMap(
WorkflowSummary summary, Map<String, StepRuntimeState> states) {
AtomicLong ordinal = new AtomicLong(0);
Map<String, Long> stepOrdinalMap =
summary.getRuntimeDag().keySet().stream()
.collect(Collecto... | @Test
public void testToStepStatusMap() throws Exception {
WorkflowSummary workflowSummary =
loadObject("fixtures/parameters/sample-wf-summary-params.json", WorkflowSummary.class);
StepRuntimeState state = new StepRuntimeState();
state.setStatus(StepInstance.Status.RUNNING);
state.setStartTime... |
public static TableConfig overwriteTableConfigForTier(TableConfig tableConfig, @Nullable String tier) {
if (tier == null) {
return tableConfig;
}
try {
boolean updated = false;
JsonNode tblCfgJson = tableConfig.toJsonNode();
// Apply tier specific overwrites for `tableIndexConfig`
... | @Test
public void testOverwriteTableConfigForTierWithError()
throws Exception {
TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(TABLE_NAME)
.setTierOverwrites(JsonUtils.stringToJsonNode("{\"coldTier\": {\"starTreeIndexConfigs\": {}}}")).build();
TableConfig tierT... |
@Override
public Map<String, Set<String>> read() {
Map<String, Set<String>> extensions = new HashMap<>();
for (String extensionPoint : processor.getExtensions().keySet()) {
try {
FileObject file = getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", EXTENSIONS_RESOU... | @Test
public void ensureServiceProviderExtensionStorageReadWorks() throws IOException {
final StringReader file = new StringReader("#hello\n World");
final Set<String> entries = new HashSet<>();
ServiceProviderExtensionStorage.read(file, entries);
assertThat(entries.size(), is(1)... |
public void changeFieldType(final CustomFieldMapping customMapping,
final Set<String> indexSetsIds,
final boolean rotateImmediately) {
checkFieldTypeCanBeChanged(customMapping.fieldName());
checkType(customMapping);
checkAllIndicesS... | @Test
void testCyclesIndexSet() {
doReturn(Optional.of(existingIndexSet)).when(indexSetService).get("existing_index_set");
doReturn(existingMongoIndexSet).when(mongoIndexSetFactory).create(any());
toTest.changeFieldType(newCustomMapping,
new LinkedHashSet<>(List.of("existing... |
public static Queue<Consumer<byte[]>> stopConsumers(final Queue<Consumer<byte[]>> consumers) throws PulsarClientException {
while (!consumers.isEmpty()) {
Consumer<byte[]> consumer = consumers.poll();
if (consumer != null) {
try {
consumer.close();
... | @Test
public void givenConsumerQueueIsEmptywhenIStopConsumersverifyEmptyQueueIsReturned() throws PulsarClientException {
Queue<Consumer<byte[]>> expected = PulsarUtils.stopConsumers(new ConcurrentLinkedQueue<Consumer<byte[]>>());
assertTrue(expected.isEmpty());
} |
@Override
public boolean add(final Integer value) {
return add(value.intValue());
} | @Test
@SuppressWarnings("UnnecessaryBoxing")
public void containsAddedBoxedElements() {
assertTrue(set.add(1));
assertTrue(set.add(Integer.valueOf(2)));
assertContains(set, Integer.valueOf(1));
assertContains(set, 2);
} |
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns... | @Test
void shouldCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("other.domain.com"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
... |
protected final void tryShutdown(final HazelcastInstance hazelcastInstance) {
OutOfMemoryHandlerHelper.tryShutdown(hazelcastInstance);
} | @Test
public void testTryShutdown() {
outOfMemoryHandler.shutdown(hazelcastInstance);
} |
@Override
public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) {
Objects.requireNonNull(intentOperationContext);
Optional<IntentData> toUninstall = intentOperationContext.toUninstall();
Optional<IntentData> toInstall = intentOperationContext.toInstall();
... | @Test
public void testGroupMissingError() {
// group exist -> group missing -> add group
intentInstallCoordinator = new TestIntentInstallCoordinator();
installer.intentInstallCoordinator = intentInstallCoordinator;
errors = ImmutableList.of(GROUPEXISTS, GROUPMISSING);
install... |
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
if (varbitChanged.getVarbitId() == Varbits.WINTERTODT_TIMER)
{
int timeToNotify = config.roundNotification();
// Sometimes wt var updates are sent to players even after leaving wt.
// So only notify if in wt or after just having left.
... | @Test
public void matchStartingNotification_shouldNotify_when5SecondsOptionSelected()
{
when(config.roundNotification()).thenReturn(5);
VarbitChanged varbitChanged = new VarbitChanged();
varbitChanged.setVarbitId(Varbits.WINTERTODT_TIMER);
varbitChanged.setValue(10);
wintertodtPlugin.onVarbitChanged(varbi... |
@Override
public void writeInt(final int v) throws IOException {
ensureAvailable(INT_SIZE_IN_BYTES);
Bits.writeInt(buffer, pos, v, isBigEndian);
pos += INT_SIZE_IN_BYTES;
} | @Test
public void testWriteIntV() throws Exception {
int expected = 100;
out.writeInt(expected);
int actual = Bits.readIntB(out.buffer, 0);
assertEquals(expected, actual);
} |
public synchronized ObjectId insertTransformationPartitionSchema( ObjectId id_transformation,
ObjectId id_partition_schema ) throws KettleException {
ObjectId id = connectionDelegate.getNextTransformationPartitionSchemaID();
RowMetaAndData table = new RowMetaAndData();
table.addValue( new ValueMetaInt... | @Test
public void testInsertTransformationPartitionSchema() throws KettleException {
ArgumentCaptor<String> argumentTableName = ArgumentCaptor.forClass( String.class );
ArgumentCaptor<RowMetaAndData> argumentTableData = ArgumentCaptor.forClass( RowMetaAndData.class );
doNothing().when( repo.connectionDele... |
@Override
public void updateRewardActivity(RewardActivityUpdateReqVO updateReqVO) {
// 校验存在
RewardActivityDO dbRewardActivity = validateRewardActivityExists(updateReqVO.getId());
if (dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 已关闭的活动,不能修改噢
... | @Test
public void testUpdateRewardActivity_success() {
// mock 数据
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus()));
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
// 准备参数
... |
public static <T> T createInstance(String userClassName,
Class<T> xface,
ClassLoader classLoader) {
Class<?> theCls;
try {
theCls = Class.forName(userClassName, true, classLoader);
} catch (ClassNotFoundExc... | @Test
public void testCreateInstanceNoNoArgConstructor() {
try {
createInstance(OneArgClass.class.getName(), classLoader);
fail("Should fail to load class doesn't have no-arg constructor");
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof NoSuch... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
String method = request.getMethod();
URI uri = request.getUri();
for (Rule rule : rules) {
if (rule.matches(method, uri)) {
log.log(Level.FINE, () ->
String.for... | @Test
void no_filtering_if_request_is_allowed() {
RuleBasedFilterConfig config = new RuleBasedFilterConfig.Builder()
.dryrun(false)
.defaultRule(new DefaultRule.Builder()
.action(DefaultRule.Action.Enum.ALLOW))
.build();
Metric... |
@Override
public Iterator<RawUnionValue> call(Iterator<WindowedValue<InputT>> inputs) throws Exception {
SparkPipelineOptions options = pipelineOptions.get().as(SparkPipelineOptions.class);
// Register standard file systems.
FileSystems.setDefaultPipelineOptions(options);
// Do not call processElemen... | @Test
public void testStageBundleClosed() throws Exception {
SparkExecutableStageFunction<Integer, ?> function = getFunction(Collections.emptyMap());
List<WindowedValue<Integer>> inputs = new ArrayList<>();
inputs.add(WindowedValue.valueInGlobalWindow(0));
function.call(inputs.iterator());
verify(... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatCreateSourceStreamStatement() {
// Given:
final CreateSourceProperties props = CreateSourceProperties.from(
new ImmutableMap.Builder<String, Literal>()
.putAll(SOME_WITH_PROPS.copyOfOriginalLiterals())
.build()
);
final CreateStream createS... |
public static boolean areCompatible(final SqlArgument actual, final ParamType declared) {
return areCompatible(actual, declared, false);
} | @Test
public void shouldPassCompatibleSchemas() {
assertThat(ParamTypes.areCompatible(
SqlArgument.of(SqlTypes.STRING),
ParamTypes.STRING,
false),
is(true));
assertThat(ParamTypes.areCompatible(
SqlArgument.of(SqlIntervalUnit.INSTANCE),
ParamTypes.INTERVALUNIT,... |
public static Object convert(Class<?> expectedClass, Object originalObject) {
if (originalObject == null) {
return null;
}
Class<?> currentClass = originalObject.getClass();
if (expectedClass.isAssignableFrom(currentClass)) {
return originalObject;
}
... | @Test
void convertUnconvertibleFromString() {
UNCONVERTIBLE_FROM_STRING.forEach((s, o) -> {
Class<?> expectedClass = o.getClass();
try {
ConverterTypeUtil.convert(expectedClass, s);
fail(String.format("Expecting KiePMMLException for %s %s", s, o));
... |
@VisibleForTesting
public static JobGraph createJobGraph(StreamGraph streamGraph) {
return new StreamingJobGraphGenerator(
Thread.currentThread().getContextClassLoader(),
streamGraph,
null,
Runnable::run)
... | @Test
void testStreamingJobTypeByDefault() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.fromData("test").sinkTo(new DiscardingSink<>());
JobGraph jobGraph = StreamingJobGraphGenerator.createJobGraph(env.getStreamGraph());
assertThat(job... |
public static ShearCaptcha createShearCaptcha(int width, int height) {
return new ShearCaptcha(width, height);
} | @Test
@Disabled
public void createTest() {
for(int i = 0; i < 1; i++) {
CaptchaUtil.createShearCaptcha(320, 240);
}
} |
public NamespaceBO loadNamespaceBO(String appId, Env env, String clusterName,
String namespaceName, boolean includeDeletedItems) {
NamespaceDTO namespace = namespaceAPI.loadNamespace(appId, env, clusterName, namespaceName);
if (namespace == null) {
throw BadRequestException.namespaceNotExists(appId,... | @Test
public void testLoadNamespaceBO() {
String branchName = "branch";
NamespaceDTO namespaceDTO = createNamespace(testAppId, branchName, testNamespaceName);
when(namespaceAPI.loadNamespace(any(), any(), any(), any())).thenReturn(namespaceDTO);
ReleaseDTO releaseDTO = new ReleaseDTO();
releaseDT... |
public int deliverAll(Set<EmailDeliveryRequest> deliveries) {
if (deliveries.isEmpty() || !isActivated()) {
LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG);
return 0;
}
return (int) deliveries.stream()
.filter(t -> !t.recipientEmail().isBlank())
.map(t -> {
EmailMessage emailM... | @Test
@UseDataProvider("emptyStrings")
public void deliverAll_ignores_requests_which_recipient_is_empty(String emptyString) {
EmailSmtpConfiguration emailSettings = mock(EmailSmtpConfiguration.class);
when(emailSettings.getSmtpHost()).thenReturn(null);
Set<EmailDeliveryRequest> requests = IntStream.rang... |
@Override
public void importData(JsonReader reader) throws IOException {
logger.info("Reading configuration for 1.1");
// this *HAS* to start as an object
reader.beginObject();
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();... | @Test
public void testImportSystemScopes() throws IOException {
SystemScope scope1 = new SystemScope();
scope1.setId(1L);
scope1.setValue("scope1");
scope1.setDescription("Scope 1");
scope1.setRestricted(true);
scope1.setDefaultScope(false);
scope1.setIcon("glass");
SystemScope scope2 = new SystemScop... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.