focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public CeWorker create(int ordinal) {
String uuid = uuidFactory.create();
CeWorkerImpl ceWorker = new CeWorkerImpl(ordinal, uuid, queue, taskProcessorRepository, ceWorkerController, executionListeners);
ceWorkers = Stream.concat(ceWorkers.stream(), Stream.of(ceWorker)).collect(Collectors.toSet()... | @Test
public void ceworker_created_by_factory_must_contain_uuid() {
CeWorker ceWorker = underTest.create(randomOrdinal);
assertThat(ceWorker.getUUID()).isNotEmpty();
} |
@Override
public boolean contains(Object o) {
throw new UnsupportedOperationException("LazySet does not support contains requests");
} | @Test(expected = UnsupportedOperationException.class)
@SuppressWarnings("ResultOfMethodCallIgnored")
public void testContains_throwsException() {
set.contains(null);
} |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
// Get the mime4j configuration, or use a default one
MimeConfig config =
new MimeConfig.Builder().setMaxLineLen(... | @Test
public void testUnusualFromAddress() throws Exception {
Metadata metadata = new Metadata();
InputStream stream = getStream("test-documents/testRFC822_oddfrom");
ContentHandler handler = mock(DefaultHandler.class);
EXTRACT_ALL_ALTERNATIVES_PARSER.parse(stream, handler, metadata... |
public static Object get(Object object, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
r... | @Test
void testGetArray5() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtils.get(new int[] {}, -1);
});
} |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testPuma8nhQuantile() {
test(Loss.quantile(0.5), "puma8nh", Puma8NH.formula, Puma8NH.data, 3.2486);
} |
public Path getSourceFileListing() {
return sourceFileListing;
} | @Test
public void testSourceListing() {
final DistCpOptions.Builder builder = new DistCpOptions.Builder(
new Path("hdfs://localhost:8020/source/first"),
new Path("hdfs://localhost:8020/target/"));
Assert.assertEquals(new Path("hdfs://localhost:8020/source/first"),
builder.build().getSo... |
@Override
public int calculateNewCapacity(int minNewCapacity, int maxCapacity) {
checkPositiveOrZero(minNewCapacity, "minNewCapacity");
if (minNewCapacity > maxCapacity) {
throw new IllegalArgumentException(String.format(
"minNewCapacity: %d (expected: not greater tha... | @Test
public void testCalculateNewCapacity() {
testCalculateNewCapacity(true);
testCalculateNewCapacity(false);
} |
public static boolean canDrop(FilterPredicate pred, List<ColumnChunkMetaData> columns) {
Objects.requireNonNull(pred, "pred cannot be null");
Objects.requireNonNull(columns, "columns cannot be null");
return pred.accept(new StatisticsFilter(columns));
} | @Test
public void testEqNonNull() {
assertTrue(canDrop(eq(intColumn, 9), columnMetas));
assertFalse(canDrop(eq(intColumn, 10), columnMetas));
assertFalse(canDrop(eq(intColumn, 100), columnMetas));
assertTrue(canDrop(eq(intColumn, 101), columnMetas));
// drop columns of all nulls when looking for ... |
@SneakyThrows({InterruptedException.class, ExecutionException.class})
@Override
public void persistEphemeral(final String key, final String value) {
buildParentPath(key);
long leaseId = client.getLeaseClient().grant(etcdProps.getValue(EtcdPropertyKey.TIME_TO_LIVE_SECONDS)).get().getID();
... | @Test
@SuppressWarnings("unchecked")
void assertPersistEphemeral() {
repository.persistEphemeral("key1", "value1");
verify(lease).grant(anyLong());
verify(lease).keepAlive(anyLong(), any(StreamObserver.class));
verify(kv).put(any(ByteSequence.class), any(ByteSequence.class), any(... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.get("list", concurrency);
try {
final String prefix = this.createPrefix(directory);
if(log.isDebugEnabl... | @Test
public void testEnableVersioningExistingFiles() throws Exception {
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path bucket = new S3DirectoryFeature(session, new S3WriteFeature(session, acl), acl)
.mkdir(new Path(new AsciiRandomStringSer... |
@Override
public synchronized void cleanupAll() {
LOG.info("Attempting to cleanup Cassandra manager.");
boolean producedError = false;
// First, delete the database if it was not given as a static argument
if (!usingStaticDatabase) {
try {
executeStatement(String.format("DROP KEYSPACE ... | @Test
public void testCleanupAllShouldThrowErrorWhenCassandraClientFailsToDropDatabase() {
doThrow(RuntimeException.class).when(cassandraClient).execute(any(SimpleStatement.class));
assertThrows(CassandraResourceManagerException.class, () -> testManager.cleanupAll());
} |
@VisibleForTesting
void setIsPartialBufferCleanupRequired() {
isPartialBufferCleanupRequired = true;
} | @TestTemplate
void testSkipPartialDataStartWithFullRecord() throws Exception {
final BufferWritingResultPartition writer = createResultPartition();
final PipelinedApproximateSubpartition subpartition =
getPipelinedApproximateSubpartition(writer);
writer.emitRecord(toByteBuff... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestExtendRecording()
{
internalEncodeLogHeader(buffer, 0, 12, 32, () -> 10_000_000_000L);
final ExtendRecordingRequestEncoder requestEncoder = new ExtendRecordingRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder)
... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testNewPersonalBest()
{
final String NEW_PB = "Fight duration: <col=ff0000>3:01</col> (new personal best).";
final String NEW_PB_PRECISE = "Fight duration: <col=ff0000>3:01.40</col> (new personal best).";
// This sets lastBoss
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "",... |
@Override
public List<PartitionInfo> getPartitions(Table table, List<String> partitionNames) {
Map<String, Partition> partitionMap = Maps.newHashMap();
IcebergTable icebergTable = (IcebergTable) table;
PartitionsTable partitionsTable = (PartitionsTable) MetadataTableUtils.
cr... | @Test
public void testGetPartitions1() {
mockedNativeTableB.newAppend().appendFile(FILE_B_1).appendFile(FILE_B_2).commit();
IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG);
CachingIcebergCatalog cachingIcebergCatalog = new Ca... |
Map<String, List<Phase2Context>> groupedByResourceId(List<Phase2Context> contexts) {
Map<String, List<Phase2Context>> groupedContexts = new HashMap<>(DEFAULT_RESOURCE_SIZE);
contexts.forEach(context -> {
if (StringUtils.isBlank(context.resourceId)) {
LOGGER.warn("resourceId i... | @Test
void groupedByResourceId() {
List<AsyncWorker.Phase2Context> contexts = getRandomContexts();
Map<String, List<AsyncWorker.Phase2Context>> groupedContexts = worker.groupedByResourceId(contexts);
groupedContexts.forEach((resourceId, group) -> group.forEach(context -> {
String... |
public boolean similarTo(ClusterStateBundle other) {
if (!baselineState.getClusterState().similarToIgnoringInitProgress(other.baselineState.getClusterState())) {
return false;
}
if (clusterFeedIsBlocked() != other.clusterFeedIsBlocked()) {
return false;
}
... | @Test
void similarity_test_considers_all_bucket_spaces() {
ClusterStateBundle bundle = createTestBundle(false);
ClusterStateBundle unchangedBundle = createTestBundle(false);
assertTrue(bundle.similarTo(unchangedBundle));
assertTrue(unchangedBundle.similarTo(bundle));
Cluste... |
public static String[] parseUri(String uri) {
return doParseUri(uri, false);
} | @Test
public void testParseUriSlashAndQuery() {
String[] out1 = CamelURIParser.parseUri("file:/absolute?recursive=true");
assertEquals("file", out1[0]);
assertEquals("/absolute", out1[1]);
assertEquals("recursive=true", out1[2]);
String[] out2 = CamelURIParser.parseUri("file... |
public Map<String, Integer> getNotAnalysedFilesByLanguage() {
return ImmutableMap.copyOf(notAnalysedFilesByLanguage);
} | @Test
public void stores_not_analysed_c_file_count_in_sq_community_edition() {
when(sonarRuntime.getEdition()).thenReturn(SonarEdition.COMMUNITY);
InputComponentStoreTester underTest = new InputComponentStoreTester(sonarRuntime);
String mod1Key = "mod1";
underTest.addFile(mod1Key, "src/main/java/Foo.j... |
public boolean after(DateTimeStamp other) {
return compareTo(other) > 0;
} | @Test
void malformedDateTimeStampThrowsException() {
final DateTimeStamp onlyDate = new DateTimeStamp("2021-09-01T11:12:13.111-0100");
final DateTimeStamp onlyTime = new DateTimeStamp(1.0D);
assertThrows(IllegalStateException.class, () -> onlyDate.after(onlyTime));
} |
public static Object mapToObject(Map<String, String> map, Class<?> clazz) {
if (CollectionUtils.isEmpty(map)) {
return null;
}
try {
Object instance = clazz.newInstance();
Field[] fields = instance.getClass().getDeclaredFields();
for (Field field :... | @Test
public void testMapToObject() {
// null map
BranchDO branchDO =
(BranchDO) BeanUtils.mapToObject(null, BranchDO.class);
Assertions.assertNull(branchDO);
Map<String, String> map = new HashMap<>();
Date date = new Date();
map.put("xid", "192.166.1... |
public TopicConfig setMultiThreadingEnabled(boolean multiThreadingEnabled) {
if (this.globalOrderingEnabled && multiThreadingEnabled) {
throw new IllegalArgumentException("Multi-threading can not be enabled when global ordering is used.");
}
this.multiThreadingEnabled = multiThreadin... | @Test
public void testSetMultiThreadingEnabled() {
TopicConfig topicConfig = new TopicConfig().setGlobalOrderingEnabled(false);
topicConfig.setMultiThreadingEnabled(true);
assertTrue(topicConfig.isMultiThreadingEnabled());
try {
topicConfig.setGlobalOrderingEnabled(true);... |
public static ChronoZonedDateTimeByInstantComparator getInstance() {
return INSTANCE;
} | @Test
void should_have_one_instance() {
assertThat(comparator).isSameAs(ChronoZonedDateTimeByInstantComparator.getInstance());
} |
public static List<FieldSchema> convert(Schema schema) {
return schema.columns().stream()
.map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc()))
.collect(Collectors.toList());
} | @Test
public void testNotSupportedTypes() {
for (FieldSchema notSupportedField : getNotSupportedFieldSchemas()) {
assertThatThrownBy(
() -> HiveSchemaUtil.convert(
Lists.newArrayList(Collections.singletonList(notSupportedField))))
.isInstanceOf(IllegalArgumentException.clas... |
public void instanceDeregistered(String serviceName, String groupName) {
String key = NamingUtils.getGroupedName(serviceName, groupName);
synchronized (registeredInstances) {
InstanceRedoData redoData = registeredInstances.get(key);
if (null != redoData) {
redoDat... | @Test
void testInstanceDeregistered() {
ConcurrentMap<String, InstanceRedoData> registeredInstances = getInstanceRedoDataMap();
redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance());
redoService.instanceDeregistered(SERVICE, GROUP);
InstanceRedoData actual = registeredInst... |
@Override
public boolean validate(Path path, ResourceContext context) {
// explicitly call a method not depending on LinkResourceService
return validate(path);
} | @Test
public void testMoreThanLatency() {
sut = new LatencyConstraint(Duration.of(3, ChronoUnit.NANOS));
assertThat(sut.validate(path, resourceContext), is(false));
} |
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
Map<String, String> mdcContextMap = getMdcContextMap();
return super.schedule(ContextPropagator.decorateRunnable(contextPropagators, () -> {
try {
setMDCContext(mdcContextM... | @Test
public void testScheduleRunnableWithDelayPropagatesContext() {
TestThreadLocalContextHolder.put("ValueShouldCrossThreadBoundary");
final ScheduledFuture<?> schedule = schedulerService.schedule(() -> {
TestThreadLocalContextHolder.get().orElseThrow(() -> new RuntimeException("Found ... |
protected <G> G doGet(String token, HttpUrl url, Function<String, G> handler) {
Request request = prepareRequestWithBearerToken(token, GET, url, null);
return doCall(request, handler);
} | @Test
public void validate_handler_call_on_empty_body() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody(""));
assertThat(underTest.doGet("token", server.url("/"), Function.identity()))
.isEmpty();
} |
public void onPeriodicEmit() {
updateCombinedWatermark();
} | @Test
void singleDeferredWatermark() {
TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput();
WatermarkOutputMultiplexer multiplexer =
new WatermarkOutputMultiplexer(underlyingWatermarkOutput);
WatermarkOutput watermarkOutput = createDeferredOutpu... |
public static Finder expandedFinder(String... queries) {
var finder = identSum();
for (String query : queries) {
finder = finder.or(Finder.contains(query));
}
return finder;
} | @Test
void expandedFinderTest() {
var res = expandedFinder("It was", "kingdom").find(text());
assertEquals(3, res.size());
assertEquals("It was many and many a year ago,", res.get(0));
assertEquals("In a kingdom by the sea,", res.get(1));
assertEquals("In this kingdom by the sea;", res.get(2));
... |
@Override
protected FlumeConfiguration getFlumeConfiguration() {
return flumeConfiguration;
} | @Test
public void testPolling() throws Exception {
es.awaitEvent();
es.reset();
FlumeConfiguration fc = cp.getFlumeConfiguration();
Assert.assertTrue(fc.getConfigurationErrors().isEmpty());
AgentConfiguration ac = fc.getConfigurationFor(AGENT_NAME);
Assert.assertNull... |
@Override
public long lastHeartbeat() {
return lastHeartbeatMillis;
} | @Test
public void lastHeartbeat_whenNoHeartbeat() {
long lastHeartbeat = failureDetector.lastHeartbeat();
assertEquals(PhiAccrualFailureDetector.NO_HEARTBEAT_TIMESTAMP, lastHeartbeat);
} |
public static void addTotalSstFilesSizeMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
streamsMetri... | @Test
public void shouldAddTotalSstFilesSizeMetric() {
final String name = "total-sst-files-size";
final String description = "Total size in bytes of all SST files";
runAndVerifyMutableMetric(
name,
description,
() -> RocksDBMetrics.addTotalSstFilesSizeMet... |
@Override
public void addToQueue(Runnable r) {
r.run();
} | @Test
public void addToQueue_executes_Runnable_synchronously() {
Set<String> s = new HashSet<>();
underTest.addToQueue(() -> s.add("done"));
assertThat(s).containsOnly("done");
} |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyWithOneNonIterableDoesNotGiveWarning() {
expectFailureWhenTestingThat(asList(1, 2, 3, 4)).containsExactly(1);
assertFailureValue("unexpected (3)", "2, 3, 4");
} |
public static int fromLogical(Schema schema, java.util.Date value) {
if (!(LOGICAL_NAME.equals(schema.name())))
throw new DataException("Requested conversion of Date object but the schema does not match.");
Calendar calendar = Calendar.getInstance(UTC);
calendar.setTime(value);
... | @Test
public void testFromLogicalInvalidHasTimeComponents() {
assertThrows(DataException.class,
() -> Date.fromLogical(Date.SCHEMA, EPOCH_PLUS_TIME_COMPONENT.getTime()));
} |
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
String accessLogKey = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY);
boolean isFixedPath = invoker.getUrl().getParameter(ACCESS_LOG_FIXED_PATH_KEY, true);
if (StringUtils.isEmpty(accessLogKey) ... | @Test
@SuppressWarnings("unchecked")
public void testDefault() throws NoSuchFieldException, IllegalAccessException {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1");
Invoker<AccessLogFilterTest> invoker = new MyInvoker<AccessLogFilterTest>(url);
Invoca... |
public void setColumn(int index, SGDVector vector) {
if (index < 0 || index > dim2) {
throw new IllegalArgumentException("Invalid column index, must be [0,"+dim2+"), received " + index);
}
if (vector.size() == dim1) {
if (vector instanceof DenseVector) {
f... | @Test
public void setColumnTest() {
//create a 2x3 matrix
DenseMatrix a = new DenseMatrix(new double[][] {new double[] {1.0, 2.0, 3.0}, new double[] {4.0, 5.0, 6.0}});
assertEquals(2, a.getDimension1Size());
assertEquals(3, a.getDimension2Size());
a.setColumn(2, new DenseVect... |
@Override
public void route(final RouteContext routeContext, final SingleRule singleRule) {
for (String each : singleRule.getDataSourceNames()) {
routeContext.getRouteUnits().add(new RouteUnit(new RouteMapper(each, each), Collections.emptyList()));
}
} | @Test
void assertRoute() throws SQLException {
SingleRule singleRule = new SingleRule(new SingleRuleConfiguration(), DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), createDataSourceMap(), Collections.emptyList());
RouteContext routeContext = new RouteContext();
SingleDatabaseBroadcastRoute... |
@Override
@SuppressWarnings("unchecked")
public int run() throws IOException {
Preconditions.checkArgument(
input != null && output != null, "Both input and output parquet file paths are required.");
Preconditions.checkArgument(codec != null, "The codec cannot be null");
Path inPath = new Path... | @Test
public void testTransCompressionCommand_ZSTD() throws IOException {
TransCompressionCommand command = new TransCompressionCommand(createLogger());
command.input = parquetFile().getAbsolutePath();
File output = new File(getTempFolder(), getClass().getSimpleName() + ".converted-1.ZSTD.parquet");
... |
public static DateTime parseDate(CharSequence dateString) {
dateString = normalize(dateString);
return parse(dateString, DatePattern.NORM_DATE_FORMAT);
} | @Test
public void parseDateTest() {
final String dateStr = "2018-4-10";
final Date date = DateUtil.parseDate(dateStr);
final String format = DateUtil.format(date, DatePattern.NORM_DATE_PATTERN);
assertEquals("2018-04-10", format);
} |
public static Date parseHttpDate(CharSequence txt) {
return parseHttpDate(txt, 0, txt.length());
} | @Test
public void testParseMidnight() {
assertEquals(new Date(784080000000L), parseHttpDate("Sunday, 06 Nov 1994 00:00:00 GMT"));
} |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \... | @Test
void testInvokeOverriddenMethodBySelect() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY).set(null);
... |
@NonNull
public String processShownotes() {
String shownotes = rawShownotes;
if (TextUtils.isEmpty(shownotes)) {
Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message");
shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShowno... | @Test
public void testProcessShownotesAndInvalidTimecode() {
final String[] timeStrs = new String[] {"2:1", "0:0", "000", "00", "00:000"};
StringBuilder shownotes = new StringBuilder("<p> Some test text with timecodes ");
for (String timeStr : timeStrs) {
shownotes.append(timeS... |
@Override
Function<Request.Builder, Request.Builder> addVerbToBuilder() {
return Request.Builder::get;
} | @Test
public void addVerbToBuilder_shouldReturnNonNullResult() {
assertThat(getRequest.addVerbToBuilder()).isNotNull();
} |
@PUT
@Path("{id}")
@ApiOperation("Update view")
@AuditEvent(type = ViewsAuditEventTypes.VIEW_UPDATE)
public ViewDTO update(@ApiParam(name = "id") @PathParam("id") @NotEmpty String id,
@ApiParam @Valid ViewDTO dto,
@Context SearchUser searchUser) {
... | @Test
public void updatesDashboardSuccessfullyIfInvisibleFilterWasPresentBefore() {
final ViewService viewService = mockViewService(TEST_DASHBOARD_VIEW);
final var dto = ViewDTO.builder().searchId("1").title("2").state(new HashMap<>()).build();
when(viewService.update(any())).thenReturn(dto)... |
@Override
public long getTimeout() {
return timeoutMills;
} | @Test
void testAbstractPushCallBack() {
AbstractRequestCallBack callBack = new AbstractRequestCallBack() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void onResponse(Response response) {
... |
@ProtoFactory
public static MediaType fromString(String tree) {
if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(tree);
return parseSingleMediaType(tree, matcher, false);
} | @Test(expected = EncodingException.class)
public void testUnQuotedParamWithSpaces() {
MediaType mediaType = MediaType.fromString("application/json ; charset= UTF-8");
} |
public static DataType getDataTypeFromColumn(EtlJobConfig.EtlColumn column, boolean regardDistinctColumnAsBinary) {
DataType dataType = DataTypes.StringType;
switch (column.columnType) {
case "BOOLEAN":
dataType = DataTypes.StringType;
break;
case ... | @Test
public void testGetDataTypeFromColumn() {
DppUtils dppUtils = new DppUtils();
try {
EtlJobConfig.EtlColumn column = new EtlJobConfig.EtlColumn();
column.columnType = "VARCHAR";
DataType stringResult = dppUtils.getDataTypeFromColumn(column, false);
... |
@Udf(description = "Converts a string representation of a time in the given format"
+ " into the TIME value.")
public Time parseTime(
@UdfParameter(
description = "The string representation of a time.") final String formattedTime,
@UdfParameter(
description = "The format pattern ... | @Test
public void shouldBeThreadSafeAndWorkWithManyDifferentFormatters() {
IntStream.range(0, 10_000)
.parallel()
.forEach(idx -> {
try {
final String sourceDate = "000105X" + idx;
final String pattern = "HHmmss'X" + idx + "'";
final Time result = udf.... |
@PUT
@Path("/{connector}/topics/reset")
@Operation(summary = "Reset the list of topics actively used by the specified connector")
public Response resetConnectorActiveTopics(final @PathParam("connector") String connector, final @Context HttpHeaders headers) {
if (isTopicTrackingDisabled) {
... | @Test
public void testResetConnectorActiveTopics() {
HttpHeaders headers = mock(HttpHeaders.class);
connectorsResource = new ConnectorsResource(herder, serverConfig, restClient, REQUEST_TIMEOUT);
Response response = connectorsResource.resetConnectorActiveTopics(CONNECTOR_NAME, headers);
... |
@VisibleForTesting
public Path getAllocationFile(Configuration conf)
throws UnsupportedFileSystemException {
String allocFilePath = conf.get(FairSchedulerConfiguration.ALLOCATION_FILE,
FairSchedulerConfiguration.DEFAULT_ALLOCATION_FILE);
Path allocPath = new Path(allocFilePath);
String alloc... | @Test
public void testGetAllocationFileFromFileSystem()
throws IOException, URISyntaxException {
File baseDir =
new File(TEST_DIR + Path.SEPARATOR + "getAllocHDFS").getAbsoluteFile();
FileUtil.fullyDelete(baseDir);
conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
... |
@Override
public int read() throws IOException {
final int tmp = read(z);
return tmp == -1 ? -1 : (0xFF & z[0]);
} | @Test
public void testRepeat() throws Exception {
final Configuration conf = new Configuration();
Arrays.fill(loc, "");
Arrays.fill(start, 0L);
Arrays.fill(len, BLOCK);
final ByteArrayOutputStream out = fillVerif();
final FileQueue q =
new FileQueue(new CombineFileSplit(paths, start, le... |
public void writeTokens(Object... tokens) throws IOException
{
for (Object token : tokens)
{
writeObject(token);
}
output.write("\n".getBytes(StandardCharsets.US_ASCII));
} | @Test
void testPDFBox4750() throws IOException
{
String filename = "PDFBOX-4750.pdf";
File file = new File("target/pdfs", filename);
try (PDDocument doc = Loader.loadPDF(file))
{
PDFRenderer r = new PDFRenderer(doc);
for (int i = 0; i < doc.getNumberOfPage... |
public static String getTimestamp() throws IOException {
return loadProperties().getProperty(TIMESTAMP);
} | @Test
public void testGetTimestamp() throws IOException {
assertEquals(getTimestamp(), ("2017-01-31 01:21:09.843 UTC"));
} |
void restoreBatch(final Collection<ConsumerRecord<byte[], byte[]>> records) {
// compute the observed stream time at the end of the restore batch, in order to speed up
// restore by not bothering to read from/write to segments which will have expired by the
// time the restoration process is co... | @Test
public void shouldRestoreMultipleBatches() {
final List<DataRecord> records = new ArrayList<>();
records.add(new DataRecord("k", null, SEGMENT_INTERVAL - 20));
records.add(new DataRecord("k", "vn10", SEGMENT_INTERVAL - 10));
records.add(new DataRecord("k", null, SEGMENT_INTERVA... |
@ScalarOperator(CAST)
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice castToVarchar(@SqlType(StandardTypes.REAL) long value)
{
return utf8Slice(String.valueOf(intBitsToFloat((int) value)));
} | @Test
public void testCastToVarchar()
{
assertFunction("CAST(REAL'754.1985' as VARCHAR)", VARCHAR, "754.1985");
assertFunction("CAST(REAL'-754.2008' as VARCHAR)", VARCHAR, "-754.2008");
assertFunction("CAST(REAL'Infinity' as VARCHAR)", VARCHAR, "Infinity");
assertFunction("CAST(R... |
@Override
public ValidationTaskResult validateImpl(Map<String, String> optionsMap) {
if (!ValidationUtils.isHdfsScheme(mPath)) {
mMsg.append(String.format(
"UFS path %s is not HDFS. Skipping validation for HDFS properties.%n", mPath));
return new ValidationTaskResult(ValidationUtils.Stat... | @Test
public void inconsistentConf() {
String hdfsSite = Paths.get(sTestDir.toPath().toString(), "hdfs-site.xml").toString();
ValidationTestUtils.writeXML(hdfsSite, ImmutableMap.of("key1", "value2"));
String coreSite = Paths.get(sTestDir.toPath().toString(), "core-site.xml").toString();
ValidationTes... |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testRunReturnDifferentRequestId() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
Dataflow mockDataflowClient = options.getDataflowClient();
Dataflow.Projects.Locations.Jobs.Create mockRequest =
mock(Dataflow.Projects.Locations.Jobs.Create.class);
... |
@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" )... | @Test
public void testGetLegacyColumnNameNoAliasText() throws Exception {
assertEquals( "NoAliasText", new MariaDBDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), getResultSetMetaData(), 6 ) );
} |
public String stringify(boolean value) {
throw new UnsupportedOperationException(
"stringify(boolean) was called on a non-boolean stringifier: " + toString());
} | @Test
public void testDateStringifier() {
PrimitiveStringifier stringifier = DATE_STRINGIFIER;
assertEquals("1970-01-01", stringifier.stringify(0));
Calendar cal = Calendar.getInstance(UTC);
cal.clear();
cal.set(2017, Calendar.DECEMBER, 14);
assertEquals("2017-12-14", stringifier.stringify((... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void integerLiteral() {
String inputExpression = "10";
BaseNode number = parse( inputExpression );
assertThat( number).isInstanceOf(NumberNode.class);
assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertLocation( inputExpression, number );
} |
@CanDistro
@DeleteMapping("/metadata/batch")
@TpsControl(pointName = "NamingInstanceMetadataUpdate", name = "HttpNamingInstanceMetadataBatchUpdate")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceMetadataBatchHttpParamExtractor.class)
public ObjectNode... | @Test
void testBatchDeleteInstanceMetadata() throws Exception {
mockRequestParameter("metadata", "{}");
when(instanceServiceV2.batchDeleteMetadata(eq(Constants.DEFAULT_NAMESPACE_ID), any(), anyMap())).thenReturn(
Collections.singletonList("1.1.1.1:3306:unknown:DEFAULT:ephemeral"));
... |
public RecordAppendResult append(String topic,
int partition,
long timestamp,
byte[] key,
byte[] value,
Header[] headers,
... | @Test
public void testIdempotenceWithOldMagic() {
// Simulate talking to an older broker, ie. one which supports a lower magic.
ApiVersions apiVersions = new ApiVersions();
int batchSize = 1025;
int deliveryTimeoutMs = 3200;
int lingerMs = 10;
long retryBackoffMs = 10... |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testSeekWithInFlightReset() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST);
// Send the ListOffsets request to reset the position
offsetFetcher.resetPositionsIfNeeded();
consumerCl... |
public static PemAuthIdentity clusterOperator(Secret secret) {
return new PemAuthIdentity(secret, "cluster-operator");
} | @Test
public void testSecretWithMissingCertChainThrowsException() {
Secret secretWithMissingClusterOperatorKey = new SecretBuilder()
.withNewMetadata()
.withName(KafkaResources.clusterOperatorCertsSecretName(CLUSTER))
.withNamespace(NAMESPACE)
... |
public Connection findAllowedConnection(String entityId) {
return connectionRepository.findAllowedByEntityId(entityId);
} | @Test
void findAllowedConnection() {
when(connectionRepositoryMock.findAllowedByEntityId(anyString())).thenReturn(new Connection());
Connection result = connectionServiceMock.findAllowedConnection("entityId");
verify(connectionRepositoryMock, times(1)).findAllowedByEntityId(anyString());
... |
public static String format(double amount, boolean isUseTraditional) {
return format(amount, isUseTraditional, false);
} | @Test
public void formatTest() {
String f0 = NumberChineseFormatter.format(5000_8000, false);
assertEquals("五千万零八千", f0);
String f1 = NumberChineseFormatter.format(1_0889.72356, false);
assertEquals("一万零八百八十九点七二", f1);
f1 = NumberChineseFormatter.format(12653, false);
assertEquals("一万二千六百五十三", f1);
f1 = ... |
@Override
public int readUnsignedShort() throws EOFException {
return readShort() & 0xffff;
} | @Test
public void testReadUnsignedShort() throws Exception {
byte[] bytes1 = {0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, -1, -1};
in.init(bytes1, bytes1.length - 4);
int unsigned = in.readUnsignedShort();
assertEquals(0xFFFF, unsigned);
} |
public CaseInsensitiveString getAncestorName() {
if (cachedAncestorName == null) {
String stringPath = path();
if (stringPath == null) {
return null;
}
int index = stringPath.indexOf(DELIMITER);
cachedAncestorName = index == -1 ? path :... | @Test
public void shouldUnderstandAncestorName() {
PathFromAncestor path = new PathFromAncestor(new CaseInsensitiveString("grand-parent/parent/child"));
assertThat(path.getAncestorName(), is(new CaseInsensitiveString("grand-parent")));
} |
public String toXmlPartial(Object domainObject) {
bombIf(!isAnnotationPresent(domainObject.getClass(), ConfigTag.class), () -> "Object " + domainObject + " does not have a ConfigTag");
Element element = elementFor(domainObject.getClass());
write(domainObject, element, configCache, registry);
... | @Test
public void shouldNotSaveUserNameAndPasswordWhenBothAreEmpty() {
MailHost mailHost = new MailHost("hostname", 24, "", "", null, true, false, "from@te.com", "to@te.com", new GoCipher());
mailHost.ensureEncrypted();
String s = xmlWriter.toXmlPartial(mailHost);
assertThat(s, is(
... |
@Override
public String getName() {
return _name;
} | @Test
public void testStringSplitTransformFunction() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("split(%s, 'ab')", STRING_ALPHANUM_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
assertTrue(transform... |
@Override
public int actionStop(String appName) throws IOException, YarnException {
int result = EXIT_SUCCESS;
try {
Service service = new Service();
service.setName(appName);
service.setState(ServiceState.STOPPED);
String buffer = jsonSerDeser.toJson(service);
ClientResponse res... | @Test
void testBadStop() {
String appName = "unknown_app";
try {
int result = badAsc.actionStop(appName);
assertEquals(EXIT_EXCEPTION_THROWN, result);
} catch (IOException | YarnException e) {
fail();
}
} |
public void revokePublisherAgreement(UserData user, UserData admin) {
checkApiUrl();
checkEclipseData(user);
var eclipseToken = admin == null ? checkEclipseToken(user) : checkEclipseToken(admin);
var headers = new HttpHeaders();
headers.setBearerAuth(eclipseToken.accessToken);
... | @Test
public void testRevokePublisherAgreement() {
var user = mockUser();
user.setEclipsePersonId("test");
eclipse.revokePublisherAgreement(user, null);
} |
@Override
public String getDataSource() {
return DataSourceConstant.DERBY;
} | @Test
void testGetDataSource() {
String dataSource = groupCapacityMapperByDerby.getDataSource();
assertEquals(DataSourceConstant.DERBY, dataSource);
} |
public static ClientDetailsEntity parse(String jsonString) {
JsonElement jsonEl = parser.parse(jsonString);
return parse(jsonEl);
} | @Test
public void testParse() {
String json = " {\n" +
" \"application_type\": \"web\",\n" +
" \"redirect_uris\":\n" +
" [\"https://client.example.org/callback\",\n" +
" \"https://client.example.org/callback2\"],\n" +
" \"client_name\": \"My Example\",\n" +
" \"client_name#j... |
static String getPIDFromOS() {
String pid;
// following is not always reliable as is (for example, see issue 3 on solaris 10
// or http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html)
// Author: Santhosh Kumar T, https://github.com/santhosh-tekuri/jlibs, licence LGPL
// Author getpids... | @Test
public void testGetPIDFromOS() {
assertNotNull("getPIDFromOS", PID.getPIDFromOS());
} |
@Override
public Set<DeviceId> getDevicesOf(NodeId nodeId) {
checkPermission(CLUSTER_READ);
checkNotNull(nodeId, NODE_ID_NULL);
return store.getDevices(nodeId);
} | @Test
public void getDevicesOf() {
mgr.setRole(NID_LOCAL, DEV_MASTER, MASTER);
mgr.setRole(NID_LOCAL, DEV_OTHER, STANDBY);
assertEquals("should be one device:", 1, mgr.getDevicesOf(NID_LOCAL).size());
//hand both devices to NID_LOCAL
mgr.setRole(NID_LOCAL, DEV_OTHER, MASTER);... |
protected static SimpleDateFormat getLog4j2Appender() {
Optional<Appender> log4j2xmlAppender =
configuration.getAppenders().values().stream()
.filter( a -> a.getName().equalsIgnoreCase( log4J2Appender ) ).findFirst();
if ( log4j2xmlAppender.isPresent() ) {
ArrayList<String> matchesArray = ne... | @Test
public void testGetLog4j2UsingAppender6() {
// Testing dd/MMM/yyyy HH:mm:ss,SSS pattern
KettleLogLayout.log4J2Appender = "pdi-execution-appender-test-6";
Assert.assertEquals( "dd/MMM/yyyy HH:mm:ss,SSS",
KettleLogLayout.getLog4j2Appender().toPattern() );
} |
public void submitLoggingTask(Collection<Member> connectedMembers, Collection<Member> allMembers) {
if (delayPeriodSeconds <= 0) {
return;
}
if ((submittedLoggingTask != null && !submittedLoggingTask.isDone())) {
submittedLoggingTask.cancel(true);
}
subm... | @Test
void assertLogMessageIsCorrect() {
List<Member> mockMembers = createMockMembers(2);
HazelcastProperties hzProps = createMockProperties(1);
ClientConnectivityLogger clientConnectivityLogger = new ClientConnectivityLogger(loggingService, executor, hzProps);
clientConnectivityLog... |
public void upgradeApp(Service service) throws IOException,
SolrServerException {
Collection<SolrInputDocument> docs = new HashSet<SolrInputDocument>();
SolrClient solr = getSolrClient();
if (service!=null) {
String name = service.getName();
String app = "";
SolrQuery query = new Sol... | @Test
void testUpgradeApp() throws Exception {
Application example = new Application();
String expected = "2.0";
String actual = "";
example.setOrganization("jenkins-ci.org");
example.setVersion("1.0");
example.setName("jenkins");
example.setDescription("World leading open source automatio... |
@Override
public ObjectNode encode(LispAsAddress address, CodecContext context) {
checkNotNull(address, "LispAsAddress cannot be null");
final ObjectNode result = context.mapper().createObjectNode()
.put(AS_NUMBER, address.getAsNumber());
if (address.get... | @Test
public void testLispAsAddressEncode() {
LispAsAddress address = new LispAsAddress.Builder()
.withAsNumber(AS_NUMBER)
.withAddress(MappingAddresses.ipv4MappingAddress(IPV4_PREFIX))
.build();
ObjectNode addressJson = asAddressCodec.encode(address, ... |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt adminExt = new DefaultMQAdminExt(rpcHook);
adminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String topic = commandLine... | @Test
public void testExecute() {
DeleteTopicSubCommand cmd = new DeleteTopicSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test", "-c default-cluster"};
final CommandLine commandLine =
ServerUt... |
public final void topoSort(final CaseInsensitiveString root, final PipelineDependencyState pipelineDependencyState) throws Exception {
Hashtable<CaseInsensitiveString, CycleState> state = new Hashtable<>();
Stack<CaseInsensitiveString> visiting = new Stack<>();
if (!state.containsKey(root)) {
... | @Test
public void shouldThrowExceptionWhenCycleDependencyFound() {
when(state.getDependencyMaterials(new CaseInsensitiveString("a"))).thenReturn(new Node(new Node.DependencyNode(new CaseInsensitiveString("b"), new CaseInsensitiveString("stage"))));
when(state.getDependencyMaterials(new CaseInsensiti... |
public ProducerAppendInfo prepareUpdate(long producerId, AppendOrigin origin) {
ProducerStateEntry currentEntry = lastEntry(producerId).orElse(ProducerStateEntry.empty(producerId));
return new ProducerAppendInfo(topicPartition, producerId, currentEntry, origin, verificationStateEntry(producerId));
} | @Test
public void updateProducerTransactionState() {
int coordinatorEpoch = 15;
long offset = 9L;
appendClientEntry(stateManager, producerId, epoch, defaultSequence, offset, false);
ProducerAppendInfo appendInfo = stateManager.prepareUpdate(producerId, AppendOrigin.CLIENT);
... |
@Override
public void process(Exchange exchange) throws Exception {
JsonElement json = getBodyAsJsonElement(exchange);
String operation = exchange.getIn().getHeader(CouchDbConstants.HEADER_METHOD, String.class);
if (ObjectHelper.isEmpty(operation)) {
Response<DocumentResult> save... | @Test
void testDocumentHeadersAreSet() throws Exception {
String id = UUID.randomUUID().toString();
String rev = UUID.randomUUID().toString();
Document doc = new Document.Builder()
.add("_rev", rev)
.id(id)
.build();
DocumentResult do... |
public static Builder newChangesetBuilder() {
return new Builder();
} | @Test
public void fail_with_NPE_when_building_without_date() {
assertThatThrownBy(() -> {
Changeset.newChangesetBuilder()
.setAuthor("john")
.setRevision("rev-1")
.build();
})
.isInstanceOf(NullPointerException.class)
.hasMessage("Date cannot be null");
} |
@SuppressWarnings("unchecked")
private void publishContainerKilledEvent(
ContainerEvent event) {
if (publishNMContainerEvents) {
ContainerKillEvent killEvent = (ContainerKillEvent) event;
ContainerId containerId = killEvent.getContainerID();
ContainerEntity entity = createContainerEntity(c... | @Test
public void testPublishContainerKilledEvent() {
ApplicationId appId = ApplicationId.newInstance(0, 1);
ApplicationAttemptId appAttemptId =
ApplicationAttemptId.newInstance(appId, 1);
ContainerId cId = ContainerId.newContainerId(appAttemptId, 1);
ContainerEvent containerEvent =
n... |
public MutableRecordBatch nextBatch() {
int remaining = buffer.remaining();
Integer batchSize = nextBatchSize();
if (batchSize == null || remaining < batchSize)
return null;
byte magic = buffer.get(buffer.position() + MAGIC_OFFSET);
ByteBuffer batchSlice = buffer.s... | @Test
public void iteratorRaisesOnTooLargeRecords() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, Compression.NONE, TimestampType.CREATE_TIME, 0L);
builder.append(15L, "a".getBytes(), "1".getBytes());
builder.close();
... |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void fail_if_date_is_not_formatted_correctly() {
assertThatThrownBy(() -> underTest.create(new SearchRequest()
.setCreatedAfter("unknown-date")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'unknown-date' cannot be parsed as either a date or date+time");
} |
@Override
public TreeEntry<K, V> get(Object key) {
return nodes.get(key);
} | @Test
public void putTest() {
final ForestMap<String, String> map = new LinkedForestMap<>(false);
TreeEntry<String, String> treeEntry = new LinkedForestMap.TreeEntryNode<>(null, "a", "aaa");
assertNull(map.put("a", treeEntry));
assertNotEquals(map.get("a"), treeEntry);
assertEquals(map.get("a").getKey(), tr... |
public static String resolveMainClass(
@Nullable String configuredMainClass, ProjectProperties projectProperties)
throws MainClassInferenceException, IOException {
if (configuredMainClass != null) {
if (isValidJavaClass(configuredMainClass)) {
return configuredMainClass;
}
thro... | @Test
public void testResolveMainClass_noneInferredWithInvalidMainClassFromJarPlugin()
throws IOException {
Mockito.when(mockProjectProperties.getMainClassFromJarPlugin()).thenReturn("${start-class}");
Mockito.when(mockProjectProperties.getClassFiles())
.thenReturn(ImmutableList.of(Paths.get("ig... |
public static String serializeRecordToJsonExpandingValue(ObjectMapper mapper, Record<GenericObject> record,
boolean flatten)
throws JsonProcessingException {
JsonRecord jsonRecord = new JsonRecord();
GenericObject value = record.ge... | @Test
public void testPrimitiveSerializeRecordToJsonExpandingValue() throws Exception {
GenericObject genericObject = new GenericObject() {
@Override
public SchemaType getSchemaType() {
return SchemaType.STRING;
}
@Override
public ... |
public KafkaClientSupplier getKafkaClientSupplier() {
return getConfiguredInstance(StreamsConfig.DEFAULT_CLIENT_SUPPLIER_CONFIG,
KafkaClientSupplier.class);
} | @Test
public void shouldReturnDefaultClientSupplier() {
final KafkaClientSupplier supplier = streamsConfig.getKafkaClientSupplier();
assertInstanceOf(DefaultKafkaClientSupplier.class, supplier);
} |
public Request setExtras(Map<String, Object> extras) {
this.extras.putAll(extras);
return this;
} | @Test
public void testSetExtras() {
Request request = new Request();
Map<String, Object> extras = Collections.singletonMap("a", "1");
request.setExtras(extras);
request.putExtra("b", "2");
assertThat(request.<String>getExtra("a")).isEqualTo("1");
assertThat(request.<S... |
@Override
public Optional<P> authenticate(C credentials) throws AuthenticationException {
try (Timer.Context context = gets.time()) {
return cache.get(credentials);
} catch (CompletionException e) {
final Throwable cause = e.getCause();
if (cause instanceof Invali... | @Test
void shouldPropagateRuntimeException() throws AuthenticationException {
final RuntimeException e = new NullPointerException();
when(underlying.authenticate(anyString())).thenThrow(e);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> cached.authentica... |
@Override
public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
final Path copy = proxy.copy(source, renamed, status, connectionCallback, new DisabledStreamListener());
... | @Test
public void testMoveWithDelimiter() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path placeholder = new Path(container, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.directory));
final ... |
public static MetricName name(Class<?> klass, String... names) {
return name(klass.getName(), names);
} | @Test
public void concatenatesStringsToFormADottedName() throws Exception {
assertThat(name("one", "two", "three"))
.isEqualTo(MetricName.build("one.two.three"));
} |
void submitConsumeRequest(ConsumeRequest consumeRequest) {
try {
consumeRequestCache.put(consumeRequest);
} catch (InterruptedException ignore) {
}
} | @Test
public void testSubmitConsumeRequest() throws Exception {
byte[] body = new byte[] {'1', '2', '3'};
MessageExt consumedMsg = new MessageExt();
consumedMsg.setMsgId("NewMsgId");
consumedMsg.setBody(body);
consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "... |
@Override
public AppResponse process(Flow flow, AppRequest body) {
digidClient.remoteLog("1218", getAppDetails());
if (!appSession.getWithBsn()) {
digidClient.remoteLog("1345", Map.of(lowerUnderscore(ACCOUNT_ID), appSession.getAccountId()));
return new NokResponse("no_bsn_on... | @Test
void processWithBsn(){
mockedAppSession.setWithBsn(true);
AppResponse appResponse = rdaChosen.process(mockedFlow, mockedAbstractAppRequest);
verify(digidClientMock, times(1)).remoteLog("1218", Map.of(lowerUnderscore(ACCOUNT_ID), mockedAppSession.getAccountId(), lowerUnderscore(APP_CO... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.