focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@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 shouldThrowOnEmptyString() {
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> udf.stringToDate("", "yyyy-MM-dd")
);
// Then:
assertThat(e.getMessage(), containsString("Failed to parse date '' with formatter 'yyyy-MM-dd'"));
} |
@Override
public boolean isSimilar(PiMeterCellConfig onosMeter, PiMeterCellConfig deviceMeter) {
final PiMeterBand onosCommittedBand = onosMeter.committedBand();
final PiMeterBand onosPeakBand = onosMeter.peakBand();
final PiMeterBand deviceCommittedBand = deviceMeter.committedBand();
... | @Test
public void testWrongIsRateSimilar() {
PiMeterBand onosMeterBand;
PiMeterBand deviceMeterBand;
PiMeterCellConfig onosMeter;
PiMeterCellConfig deviceMeter;
for (Map.Entry<Long, Long> entry : WRONG_RATES.entrySet()) {
onosMeterBand = new PiMeterBand(PiMeterBan... |
public void retrieveDocuments() throws DocumentRetrieverException {
boolean first = true;
String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster);
MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route);
doc... | @Test
void testDocumentNotFound() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPrintIdsOnly(true)
.build();
when(mockedSession.syncSend(any())).thenReturn(new GetDocumentRep... |
@Override
public void delete(DataAdapterDto nativeEntity) {
dataAdapterService.deleteAndPostEventImmutable(nativeEntity.id());
} | @Test
@MongoDBFixtures("LookupDataAdapterFacadeTest.json")
public void delete() {
final Optional<DataAdapterDto> dataAdapterDto = dataAdapterService.get("5adf24a04b900a0fdb4e52c8");
assertThat(dataAdapterService.findAll()).hasSize(1);
dataAdapterDto.ifPresent(facade::delete);
a... |
public static String randomStringWithoutStr(final int length, final String elemData) {
String baseStr = BASE_CHAR_NUMBER;
baseStr = StrUtil.removeAll(baseStr, elemData.toCharArray());
return randomString(baseStr, length);
} | @Test
@Disabled
public void randomStringWithoutStrTest() {
for (int i = 0; i < 100; i++) {
final String s = RandomUtil.randomStringWithoutStr(8, "0IPOL");
System.out.println(s);
for (char c : "0IPOL".toCharArray()) {
assertFalse(s.contains((String.valueOf(c).toLowerCase(Locale.ROOT))));
}
}
} |
public static TreeMap<Integer, List<BufferIndexAndChannel>>
getBuffersByConsumptionPriorityInOrder(
List<Integer> nextBufferIndexToConsume,
TreeMap<Integer, Deque<BufferIndexAndChannel>> subpartitionToAllBuffers,
int expectedSize) {
if (exp... | @Test
void testGetBuffersByConsumptionPriorityInOrder() {
final int subpartition1 = 0;
final int subpartition2 = 1;
final int progress1 = 10;
final int progress2 = 20;
TreeMap<Integer, Deque<BufferIndexAndChannel>> subpartitionBuffers = new TreeMap<>();
List<BufferI... |
public static ClassLoader getCallerClassLoader(Class<?> caller) {
return caller.getClassLoader();
} | @Test
void testGetCallerClassLoader() {
assertThat(
ClassUtils.getCallerClassLoader(ClassUtilsTest.class),
sameInstance(ClassUtilsTest.class.getClassLoader()));
} |
public CompletableFuture<Long> getMinOffsetFromFileAsync() {
int length = MessageFormatUtil.QUEUE_OFFSET_POSITION + Long.BYTES;
if (this.fileSegmentTable.isEmpty() ||
this.getCommitOffset() - this.getMinOffset() < length) {
return CompletableFuture.completedFuture(GET_OFFSET_ERRO... | @Test
public void getMinOffsetFromFileAsyncTest() {
String filePath = MessageStoreUtil.toFilePath(queue);
FlatCommitLogFile flatFile = flatFileFactory.createFlatFileForCommitLog(filePath);
// append some messages
for (int i = 6; i < 9; i++) {
ByteBuffer byteBuffer = Mess... |
protected abstract void modifyDataSourceProperties(RoutineLoadDataSourceProperties dataSourceProperties)
throws DdlException; | @Test
public void testModifyDataSourceProperties() throws Exception {
KafkaRoutineLoadJob routineLoadJob = new KafkaRoutineLoadJob();
ConnectContext connectContext = UtFrameUtils.createDefaultCtx();
//alter data source custom properties
String groupId = "group1";
String clien... |
@Override public Status unwrap() {
return status;
} | @Test void unwrap() {
assertThat(response.unwrap()).isSameAs(status);
} |
@Override
public void onThrowing(final TargetAdviceObject target, final TargetAdviceMethod method, final Object[] args, final Throwable throwable, final String pluginType) {
Span span = (Span) target.getAttachment();
span.setStatus(StatusCode.ERROR).recordException(throwable);
span.end();
... | @Test
void assertExceptionHandle() {
TargetAdviceObjectFixture adviceObjectFixture = new TargetAdviceObjectFixture();
OpenTelemetrySQLParserEngineAdvice advice = new OpenTelemetrySQLParserEngineAdvice();
advice.beforeMethod(adviceObjectFixture, null, new Object[]{SQL, true}, "OpenTelemetry")... |
public static String toHexColor(final Color color)
{
return "#" + colorToHexCode(color);
} | @Test
public void toHexColor()
{
COLOR_HEXSTRING_MAP.forEach((color, hex) ->
{
assertEquals("#" + hex, ColorUtil.toHexColor(color));
});
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Timestamped)) {
return false;
}
@SuppressWarnings("unchecked")
Timestamped<T> that = (Timestamped<T>) obj;
return Objects.equals(this.t... | @Test
public final void testEquals() {
Timestamped<String> a = new Timestamped<>("a", TS_1_1);
Timestamped<String> b = new Timestamped<>("b", TS_1_1);
assertTrue("value does not impact equality",
a.equals(b));
new EqualsTester()
.addEqualityGroup(new Timestam... |
public CompletableFuture<Void> deleteStoredData(final UUID accountUuid) {
final ExternalServiceCredentials credentials = storageServiceCredentialsGenerator.generateForUuid(accountUuid);
final HttpRequest request = HttpRequest.newBuilder()
.uri(deleteUri)
.DELETE()
.header(HttpHeaders.AU... | @Test
void deleteStoredData() {
final String username = RandomStringUtils.randomAlphabetic(16);
final String password = RandomStringUtils.randomAlphanumeric(32);
when(credentialsGenerator.generateForUuid(accountUuid)).thenReturn(
new ExternalServiceCredentials(username, password));
wireMock... |
public String create(final String secret, final String bucket, String region, final String key, final String method, final long expiry) {
if(StringUtils.isBlank(region)) {
// Only for AWS
switch(session.getSignatureVersion()) {
case AWS4HMACSHA256:
// ... | @Test
public void testCreateEuWest() throws Exception {
final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
expiry.add(Calendar.MILLISECOND, (int) TimeUnit.DAYS.toMillis(7));
final String url = new S3PresignedUrlProvider(session).create(PROPERTIES.get("s3.secret"),
... |
public static <T, R> R unaryCall(Invoker<?> invoker, MethodDescriptor methodDescriptor, T request) {
return (R) call(invoker, methodDescriptor, new Object[] {request});
} | @Test
void unaryCall() {
when(invoker.invoke(any(Invocation.class))).thenReturn(result);
Object ret = StubInvocationUtil.unaryCall(invoker, method, request);
Assertions.assertEquals(response, ret);
} |
public boolean hasConfigRepo(String configRepoId) {
return this.getConfigRepo(configRepoId) != null;
} | @Test
public void shouldReturnTrueIfContainsConfigRepoWithTheSpecifiedId() {
ConfigRepoConfig repo = ConfigRepoConfig.createConfigRepoConfig(git("http://git1"), "myplugin", "id");
repos.add(repo);
assertThat(repos.hasConfigRepo(repo.getId()), is(true));
} |
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 testBank32nhLAD() {
test(Loss.lad(), "bank32nh", Bank32nh.formula, Bank32nh.data, 0.0909);
} |
public ObjectMapper getObjectMapper() {
return mapObjectMapper;
} | @Test
public void test() {
Assertions.assertThrows(JsonMappingException.class, () -> {
String JSON =
"{'id': 124,\n" +
" 'obj':[ 'com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl',\n" +
" {\n" +
... |
@Override
// TODO(yimin) integrate this method with load() method
public void cacheData(String ufsPath, long length, long pos, boolean isAsync)
throws IOException {
List<CompletableFuture<Void>> futures = new ArrayList<>();
// TODO(yimin) To implement the sync data caching.
alluxio.grpc.FileInfo f... | @Test
public void testCacheData() throws Exception {
int numPages = 10;
long length = mPageSize * numPages;
String ufsPath = mTestFolder.newFile("test").getAbsolutePath();
byte[] buffer = BufferUtils.getIncreasingByteArray((int) length);
BufferUtils.writeBufferToFile(ufsPath, buffer);
mWorker... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final Map<String, Object> event;
try {
event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT);
} catch (IOException e) {
... | @Test
public void decodeReturnsNullIfPayloadCouldNotBeDecoded() throws Exception {
assertThat(codec.decode(new RawMessage(new byte[0]))).isNull();
} |
@Override
public KeyValueIterator<K, V> reverseAll() {
final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = new NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>>() {
@Override
public KeyValueIterator<K, V> apply(final ReadOnlyKeyValueStore<K, V> ... | @Test
public void shouldSupportReverseAllAcrossMultipleStores() {
final KeyValueStore<String, String> cache = newStoreInstance();
stubProviderTwo.addStore(storeName, cache);
stubOneUnderlying.put("a", "a");
stubOneUnderlying.put("b", "b");
stubOneUnderlying.put("z", "z");
... |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
} | @Test
public void compute_and_aggregate_duplicated_lines() {
addDuplicatedBlock(FILE_1_REF, 2);
addDuplicatedBlock(FILE_3_REF, 10);
addDuplicatedBlock(FILE_4_REF, 12);
setNewLines(FILE_1, FILE_2, FILE_3, FILE_4);
underTest.execute(new TestComputationStepContext());
assertRawMeasureValue(FILE... |
@Override
public RestLiRequestData extractRequestData(RoutingResult routingResult, DataMap data)
{
ResourceMethodDescriptor resourceMethodDescriptor = routingResult.getResourceMethod();
if (data == null)
{
data = new DataMap();
}
DynamicRecordTemplate template = new DynamicRecordTemplate(d... | @Test(dataProvider = "failureData")
public void testExtractRequestDataFailure(String entity, List<Parameter<?>> params, String errorRegEx)
throws IOException
{
RecordDataSchema dataSchema = DynamicRecordMetadata.buildSchema("testAction", params);
RestRequest request = RestLiArgumentBuilderTestHelper.g... |
public V get(final int keyPartA, final int keyPartB)
{
return unmapNullValue(getMapping(keyPartA, keyPartB));
} | @Test
void shouldReturnNullWhenNotFoundItem()
{
final int keyPartA = 3;
final int keyPartB = 7;
assertNull(map.get(keyPartA, keyPartB));
} |
public static ResourceProfile generateDefaultSlotResourceProfile(
WorkerResourceSpec workerResourceSpec, int numSlotsPerWorker) {
final ResourceProfile.Builder resourceProfileBuilder =
ResourceProfile.newBuilder()
.setCpuCores(workerResourceSpec.getCpuCores().... | @Test
void testGenerateDefaultSlotConsistentWithTaskExecutorResourceUtils() {
final int numSlots = 5;
final TaskExecutorResourceSpec taskExecutorResourceSpec =
new TaskExecutorResourceSpec(
new CPUResource(1.0),
MemorySize.parse("1m"),
... |
public <I> I newFlyweight(Class<I> implementationParent, String templateFileName, Object... args) {
Template template = Template.fromFile(implementationParent, templateFileName);
return newFlyweight(implementationParent, templateFileName, template, args);
} | @Test
public void shouldBeAbleToMoveFlyweights() {
Example writer = (Example) newFlyweight();
Example reader = (Example) newFlyweight();
StubFlyweight writeCursor = (StubFlyweight) writer;
StubFlyweight readCursor = (StubFlyweight) reader;
writeCursor.moveTo(startAddress + ... |
@Override
public String convertTo(SortedSet<Path> value) {
if (value == null) {
throw new ParameterException("String list of Paths must not be null.");
}
return value.stream().map(Path::toString).collect(Collectors.joining(","));
} | @Test
public void testConvertToEmpty() {
assertEquals("", converter.convertTo(new TreeSet<>()));
} |
public boolean execute(final File clusterDir)
{
if (!clusterDir.exists() || !clusterDir.isDirectory())
{
throw new IllegalArgumentException("invalid cluster directory: " + clusterDir.getAbsolutePath());
}
final RecordingLog.Entry entry = ClusterTool.findLatestValidSnapsh... | @Test
void executeThrowsIllegalArgumentExceptionIfClusterDirIsNotADirectory(
final @TempDir File tempDir) throws IOException
{
final File clusterDir = new File(tempDir, "file.txt");
assertTrue(clusterDir.createNewFile());
final IllegalArgumentException exception = assertThrowsEx... |
@Override
public ConsumerRunningInfo getConsumerRunningInfo(String consumerGroup, String clientId,
boolean jstack) throws RemotingException,
MQClientException, InterruptedException {
return defaultMQAdminExtImpl.getConsumerRunningInfo(consumerGroup, clientId, jstack);
} | @Test
public void testGetConsumerRunningInfo() throws RemotingException, MQClientException, InterruptedException {
ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo("consumer-group", "cid_123", false);
assertThat(consumerRunningInfo.getJstack()).isEqualTo("test");
... |
public static <InputT> KeyByBuilder<InputT> of(PCollection<InputT> input) {
return named(null).of(input);
} | @Test
public void testBuild_Windowing() {
final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings());
final PCollection<Triple<String, Long, Long>> result =
TopPerKey.of(dataset)
.keyBy(s -> s)
.valueBy(s -> 1L)
.scoreBy(s -> 1L)
... |
public static boolean canFail(LogicalType inputType, LogicalType targetType) {
return Preconditions.checkNotNull(
resolve(inputType, targetType), "Cast rule cannot be resolved")
.canFail(inputType, targetType);
} | @Test
void testCanFail() {
assertThat(CastRuleProvider.canFail(TINYINT, INT)).isFalse();
assertThat(CastRuleProvider.canFail(STRING_TYPE, TIME().getLogicalType())).isTrue();
assertThat(CastRuleProvider.canFail(STRING_TYPE, STRING_TYPE)).isFalse();
LogicalType inputType = ROW(TINYINT... |
@Nullable
public Function<DnsNameResolverBuilder, DnsAddressResolverGroup> dnsAddressResolverGroupProvider() {
return dnsAddressResolverGroupProvider;
} | @Test
void dnsAddressResolverGroupProvider() {
assertThat(builder.build().dnsAddressResolverGroupProvider()).isNull();
Function<DnsNameResolverBuilder, DnsAddressResolverGroup> provider = RoundRobinDnsAddressResolverGroup::new;
builder.dnsAddressResolverGroupProvider(provider);
assertThat(builder.build().dnsA... |
public synchronized boolean hasEndOfData() {
if (hasEndOfBlock()) {
int potentialEndOfDataIndex = endOfBlockIndex + 1;
if (potentialEndOfDataIndex < availableByteCount
&& buffer[potentialEndOfDataIndex] == MllpProtocolConstants.END_OF_DATA) {
return tr... | @Test
public void testHasEndOfData() {
assertFalse(instance.hasEndOfData(), "Unexpected initial value");
// Test just the END_OF_DATA
instance.write(MllpProtocolConstants.END_OF_DATA);
assertFalse(instance.hasEndOfData());
instance.reset();
assertFalse(instance.hasE... |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile,
String apiTemplateId, List<KeyValue<String, Object>> templateParams) throws Throwable {
// 构建请求
SendSmsRequest request = new SendSmsRequest();
request.setSmsSdkAppId(getSdkAppId());
... | @Test
public void testDoSendSms_fail() throws Throwable {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
List<KeyValue<String, Object>> templateParams = Lists.newArrayList(
new KeyValue<>("1", 12... |
public static <P, R> FuncRt<P, R> uncheck(Func<P, R> expression) {
return uncheck(expression, RuntimeException::new);
} | @Test
public void functionTest() {
Func1<String, String> afunc = (funcParam) -> {
if (funcParam.length() > 5) {
throw new Exception("这是受检查异常需要屌用处显示处理");
}
return funcParam.toUpperCase();
};
//afunc.apply("hello world"); 直接调用需要处理异常
try {
//本行代码原本需要抛出受检查异常,现在只抛出运行时异常
CheckedUtil.uncheck(afu... |
@Override
public void persist(final String key, final String value) {
try {
if (isExisted(key)) {
update(key, value);
return;
}
String tempPrefix = "";
String parent = SEPARATOR;
String[] paths = Arrays.stream(key.sp... | @Test
void assertPersistFailureDuringInsert() throws SQLException {
when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByKeySQL())).thenReturn(mockPreparedStatement);
when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet);
when(mockResultSet.next()).thenReturn(fals... |
@Override
public Map<String, Object> entries() {
return threadLocal.get();
} | @Test
public void testEntries() {
// Test getting all entries
contextCore.put("key1", "value1");
contextCore.put("key2", "value2");
contextCore.put("key3", "value3");
assertEquals(3, contextCore.entries().size());
assertTrue(contextCore.entries().containsKey("key1"));... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_collection_of_non_serializable_object() {
List<NonSerializableObject> original = new ArrayList<>();
original.add(new NonSerializableObject("value"));
List<NonSerializableObject> cloned = serializer.clone(original);
assertEquals(original, cloned);
... |
@Override
public void abort(OutputBufferId bufferId)
{
checkState(!Thread.holdsLock(this), "Can not abort while holding a lock on this");
requireNonNull(bufferId, "bufferId is null");
getBuffer(bufferId).destroy();
checkFlushComplete();
} | @Test
public void testAbort()
{
BroadcastOutputBuffer bufferedBuffer = createBroadcastBuffer(
createInitialEmptyOutputBuffers(BROADCAST)
.withBuffer(FIRST, BROADCAST_PARTITION_ID)
.withBuffer(SECOND, BROADCAST_PARTITION_ID)
... |
@Override
public void commit() {
Tasks.foreach(ops)
.retry(base.propertyAsInt(COMMIT_NUM_RETRIES, COMMIT_NUM_RETRIES_DEFAULT))
.exponentialBackoff(
base.propertyAsInt(COMMIT_MIN_RETRY_WAIT_MS, COMMIT_MIN_RETRY_WAIT_MS_DEFAULT),
base.propertyAsInt(COMMIT_MAX_RETRY_WAIT_MS, C... | @TestTemplate
public void testExpireSnapshotsWhenGarbageCollectionDisabled() {
table.updateProperties().set(TableProperties.GC_ENABLED, "false").commit();
table.newAppend().appendFile(FILE_A).commit();
assertThatThrownBy(() -> table.expireSnapshots())
.isInstanceOf(ValidationException.class)
... |
@Override
public byte[] serialize(final String topic, final List<?> data) {
if (data == null) {
return null;
}
try {
final StringWriter stringWriter = new StringWriter();
final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
csvPrinter.printRecord(() -> new FieldI... | @Test
public void shouldSerializeReallyLargeDecimalWithoutScientificNotation() {
// Given:
givenSingleColumnSerializer(SqlTypes.decimal(10, 3));
final List<?> values = Collections.singletonList(new BigDecimal("10000000000.000"));
// When:
final byte[] bytes = serializer.serialize("", values);
... |
public ProjectList searchProjects(String gitlabUrl, String personalAccessToken, @Nullable String projectName,
@Nullable Integer pageNumber, @Nullable Integer pageSize) {
String url = format("%s/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%s%s%s",
gitlabUrl,
proj... | @Test
public void should_throw_IllegalArgumentException_when_token_insufficient_scope() {
MockResponse response = new MockResponse()
.setResponseCode(403)
.setBody("{\"error\":\"insufficient_scope\"," +
"\"error_description\":\"The request requires higher privileges than provided by the access... |
@ProcessElement
public void processElement(OutputReceiver<PartitionMetadata> receiver) {
PartitionMetadataDao partitionMetadataDao = daoFactory.getPartitionMetadataDao();
if (!partitionMetadataDao.tableExists()) {
daoFactory.getPartitionMetadataAdminDao().createPartitionMetadataTable();
createFake... | @Test
public void testInitialize() {
when(daoFactory.getPartitionMetadataDao()).thenReturn(partitionMetadataDao);
when(partitionMetadataDao.tableExists()).thenReturn(false);
when(daoFactory.getPartitionMetadataAdminDao()).thenReturn(partitionMetadataAdminDao);
doNothing().when(partitionMetadataAdminDa... |
public String doLayout(ILoggingEvent event) {
StringBuilder buf = new StringBuilder();
startNewTableIfLimitReached(buf);
boolean odd = true;
if (((counter++) & 1) == 0) {
odd = false;
}
String level = event.getLevel().toString().toLowerCase();
buf.a... | @Test
@Disabled
public void rawLimit() throws Exception {
StringBuilder sb = new StringBuilder();
String header = layout.getFileHeader();
assertTrue(header.startsWith(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-str... |
@Override
public void close() throws BlockStoreException {
try {
buffer.force();
buffer = null; // Allow it to be GCd and the underlying file mapping to go away.
fileLock.release();
randomAccessFile.close();
blockCache.clear();
} catch (IO... | @Test(expected = BlockStoreException.class)
public void twoStores_sequentially_shrink() throws Exception {
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile, 20, true);
store.close();
store = new SPVBlockStore(TESTNET, blockStoreFile, 10, true);
} |
@Override
public Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor(
List<ExecutionAttemptID> executionAttemptIds) {
final Map<ExecutionVertexID, ExecutionAttemptID> vertexIdToExecutionId = new HashMap<>();
executionAttemptIds.forEach(
executionId ->
... | @Test
void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture()
throws ExecutionException, InterruptedException {
AllocationContext context = AllocationContext.newBuilder().addGroup(EV1).build();
ExecutionSlotAssignment assignment1 =
getAssignmentByExecutionVertexId... |
public static String getNativeDataTypeSimpleName( ValueMetaInterface v ) {
try {
return v.getType() != ValueMetaInterface.TYPE_BINARY ? v.getNativeDataTypeClass().getSimpleName() : "Binary";
} catch ( KettleValueException e ) {
LogChannelInterface log = new LogChannel( v );
log.logDebug( BaseM... | @Test
public void getNativeDataTypeSimpleName_Timestamp() {
ValueMetaTimestamp v = new ValueMetaTimestamp();
assertEquals( "Timestamp", FieldHelper.getNativeDataTypeSimpleName( v ) );
} |
public static void main(String[] args) {
// DB seeding
LOGGER.info("Db seeding: " + "1 user: {\"ignite1771\", amount = 1000.0}, "
+ "2 products: {\"computer\": price = 800.0, \"car\": price = 20000.0}");
Db.getInstance().seedUser(TEST_USER_1, 1000.0);
Db.getInstance().seedItem(ITEM_COMPUTER, 800... | @Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@Override
public boolean deleteAll(JobID jobId) {
return delete(BlobUtils.getStorageLocationPath(basePath, jobId));
} | @Test
void testDeleteAll() throws IOException {
final Path temporaryFile = createTemporaryFileWithContent("delete");
final JobID jobId = new JobID();
assertThat(testInstance.put(temporaryFile.toFile(), jobId, new PermanentBlobKey()))
.isTrue();
assertThat(testInstanc... |
public boolean isJspOrStrutsCounter() {
return JSP_COUNTER_NAME.equals(name) || STRUTS_COUNTER_NAME.equals(name);
} | @Test
public void testJspOrStrutsCounter() {
assertFalse("jspOrStrutsCounter", new Counter("http", null).isJspOrStrutsCounter());
assertTrue("jspOrStrutsCounter", new Counter("jsp", null).isJspOrStrutsCounter());
assertTrue("jspOrStrutsCounter", new Counter("struts", null).isJspOrStrutsCounter());
} |
@Override
public boolean isConnected() {
return channel.isConnected();
} | @Test
void isConnectedTest() {
Assertions.assertFalse(header.isConnected());
} |
@Override
synchronized public void registerConfigChangeWatcher(ConfigChangeWatcher watcher) {
startListening(new WatcherHolder(watcher), new ConfigChangeCallback() {
@Override
public synchronized void onSingleValueChanged(final WatcherHolder holder, final ConfigTable.ConfigItem confi... | @Test
public void testInit() {
final String[] newValue = new String[1];
register.registerConfigChangeWatcher(
new ConfigChangeWatcher("MockModule", new FetchingConfigWatcherRegisterTest.MockProvider(), "prop2") {
@Override
public void notify(ConfigChangeE... |
@Override
public void completeInitialLoad() {
data = data.copyWithNewLoadingComplete(true);
data.log.info("Completed initial ACL load process.");
initialLoadFuture.complete(null);
} | @Test
public void testCompleteInitialLoad() {
StandardAuthorizer authorizer = new StandardAuthorizer();
authorizer.configure(Collections.singletonMap(SUPER_USERS_CONFIG, "User:superman"));
Map<Endpoint, ? extends CompletionStage<Void>> futures = authorizer.
start(new AuthorizerTe... |
@Override
public boolean isValidHeader(final int readableBytes) {
return readableBytes >= (startupPhase ? 0 : MESSAGE_TYPE_LENGTH) + PAYLOAD_LENGTH;
} | @Test
void assertIsInvalidHeader() {
assertTrue(new PostgreSQLPacketCodecEngine().isValidHeader(4));
} |
public double length() {
double result = 0;
for (LineSegment segment : this.segments) {
result += segment.length();
}
return result;
} | @Test
public void lengthTest() {
Point point1 = new Point(0, 0);
Point point2 = new Point(1, 0);
Point point3 = new Point(1, 1);
Point point4 = new Point(3, 1);
LineString lineString = new LineString();
lineString.segments.add(new LineSegment(point1, point2));
... |
public void setup(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to setup internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final Map<String, Map<String, String>> streamsSideTopicCo... | @Test
public void shouldOnlyRetryNotSuccessfulFuturesDuringSetup() {
final AdminClient admin = mock(AdminClient.class);
final StreamsConfig streamsConfig = new StreamsConfig(config);
final InternalTopicManager topicManager = new InternalTopicManager(time, admin, streamsConfig);
final... |
public int base() { return this.alphabet.alphabetChars.length; } | @Test
void base62_codec_test_cases_pass() {
var b62 = Base62.codec();
assertEquals(62, b62.base());
verifyRoundtrip(b62, "Hello World!", "T8dgcjRGkZ3aysdN");
verifyRoundtrip(b62, "\0\0Hello World!", "00T8dgcjRGkZ3aysdN");
verifyRoundtrip(b62, "", "");
verifyRoundtrip(... |
@Override
public double score(int[] truth, int[] prediction) {
return of(truth, prediction);
} | @Test
public void testMeasure() {
System.out.println("FDR");
int[] truth = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... |
@SuppressWarnings("unchecked")
public <T extends Expression> T rewrite(final T expression, final C context) {
return (T) rewriter.process(expression, context);
} | @Test
public void shouldRewriteLogicalBinaryExpression() {
// Given:
final LogicalBinaryExpression parsed = parseExpression("true OR false");
when(processor.apply(parsed.getLeft(), context)).thenReturn(expr1);
when(processor.apply(parsed.getRight(), context)).thenReturn(expr2);
// When:
final... |
@Override
public JobStatus getJobStatus() {
return JobStatus.CANCELLING;
} | @Test
void testStateDoesNotExposeGloballyTerminalExecutionGraph() throws Exception {
try (MockStateWithExecutionGraphContext ctx = new MockStateWithExecutionGraphContext()) {
StateTrackingMockExecutionGraph meg = new StateTrackingMockExecutionGraph();
Canceling canceling = createCanc... |
@Override
public PackageRevision responseMessageForLatestRevisionSince(String responseBody) {
return toPackageRevision(responseBody);
} | @Test
public void shouldBuildNullPackageRevisionFromLatestRevisionSinceWhenEmptyResponse() throws Exception {
assertThat(messageHandler.responseMessageForLatestRevisionSince(""), nullValue());
assertThat(messageHandler.responseMessageForLatestRevisionSince(null), nullValue());
assertThat(mes... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof Rotation)) {
return false;
}
Rotation other = (Rotation) obj;
if (noRotation(this)) {
return noRotation(other);
}
if (... | @Test
public void equalsTest() {
Rotation Rotation1 = new Rotation(1, 2, 1);
Rotation Rotation2 = new Rotation(1, 2, 1);
Rotation Rotation3 = new Rotation(1, 1, 1);
Rotation Rotation4 = new Rotation(2, 2, 4);
TestUtils.equalsTest(Rotation1, Rotation2);
TestUtils.not... |
@Override
public Long sendSingleMailToAdmin(String mail, Long userId,
String templateCode, Map<String, Object> templateParams) {
// 如果 mail 为空,则加载用户编号对应的邮箱
if (StrUtil.isEmpty(mail)) {
AdminUserDO user = adminUserService.getUser(userId);
... | @Test
public void testSendSingleMailToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// m... |
public final void isFinite() {
if (actual == null || actual.isNaN() || actual.isInfinite()) {
failWithActual(simpleFact("expected to be finite"));
}
} | @Test
public void isFinite() {
assertThat(1.23f).isFinite();
assertThat(Float.MAX_VALUE).isFinite();
assertThat(-1.0 * Float.MIN_VALUE).isFinite();
assertThatIsFiniteFails(Float.POSITIVE_INFINITY);
assertThatIsFiniteFails(Float.NEGATIVE_INFINITY);
assertThatIsFiniteFails(Float.NaN);
assert... |
@Override
public final void collect(T record) {
collect(record, TimestampAssigner.NO_TIMESTAMP);
} | @Test
void testNoTimestampValue() {
final CollectingDataOutput<Integer> dataOutput = new CollectingDataOutput<>();
final SourceOutputWithWatermarks<Integer> out =
createWithSameOutputs(
dataOutput, new RecordTimestampAssigner<>(), new NoWatermarksGenerator<>()... |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PRO... | @Test
void assertGetBinaryProtocolValueWithMySQLTypeLong() {
assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.LONG), instanceOf(MySQLInt4BinaryProtocolValue.class));
} |
@Override
public void onRuleSubscribe(final RuleData ruleData) {
LOG.info("subscribe rule data for rule[id: {}, selectorId: {}, name: {}]", ruleData.getId(), ruleData.getSelectorId(), ruleData.getName());
subscribeDataHandler(ruleData, DataEventTypeEnum.UPDATE);
} | @Test
public void testOnRuleSubscribe() {
baseDataCache.cleanRuleData();
RuleData ruleData = RuleData.builder().id("1").selectorId(mockSelectorId1).enabled(true).pluginName(mockPluginName1).sort(1).build();
commonPluginDataSubscriber.onRuleSubscribe(ruleData);
assertNotNull(baseData... |
@Override
public String name() {
return name;
} | @Test
public void testSetNamespaceOwnership() throws TException {
setNamespaceOwnershipAndVerify(
"set_individual_ownership_on_default_owner",
ImmutableMap.of(),
ImmutableMap.of(
HiveCatalog.HMS_DB_OWNER,
"some_individual_owner",
HiveCatalog.HMS_DB_OWNER... |
@Deprecated
public static org.apache.rocketmq.common.message.Message convertToRocketMessage(
ObjectMapper objectMapper, String charset,
String destination, org.springframework.messaging.Message message) {
Object payloadObj = message.getPayload();
byte[] payloads;
if (payload... | @Test
public void testConvertToRocketMessageWithMessageConvert() {
Message msgWithStringPayload = MessageBuilder.withPayload("test body")
.setHeader("test", 1)
.setHeader(RocketMQHeaders.TAGS, "tags")
.setHeader(RocketMQHeaders.KEYS, "my_keys")
.build();
... |
@Override
public void addSAJSListener(SAJSListener listener) {
} | @Test
public void addSAJSListener() {
mSensorsAPI.addSAJSListener(new SAJSListener() {
@Override
public void onReceiveJSMessage(WeakReference<View> view, String message) {
Assert.fail();
}
});
} |
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
} | @Test
public void resolve_defaultValueLimit() {
assertThat(resolve("${FOO:-default:-other}"), equalTo("default:-other"));
} |
public static Result<Void> success() {
return new Result<Void>()
.setCode(Result.SUCCESS_CODE);
} | @Test
public void success() {
Assert.isTrue(Result.SUCCESS_CODE.equals(Results.success().getCode()));
} |
@Secured(resource = Commons.NACOS_CORE_CONTEXT_V2 + "/loader", action = ActionTypes.WRITE)
@GetMapping("/smartReloadCluster")
public ResponseEntity<String> smartReload(HttpServletRequest request,
@RequestParam(value = "loaderFactor", required = false) String loaderFactorStr,
@RequestPara... | @Test
void testSmartReload() throws NacosException {
EnvUtil.setEnvironment(new MockEnvironment());
Member member = new Member();
member.setIp("1.1.1.1");
member.setPort(8848);
ServerAbilities serverAbilities = new ServerAbilities();
ServerRemoteAbility serverRemoteAb... |
public final Sensor taskLevelSensor(final String threadId,
final String taskId,
final String sensorSuffix,
final RecordingLevel recordingLevel,
final Sensor... ... | @Test
public void shouldGetNewTaskLevelSensor() {
final Metrics metrics = mock(Metrics.class);
final RecordingLevel recordingLevel = RecordingLevel.INFO;
setupGetNewSensorTest(metrics, recordingLevel);
final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_I... |
@Override
public void processElement(StreamRecord<MergeOnReadInputSplit> element) {
splits.add(element.getValue());
enqueueProcessSplits();
} | @Test
public void testCheckpoint() throws Exception {
// Received emitted splits: split1, split2, split3, split4, checkpoint request is triggered
// when reading records from split1.
TestData.writeData(TestData.DATA_SET_INSERT, conf);
long timestamp = 0;
try (OneInputStreamOperatorTestHarness<Merg... |
static <T, W extends BoundedWindow>
ThrowingFunction<KV<T, Iterable<W>>, KV<T, KV<Iterable<W>, Iterable<KV<W, Iterable<W>>>>>>
createMapFunctionForPTransform(String ptransformId, PTransform ptransform)
throws IOException {
RunnerApi.FunctionSpec payload =
RunnerApi.FunctionSpec... | @Test
public void testWindowMergingWithNonMergingWindowFn() throws Exception {
ThrowingFunction<
KV<Object, Iterable<BoundedWindow>>,
KV<
Object,
KV<Iterable<BoundedWindow>, Iterable<KV<BoundedWindow, Iterable<BoundedWindow>>>>>>
mapFunction =
... |
@Override
public void removeSelector(final SelectorData selectorData) {
super.getWasmExtern(REMOVE_SELECTOR_METHOD_NAME)
.ifPresent(handlerPlugin -> callWASI(selectorData, handlerPlugin));
} | @Test
public void removeSelectorTest() {
pluginDataHandler.removeSelector(selectorData);
testWasmPluginDataHandler.handlerSelector(selectorData);
testWasmPluginDataHandler.removeSelector(selectorData);
} |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final List<Path> deleted = new ArrayList<Path>();
for(Map.Entry<Path, TransferStatus> entry : files.entrySet()) {
boolean skip = false;... | @Test(expected = NotfoundException.class)
public void testDeleteNotFound() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new DAVDeleteFeature(session).delete(Collections.singlet... |
@Override
public <R> RFuture<R> evalAsync(Mode mode, String luaScript, ReturnType returnType, List<Object> keys, Object... values) {
String key = getKey(keys);
return evalAsync(key, mode, luaScript, returnType, keys, values);
} | @Test
public void testEvalAsync() {
RScript script = redisson.getScript(StringCodec.INSTANCE);
RFuture<List<Object>> res = script.evalAsync(RScript.Mode.READ_ONLY, "return {'1','2','3.3333','foo',nil,'bar'}", RScript.ReturnType.MULTI, Collections.emptyList());
assertThat(res.toCompletableFut... |
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"})
void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas,
MigrationDecisionCallback callback) {
assert oldReplicas.length == newReplicas.leng... | @Test
public void test_SHIFT_UP() throws UnknownHostException {
final PartitionReplica[] oldReplicas = {
new PartitionReplica(new Address("localhost", 5701), uuids[0]),
null,
new PartitionReplica(new Address("localhost", 5703), uuids[2]),
new P... |
@Override
public boolean equals(Object o)
{
return o instanceof COSInteger && ((COSInteger)o).intValue() == intValue();
} | @Test
void testEquals()
{
// Consistency
for (int i = -1000; i < 3000; i += 200)
{
COSInteger test1 = COSInteger.get(i);
COSInteger test2 = COSInteger.get(i);
COSInteger test3 = COSInteger.get(i);
// Reflexive (x == x)
assertEqu... |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForStreamFilter() {
// Given:
final StreamFilter<?> step = new StreamFilter<>(
PROPERTIES,
streamSource,
mock(Expression.class)
);
// When:
final LogicalSchema result = resolver.resolve(step, SCHEMA);
// Then:
assertThat(result... |
public AlertResult send(String content) {
try {
return checkSendMsgResult(HttpUtils.post(feiShuParams.getWebhook(), content, proxyConfig));
} catch (Exception e) {
e.printStackTrace();
logger.error("send fei shu alert msg exception : {}", e.getMessage(), e);
... | @Ignore
@Test
public void testSend() {
FeiShuAlert feiShuAlert = new FeiShuAlert();
AlertConfig alertConfig = new AlertConfig();
alertConfig.setType(FeiShuConstants.TYPE);
alertConfig.setParam(feiShuConfig);
feiShuAlert.setConfig(alertConfig);
AlertResult alert... |
static boolean applyTags(RuleDto rule, Set<String> tags) {
for (String tag : tags) {
RuleTagFormat.validate(tag);
}
Set<String> initialTags = rule.getTags();
final Set<String> systemTags = rule.getSystemTags();
Set<String> withoutSystemTags = Sets.filter(tags, input -> input != null && !syste... | @Test
public void applyTags() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("java8", "security"));
assertThat(rule.getTags()).containsOnly("java8", "security");
assertThat(changed).isTrue();
} |
public static String artifactToString(Artifact artifact) {
StringBuilder buffer = new StringBuilder(128);
buffer.append(artifact.getGroupId());
buffer.append(':').append(artifact.getArtifactId());
buffer.append(':').append(artifact.getExtension());
if (artifact.getClassifier().le... | @Test
public void artifactToString() {
Artifact testArtifact = new DefaultArtifact("org.apache.storm:storm-core:1.0.0");
String ret = AetherUtils.artifactToString(testArtifact);
assertEquals("org.apache.storm:storm-core:jar:1.0.0", ret);
} |
@SuppressWarnings({"checkstyle:NPathComplexity", "checkstyle:CyclomaticComplexity"})
@Override
public void shutdown() {
log.info("ksqlDB shutdown called");
try {
pullQueryMetrics.ifPresent(PullQueryExecutorMetrics::close);
} catch (final Exception e) {
log.error("Exception while waiting for... | @Test
public void shouldCloseSecurityExtensionOnClose() {
// When:
app.shutdown();
// Then:
verify(securityExtension).close();
} |
public Set<Map.Entry<String, JsonElement>> entrySet() {
return members.entrySet();
} | @Test
public void testEntrySet() {
JsonObject o = new JsonObject();
assertThat(o.entrySet()).hasSize(0);
o.addProperty("b", true);
Set<?> expectedEntries = Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(true)));
assertThat(o.entrySet()).isEqualTo(expectedEntries);
assertThat(o... |
public void removeFromLastWhen(final Predicate<T> predicate) {
Segment<T> lastSeg = getLast();
while (true) {
if (lastSeg == null) {
this.firstOffset = this.size = 0;
return;
}
int removed = lastSeg.removeFromLastWhen(predicate);
... | @Test
public void testRemoveFromLastWhen() {
fillList();
// remove elements is greater or equal to 150.
this.list.removeFromLastWhen(x -> x >= 150);
assertEquals(150, this.list.size());
assertFalse(this.list.isEmpty());
for (int i = 0; i < 150; i++) {
ass... |
public Map<String, Parameter> generateMergedWorkflowParams(
WorkflowInstance instance, RunRequest request) {
Workflow workflow = instance.getRuntimeWorkflow();
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
Map<String, ParamDefinition> defaultWorkflowParams =
defaultParamMa... | @Test
public void testSubRestartConfigRunUnchangedParamMerge() {
Map<String, Object> meta =
Collections.singletonMap(Constants.METADATA_SOURCE_KEY, "SUBWORKFLOW");
LongParameter param =
LongParameter.builder()
.name("TARGET_RUN_DATE")
.value(1000L)
.evaluate... |
@Override
public int getPrecision(final int column) {
Preconditions.checkArgument(1 == column);
return 0;
} | @Test
void assertGetPrecision() throws SQLException {
assertThat(actualMetaData.getPrecision(1), is(0));
} |
public static HoodieRecordMerger loadRecordMerger(String mergerClass) {
try {
HoodieRecordMerger recordMerger = (HoodieRecordMerger) INSTANCE_CACHE.get(mergerClass);
if (null == recordMerger) {
synchronized (HoodieRecordMerger.class) {
recordMerger = (HoodieRecordMerger) INSTANCE_CACHE... | @Test
void loadHoodieMergeWithWrongMerger() {
String mergeClassName = "wrong.package.MergerName";
assertThrows(HoodieException.class, () -> HoodieRecordUtils.loadRecordMerger(mergeClassName));
} |
@Override
public ResultSet getTablePrivileges(final String catalog, final String schemaPattern, final String tableNamePattern) throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getTablePrivileges(getActualCatalog(catalog), getActualSchema(schemaPattern), getActualTableNamePa... | @Test
void assertGetTablePrivileges() throws SQLException {
when(databaseMetaData.getTablePrivileges("test", null, null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getTablePrivileges("test", null, null), instanceOf(DatabaseMetaDataResultSet.class));
} |
public JobRecord getJobRecord(long jobId) {
return jobRecords.get().get(jobId);
} | @Test
public void test_getJobRecordFromClient() {
HazelcastInstance client = createHazelcastClient();
Pipeline p = Pipeline.create();
p.readFrom(Sources.streamFromProcessor("source", ProcessorMetaSupplier.of(() -> new NoOutputSourceP())))
.withoutTimestamps()
... |
@VisibleForTesting
@Nonnull
Map<String, Object> prepareContextForPaginatedResponse(@Nonnull List<RuleDao> rules) {
final Map<String, RuleDao> ruleTitleMap = rules
.stream()
.collect(Collectors.toMap(RuleDao::title, dao -> dao));
final Map<String, List<PipelineCom... | @Test
public void prepareContextForPaginatedResponse_returnsEmptyRuleMapIfRulesNotUsedByPipelines() {
final List<RuleDao> rules = List.of(
ruleDao("rule-1", "Rule 1"),
ruleDao("rule-2", "Rule 2")
);
assertThat(underTest.prepareContextForPaginatedResponse(rule... |
public Array getArray(String name) {
Array a = arrayMap.get(name);
if (a == null) {
validateArray(name);
a = new Array(configDefinition, name);
arrayMap.put(name, a);
}
return a;
} | @Test
public void require_that_definition_is_passed_to_childarray() {
ConfigPayloadBuilder.Array nestedArray = builderWithDef.getArray("myarray");
nestedArray.append("1337");
} |
public static IssueChangeContextBuilder newBuilder() {
return new IssueChangeContextBuilder();
} | @Test
public void test_equal() {
context = IssueChangeContext.newBuilder()
.setUserUuid(USER_UUID)
.setDate(NOW)
.setExternalUser(EXTERNAL_USER)
.setWebhookSource(WEBHOOK_SOURCE)
.build();
IssueChangeContext equalContext = IssueChangeContext.newBuilder()
.setUserUuid(USER_U... |
private CoordinatorResult<ShareGroupHeartbeatResponseData, CoordinatorRecord> shareGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String rackId,
String clientId,
String clientHost,
List<String> subscribedTopicNames
) throws ApiException {
... | @Test
public void testShareGroupMemberIdGeneration() {
MockPartitionAssignor assignor = new MockPartitionAssignor("share");
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.withShareGroupAssignor(assignor)
.withMetadataImage(MetadataIma... |
@Override
public Ring<T> createRing(Map<T, Integer> pointsMap) {
return _ringFactory.createRing(pointsMap);
} | @Test(groups = { "small", "back-end" })
public void testPointsCleanUpLarge()
throws URISyntaxException
{
Map<String, Integer> pointsMp = buildPointsMap(19);
PointBasedConsistentHashRingFactory<String> ringFactory = new PointBasedConsistentHashRingFactory<>(new DegraderLoadBalancerStrategyConfig(1L));... |
@Override
public Instant getWatermarkThatGuaranteesFiring(BoundedWindow window) {
return BoundedWindow.TIMESTAMP_MAX_VALUE;
} | @Test
public void testFireDeadline() throws Exception {
assertEquals(
BoundedWindow.TIMESTAMP_MAX_VALUE,
underTest.getWatermarkThatGuaranteesFiring(
new IntervalWindow(new Instant(0), new Instant(10))));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.