focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void stop() {
stop(true);
} | @Test
public void shouldNotCallCloseCallbackOnStop() {
// When:
query.stop();
// Then:
verify(listener, times(0)).onClose(query);
} |
@Override
public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context,
Map<String, Long> recentlyUnloadedBundles,
Map<String, Long> recentlyUnloadedBrokers) {
final var conf = context.broker... | @Test
public void testSingleTopBundlesLoadData() {
UnloadCounter counter = new UnloadCounter();
TransferShedder transferShedder = new TransferShedder(counter);
var ctx = setupContext();
var topBundlesLoadDataStore = ctx.topBundleLoadDataStore();
topBundlesLoadDataStore.pushAs... |
public static JibContainerBuilder toJibContainerBuilder(
ArtifactProcessor processor,
Jar jarOptions,
CommonCliOptions commonCliOptions,
CommonContainerConfigCliOptions commonContainerConfigCliOptions,
ConsoleLogger logger)
throws IOException, InvalidImageReferenceException {
Str... | @Test
public void testToJibContainerBuilder_packagedStandard_basicInfo()
throws IOException, InvalidImageReferenceException {
when(mockStandardPackagedProcessor.getJavaVersion()).thenReturn(8);
FileEntriesLayer layer =
FileEntriesLayer.builder()
.setName("jar")
.addEntry(... |
public static RestSettingBuilder get(final String id) {
return get(eq(checkId(id)));
} | @Test
public void should_get_all_resources() throws Exception {
Plain resource1 = new Plain();
resource1.code = 1;
resource1.message = "hello";
Plain resource2 = new Plain();
resource2.code = 2;
resource2.message = "world";
server.resource("targets",
... |
int calculatePrice(Integer basePrice, Integer percent, Integer fixedPrice) {
// 1. 优先使用固定佣金
if (fixedPrice != null && fixedPrice > 0) {
return ObjectUtil.defaultIfNull(fixedPrice, 0);
}
// 2. 根据比例计算佣金
if (basePrice != null && basePrice > 0 && percent != null && percen... | @Test
public void testCalculatePrice_equalsZero() {
// mock 数据
Integer payPrice = null;
Integer percent = null;
Integer fixedPrice = null;
// 调用
int brokerage = brokerageRecordService.calculatePrice(payPrice, percent, fixedPrice);
// 断言
assertEquals(br... |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<Path>();
// At least one entry successfully parsed
boolean success = false;
// Call hook for those im... | @Test(expected = FTPInvalidListException.class)
public void test3763() throws Exception {
Path path = new Path("/www", EnumSet.of(Path.Type.directory));
assertEquals("www", path.getName());
assertEquals("/www", path.getAbsolute());
final AttributedList<Path> list = new FTPListRespons... |
@VisibleForTesting
static Function<List<String>, ProcessBuilder> defaultProcessBuilderFactory(
String dockerExecutable, ImmutableMap<String, String> dockerEnvironment) {
return dockerSubCommand -> {
List<String> dockerCommand = new ArrayList<>(1 + dockerSubCommand.size());
dockerCommand.add(dock... | @Test
public void testDefaultProcessorBuilderFactory_customExecutable() {
ProcessBuilder processBuilder =
CliDockerClient.defaultProcessBuilderFactory("docker-executable", ImmutableMap.of())
.apply(Arrays.asList("sub", "command"));
Assert.assertEquals(
Arrays.asList("docker-execut... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STATE:
handleLiteralState(c,... | @Test
public void testEmptyP2() throws ScanException {
List<Token> tl = new TokenStream("%()").tokenize();
List<Token> witness = new ArrayList<Token>();
witness.add(Token.PERCENT_TOKEN);
witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN);
witness.add(Token.RIGHT_PARENTHESIS_TOKEN);
assertEquals(w... |
public void calculate(IThrowableProxy tp) {
while (tp != null) {
populateFrames(tp.getStackTraceElementProxyArray());
IThrowableProxy[] suppressed = tp.getSuppressed();
if(suppressed != null) {
for(IThrowableProxy current:suppressed) {
populateFrames(current.getStackTraceElementP... | @Test
public void nested() throws Exception {
Throwable t = TestHelper.makeNestedException(3);
ThrowableProxy tp = new ThrowableProxy(t);
PackagingDataCalculator pdc = tp.getPackagingDataCalculator();
pdc.calculate(tp);
verify(tp);
} |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
try {
final EueApiClient client = new EueApiClient(session);
// Move to trash first as precondition of delete
this.dele... | @Test(expected = NotfoundException.class)
public void testDoubleDelete() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path file = new EueTouchFeature(session, fileid).touch(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.T... |
public KsqlTarget target(final URI server) {
return target(server, Collections.emptyMap());
} | @Test
public void shouldSendKsqlRequest() {
// Given:
String ksql = "some ksql";
Object expectedResponse = setupExpectedResponse();
// When:
KsqlTarget target = ksqlClient.target(serverUri);
RestResponse<KsqlEntityList> resp = target.postKsqlRequest(ksql, Collections.emptyMap(), Optional.of(... |
@Override
public void setQualityGate(QualityGate g) {
// fail fast
requireNonNull(g);
checkState(qualityGate == null, "QualityGateHolder can be initialized only once");
this.qualityGate = g;
} | @Test
public void setQualityGate_throws_ISE_if_called_twice() {
assertThatThrownBy(() -> {
QualityGateHolderImpl holder = new QualityGateHolderImpl();
holder.setQualityGate(QUALITY_GATE);
holder.setQualityGate(QUALITY_GATE);
})
.isInstanceOf(IllegalStateException.class);
} |
public static String compareMd5ResultString(List<String> changedGroupKeys) throws IOException {
if (null == changedGroupKeys) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String groupKey : changedGroupKeys) {
String[] dataIdGroupId = GroupKey.parseK... | @Test
public void compareMd5ResultStringTest() {
String key = null;
try {
key = Md5ConfigUtil.compareMd5ResultString(Lists.newArrayList("DataId+Group"));
} catch (IOException ignored) {
}
Assert.isTrue(Objects.equals("DataId%02Group%01", key));
} |
@Override
protected Collection<X509Certificate> getTrusted() {
return repository.findTrustedCertificates().stream().map(
c -> X509Factory.toCertificate(c.getRaw())
).collect(Collectors.toList());
} | @Test
public void shouldNotLoadCertificateIfNoTrustedInDocumentType() throws Exception {
final Certificate rdw = loadCertificate("rdw/01.cer", true);
final Certificate npkd = loadCertificate("npkd/01.cer", false);
certificateRepo.save(rdw);
certificateRepo.save(npkd);
certifi... |
public MutableDataset<T> load(Path csvPath, String responseName) throws IOException {
return new MutableDataset<>(loadDataSource(csvPath, responseName));
} | @Test
public void testFileDoesNotExist() {
Path tmp;
try {
tmp = Files.createTempFile("CSVLoaderTest_testFileDoesNotExist", "txt");
Files.delete(tmp);
assertFalse(Files.exists(tmp));
} catch (IOException e) {
throw new RuntimeException(e);
... |
@Deactivate
public void deactivate() {
states.removeListener(statesListener);
eventHandler.shutdown();
violations.destroy();
log.info("Stopped");
} | @Test
public void testDeactivate() {
eventHandler = newSingleThreadExecutor(groupedThreads("onos/security/store", "event-handler", log));
eventHandler.shutdown();
assertTrue(eventHandler.isShutdown());
} |
public Stream<Hit> stream() {
if (nPostingLists == 0) {
return Stream.empty();
}
return StreamSupport.stream(new PredicateSpliterator(), false);
} | @Test
void requireThatSingleStreamFiltersOnConstructedCompleteIntervals() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 1, 1},
postingList(
SubqueryBitmap.ALL_SUBQUERIES,
entry(0, 0x000100ff),
... |
public List<StepInstance> getAllStepInstances(
String workflowId, long workflowInstanceId, long workflowRunId) {
return getStepInstancesByIds(
workflowId, workflowInstanceId, workflowRunId, null, this::maestroStepFromResult);
} | @Test
public void testGetAllStepInstances() {
List<StepInstance> instances = stepDao.getAllStepInstances(TEST_WORKFLOW_ID, 1, 1);
assertEquals(1, instances.size());
StepInstance instance = instances.get(0);
assertEquals(StepInstance.Status.RUNNING, instance.getRuntimeState().getStatus());
assertFa... |
public static ReadStudyMetadata readStudyMetadata() {
return new ReadStudyMetadata();
} | @Test
public void test_Dicom_failedMetadataRead() {
String badWebPath = "foo";
DicomIO.ReadStudyMetadata.Result retrievedData;
retrievedData = pipeline.apply(Create.of(badWebPath)).apply(DicomIO.readStudyMetadata());
PAssert.that(retrievedData.getReadResponse()).empty();
PAssert.that(retrievedD... |
@Override
public String resolve(Method method, Object[] arguments, String spelExpression) {
if (StringUtils.isEmpty(spelExpression)) {
return spelExpression;
}
if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) {
return stringValueReso... | @Test
public void stringSpelTest() throws Exception {
String testExpression = "#{'recover'}";
DefaultSpelResolverTest target = new DefaultSpelResolverTest();
Method testMethod = target.getClass().getMethod("testMethod", String.class);
String result = sut.resolve(testMethod, new Obj... |
@Override
@GuardedBy("getLock()")
public boolean hasPage(PageId pageId) {
return mPages.contains(INDEX_PAGE_ID, pageId);
} | @Test
public void hasPage() {
Assert.assertFalse(mMetaStore.hasPage(mPage));
mMetaStore.addPage(mPage, mPageInfo);
Assert.assertTrue(mMetaStore.hasPage(mPage));
} |
public Set<HotColdLocation> signal(@Nonnull final WorldPoint worldPoint, @Nonnull final HotColdTemperature temperature, @Nullable final HotColdTemperatureChange temperatureChange)
{
// when the strange device reads a temperature, that means that the center of the final dig location
// is a range of squares away fr... | @Test
public void testBeginnerCowFieldNarrowing()
{
// Start with Cow field north of Lumbridge and Northeast of Al Kharid mine locations remaining
final Set<HotColdLocation> startingLocations = EnumSet.of(
HotColdLocation.LUMBRIDGE_COW_FIELD,
HotColdLocation.NORTHEAST_OF_AL_KHARID_MINE
);
HotColdSolver ... |
@Override
public void subscribe(String serviceName, EventListener listener) throws NacosException {
subscribe(serviceName, new ArrayList<>(), listener);
} | @Test
void testSubscribe4() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
List<String> clusterList = Arrays.asList("cluster1", "cluster2");
EventListener listener = event -> {
};
//when
client.su... |
@Override
public <T> Task<T> synchronize(Task<T> task, long deadline) {
return PlanLocal.get(getPlanLocalKey(), LockInternal.class)
.flatMap(lockInternal -> {
if (lockInternal != null) {
// we already acquire the lock, add count only.
lockInternal._lockCount++;
... | @Test
public void testReentrant()
throws InterruptedException {
final long deadline = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(10, TimeUnit.SECONDS);
final ZKLock lock = createZKLock();
Task<Integer> synchronizedTask = lock.synchronize(lock.synchronize(Task.value(1), deadline), de... |
@Override
public ResponseHeader execute() throws SQLException {
check(sqlStatement);
ProxyContext.getInstance().getContextManager().getPersistServiceFacade().getMetaDataManagerPersistService().createDatabase(sqlStatement.getDatabaseName());
return new UpdateResponseHeader(sqlStatement);
... | @Test
void assertExecuteCreateExistDatabase() {
when(statement.getDatabaseName()).thenReturn("foo_db");
ContextManager contextManager = mockContextManager();
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
when(ProxyContext.getInstance().databaseExist... |
@Override
public void openExisting(final ProcessorContext context, final long streamTime) {
metricsRecorder.init(ProcessorContextUtils.metricsImpl(context), context.taskId());
super.openExisting(context, streamTime);
} | @Test
public void shouldUpdateSegmentFileNameFromOldColonFormatToNewFormat() throws Exception {
final String storeDirectoryPath = stateDirectory.getAbsolutePath() + File.separator + storeName;
final File storeDirectory = new File(storeDirectoryPath);
//noinspection ResultOfMethodCallIgnored
... |
public void verify(int number, byte[] dg) {
final byte[] compare = digests.get(number);
if (compare == null) {
throw new CryptoException("Could not find digest of data group " + number);
}
final byte[] calculated = DigestUtils.digest(algorithm).digest(dg);
if (!Crypto... | @Test
public void verifyPcaRvigDg14() throws Exception {
final LdsSecurityObject ldsSecurityObject = mapper.read(
readFromCms("pca-rvig"), LdsSecurityObject.class);
ldsSecurityObject.verify(14, createPcaRvigDg14());
} |
public static void smooth(PointList pointList, double maxElevationDelta) {
internSmooth(pointList, 0, pointList.size() - 1, maxElevationDelta);
} | @Test
public void smoothRamer() {
PointList pl1 = new PointList(3, true);
pl1.add(0, 0, 0);
pl1.add(0.0005, 0.0005, 100);
pl1.add(0.001, 0.001, 50);
EdgeElevationSmoothingRamer.smooth(pl1, 70);
assertEquals(3, pl1.size());
assertEquals(100, pl1.getEle(1), .1);... |
public void terminateCluster(final List<String> deleteTopicPatterns) {
terminatePersistentQueries();
deleteSinkTopics(deleteTopicPatterns);
deleteTopics(managedTopics);
ksqlEngine.close();
} | @Test
public void shouldNotCleanUpSchemaIfSchemaDoesNotExist() throws Exception {
// Given:
givenTopicsExistInKafka("K_Foo", "K_Bar");
givenSinkTopicsExistInMetastore(FormatFactory.AVRO, "K_Foo", "K_Bar");
givenSchemasForTopicsExistInSchemaRegistry("K_Bar");
// When:
clusterTerminator.termina... |
@Override
protected List<SegmentConversionResult> convert(PinotTaskConfig pinotTaskConfig, List<File> segmentDirs,
File workingDir)
throws Exception {
int numInputSegments = segmentDirs.size();
_eventObserver.notifyProgress(pinotTaskConfig, "Converting segments: " + numInputSegments);
String t... | @Test
public void testConvert()
throws Exception {
MergeRollupTaskExecutor mergeRollupTaskExecutor = new MergeRollupTaskExecutor(new MinionConf());
mergeRollupTaskExecutor.setMinionEventObserver(new MinionProgressObserver());
Map<String, String> configs = new HashMap<>();
configs.put(MinionConst... |
@Override
public long getIndexedQueryCount() {
throw new UnsupportedOperationException("Queries on replicated maps are not supported.");
} | @Test(expected = UnsupportedOperationException.class)
public void testIndexedQueryCount() {
localReplicatedMapStats.getIndexedQueryCount();
} |
@Override
public Exchange add(CamelContext camelContext, String key, Exchange oldExchange, Exchange newExchange)
throws OptimisticLockingException {
if (!optimistic) {
throw new UnsupportedOperationException();
}
LOG.trace("Adding an Exchange with ID {} for key {} in... | @Test
public void optimisticRepoFailsForNonOptimisticAdd() throws Exception {
JCacheAggregationRepository repo = createRepository(true);
repo.start();
try {
final CamelContext context = context();
Exchange ex = new DefaultExchange(context);
assertThrows(U... |
@Override
public String toString() {
if (data == null)
return getOpCodeName(opcode);
return String.format("%s[%s]", getPushDataName(opcode), ByteUtils.formatHex(data));
} | @Test
public void testToStringOnInvalidScriptChunk() {
// see https://github.com/bitcoinj/bitcoinj/issues/1860
// In summary: toString() throws when given an invalid ScriptChunk.
// It should perhaps be impossible to even construct such a ScriptChunk, but
// until that is the case, t... |
@Override
public void setProperties(final Properties properties) {
} | @Test
public void setPropertiesTest() {
final PostgreSqlUpdateInterceptor postgreSqlUpdateInterceptor = new PostgreSqlUpdateInterceptor();
Assertions.assertDoesNotThrow(() -> postgreSqlUpdateInterceptor.setProperties(mock(Properties.class)));
} |
public static Map<String, String> deserialize2Map(String jsonStr) {
try {
if (StringUtils.hasText(jsonStr)) {
Map<String, Object> temp = OM.readValue(jsonStr, Map.class);
Map<String, String> result = new HashMap<>();
temp.forEach((key, value) -> {
result.put(String.valueOf(key), String.valueOf(val... | @Test
public void testDeserialize2Map() {
String jsonStr = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"}";
Map<String, String> map = JacksonUtils.deserialize2Map(jsonStr);
assertThat(map.size()).isEqualTo(3);
assertThat(map.get("k1")).isEqualTo("v1");
assertThat(map.get("k2")).isEqualTo("v2");
assertThat(ma... |
public static void validateRequestHeadersAndUpdateResourceContext(final Map<String, String> headers,
final Set<String> customMimeTypesSupported,
ServerResourceContext resourceContext)
... | @Test()
public void testValidateRequestHeadersWithValidAcceptHeaderAndMatch() throws Exception
{
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
ServerResourceContext resourceContext = new ResourceContextImpl();
RestUtils.validateRequestHeadersAndUpdateResou... |
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException {
return buildFunction(functionDefinition, true);
} | @Test
public void testBuildFunctionConstantDynamicArrayRawListReturn() throws Exception {
AbiDefinition functionDefinition =
new AbiDefinition(
true,
Arrays.asList(new NamedType("param", "uint8[]")),
"functionName",
... |
public Object toIdObject(String baseId) throws AmqpProtocolException {
if (baseId == null) {
return null;
}
try {
if (hasAmqpUuidPrefix(baseId)) {
String uuidString = strip(baseId, AMQP_UUID_PREFIX_LENGTH);
return UUID.fromString(uuidStrin... | @Test
public void testToIdObjectWithStringContainingNoEncodingPrefix() throws Exception {
String stringId = "myStringId";
Object idObject = messageIdHelper.toIdObject(stringId);
assertNotNull("null object should not have been returned", idObject);
assertEquals("expected id object wa... |
private void flush() throws InterruptedException {
RequestInfo requestInfo = createRequestInfo();
while (rateLimitingStrategy.shouldBlock(requestInfo)) {
mailboxExecutor.yield();
requestInfo = createRequestInfo();
}
List<RequestEntryT> batch = createNextAvailable... | @Test
public void testRetryableErrorsDoNotViolateAtLeastOnceSemanticsDueToRequeueOfFailures()
throws IOException, InterruptedException {
AsyncSinkWriterImpl sink =
new AsyncSinkWriterImplBuilder()
.context(sinkInitContext)
.maxBatch... |
@Override
public void onQueuesUpdate(List<Queue> queues) {
List<QueueUpdateMsg> queueUpdateMsgs = queues.stream()
.map(queue -> QueueUpdateMsg.newBuilder()
.setTenantIdMSB(queue.getTenantId().getId().getMostSignificantBits())
.setTenantIdLSB(qu... | @Test
public void testOnQueueChangeSingleMonolithAndSingleRemoteTransport() {
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(MONOLITH));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(MONOLITH));
when(pa... |
public static Map<String, String> inputFiles(RunContext runContext, Object inputs) throws Exception {
return FilesService.inputFiles(runContext, Collections.emptyMap(), inputs);
} | @Test
void renderInputFile() throws Exception {
RunContext runContext = runContextFactory.of(Map.of("filename", "file.txt", "content", "Hello World"));
Map<String, String> content = FilesService.inputFiles(runContext, Map.of("{{filename}}", "{{content}}"));
assertThat(content.get("file.txt")... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return StringUtils.equals(filePath, ((FlatMessageFile) ob... | @Test
public void testEquals() {
String topic = "EqualsTest";
FlatMessageFile flatFile1 = new FlatMessageFile(flatFileFactory, topic, 0);
FlatMessageFile flatFile2 = new FlatMessageFile(flatFileFactory, topic, 0);
FlatMessageFile flatFile3 = new FlatMessageFile(flatFileFactory, topic... |
@SuppressWarnings("deprecation")
public static void setupDistributedCache(Configuration conf,
Map<String, LocalResource> localResources) throws IOException {
LocalResourceBuilder lrb = new LocalResourceBuilder();
lrb.setConf(conf);
// Cache archives
lrb.setType(LocalResourceType.ARCHIVE);
... | @Test
@Timeout(30000)
public void testSetupDistributedCacheEmpty() throws IOException {
Configuration conf = new Configuration();
Map<String, LocalResource> localResources = new HashMap<String, LocalResource>();
MRApps.setupDistributedCache(conf, localResources);
assertTrue(localResources.isEmpty(),... |
@Override
public Boolean delete(Alarm alarm, User user) {
TenantId tenantId = alarm.getTenantId();
logEntityActionService.logEntityAction(tenantId, alarm.getOriginator(), alarm, alarm.getCustomerId(),
ActionType.ALARM_DELETE, user);
return alarmSubscriptionService.deleteAlarm... | @Test
public void testDelete() {
service.delete(new Alarm(), new User());
verify(logEntityActionService, times(1)).logEntityAction(any(), any(), any(), any(), eq(ActionType.ALARM_DELETE), any());
verify(alarmSubscriptionService, times(1)).deleteAlarm(any(), any());
} |
@Override
public String[] split(String text) {
if (splitContraction) {
text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not");
text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not");
text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not");
f... | @Test
public void testTokenizeTis() {
System.out.println("tokenize tis");
String text = "'tis, 'tisn't, and 'twas were common in early modern English texts.";
String[] expResult = {"'t", "is", ",", "'t", "is", "not", ",", "and",
"'t", "was", "were", "common", "in", "early", "mode... |
@Override
public void remove(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName());
} | @Test
public void testRemove() {
Collection<RedisServer> masters = connection.masters();
connection.remove(masters.iterator().next());
} |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_parse_plugin_publish_enabled() {
properties.put(Constants.PLUGIN_PUBLISH_ENABLED_PROPERTY_NAME, "true");
RuntimeOptions options = cucumberPropertiesParser
.parse(properties)
.enablePublishPlugin()
.build();
assertThat(options.... |
@Override
public synchronized void write(int b) throws IOException {
mUfsOutStream.write(b);
mBytesWritten++;
} | @Test
public void writeIncreasingByteArray() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
try (FileOutStream outStream = mFileSystem.createFile(ufsPath)) {
outStream.write(BufferUtils.getIncreasingByteArray(CHUNK_SIZE));
}
verifyIncreasingBytesWritten(ufsPath, CHUNK_... |
public Result runIndexOrPartitionScanQueryOnOwnedPartitions(Query query) {
Result result = runIndexOrPartitionScanQueryOnOwnedPartitions(query, true);
assert result != null;
return result;
} | @Test
public void runFullQuery() {
Predicate<Object, Object> predicate = Predicates.equal("this", value);
Query query = Query.of()
.mapName(map.getName())
.predicate(predicate)
.iterationType(IterationType.ENTRY)
.partitionIdSet(SetUtil... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void setGameScore() {
int res = (int) (System.currentTimeMillis() / 1000);
BaseResponse response = bot.execute(new SetGameScore(chatId, res, "AgAAAPrwAQCj_Q4D2s-51_8jsuU"));
assertTrue(response.isOk());
SendResponse sendResponse = (SendResponse) bot.execute(
... |
private Main() {
// Utility Class.
} | @Test
public void runsAgainstLocal() throws Exception {
final File pwd = temp.newFolder();
Main.main(String.format(
"--version=local:%s",
System.getProperty("logstash.benchmark.test.local.path")
), String.format("--workdir=%s", pwd.getAbsolutePath()));
} |
@Override
public String getAvailabilityZone() {
return awsMetadataApi.availabilityZoneEcs();
} | @Test
public void getAvailabilityZone() {
// given
String expectedResult = "us-east-1a";
given(awsMetadataApi.availabilityZoneEcs()).willReturn(expectedResult);
// when
String result = awsEcsClient.getAvailabilityZone();
// then
assertEquals(expectedResult, ... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE);
} | @Test
void givenTypePolygonAndConfigWithPolygonDefined_whenOnMsg_thenTrue() throws TbNodeException {
// GIVEN
var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration();
config.setFetchPerimeterInfoFromMessageMetadata(false);
config.setPolygonsDefinition(GeoUtil... |
@Override
public Iterable<Overlay> overlaysReversed() {
return new Iterable<Overlay>() {
/**
* @since 6.1.0
*/
private ListIterator<Overlay> bulletProofReverseListIterator() {
while (true) {
try {
... | @Test
public void testOverlaysReversed() {
final ListTest<Overlay> list = new ListTest<Overlay>() {
private final DefaultOverlayManager defaultOverlayManager = new DefaultOverlayManager(null);
@Override
public void add() {
defaultOverlayManager.add(new O... |
public BeamFnApi.InstructionResponse.Builder harnessMonitoringInfos(
BeamFnApi.InstructionRequest request) {
BeamFnApi.HarnessMonitoringInfosResponse.Builder response =
BeamFnApi.HarnessMonitoringInfosResponse.newBuilder();
MetricsContainer container = MetricsEnvironment.getProcessWideContainer();... | @Test
public void testReturnsProcessWideMonitoringInfos() {
MetricsEnvironment.setProcessWideContainer(MetricsContainerImpl.createProcessWideContainer());
HashMap<String, String> labels = new HashMap<String, String>();
labels.put(MonitoringInfoConstants.Labels.SERVICE, "service");
labels.put(Monitori... |
@Override
public AuthenticationResult authenticate(final ChannelHandlerContext context, final PacketPayload payload) {
AuthorityRule rule = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class);
if (MySQLConnecti... | @Test
void assertAuthenticateSuccess() {
setConnectionPhase(MySQLConnectionPhase.AUTH_PHASE_FAST_PATH);
AuthorityRule rule = mock(AuthorityRule.class);
when(rule.getAuthenticatorType(any())).thenReturn("");
ShardingSphereUser user = new ShardingSphereUser("root", "", "127.0.0.1");
... |
public static boolean matchPathToPattern(String requestPath, String endpointPattern) {
String[] pathPatternParts = endpointPattern.split("/");
String[] pathParts = requestPath.split("/");
boolean isMatch = true;
for (int i = 0; i < pathPatternParts.length; i++) {
String patt... | @Test
public void testMatchPath() {
String pattern = "/v1/pets/{petId}";
String path = "/v1/pets/1";
Assert.assertTrue(StringUtils.matchPathToPattern(path, pattern));
pattern = "/v1/pets/{petId}/name";
path = "/v1/pets/1/name";
Assert.assertTrue(StringUtils.matchPathT... |
@Bean("EsClient")
public EsClient provide(Configuration config) {
Settings.Builder esSettings = Settings.builder();
// mandatory property defined by bootstrap process
esSettings.put("cluster.name", config.get(CLUSTER_NAME.getKey()).get());
boolean clusterEnabled = config.getBoolean(CLUSTER_ENABLED.g... | @Test
public void connection_to_remote_es_nodes_when_cluster_mode_is_enabled_and_local_es_is_disabled() {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "application");
settings.setProperty(CLUSTER_SEARCH_HOSTS.getKey(), format("%s:8080,%s:8081", loc... |
@Override
public byte[] echo(byte[] message) {
return read(null, ByteArrayCodec.INSTANCE, ECHO, message);
} | @Test
public void testEcho() {
assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes());
} |
public Map<String, String> getLabels() {
return labels;
} | @Test
void testGetLabels() {
Map<String, String> labels = requestMeta.getLabels();
assertNotNull(labels);
assertEquals(1, labels.size());
assertEquals("dev", labels.get("env"));
} |
public ClusterStateBundle.FeedBlock inferContentClusterFeedBlockOrNull(ContentCluster cluster) {
if (!feedBlockEnabled) {
return null;
}
var nodeInfos = cluster.getNodeInfos();
var exhaustions = enumerateNodeResourceExhaustionsAcrossAllNodes(nodeInfos);
if (exhaustion... | @Test
void feed_block_description_can_contain_optional_name_component() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", "a-fancy-disk", 0.51), usage("memory", 0.79)),
... |
public void isAnyOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
isIn(accumulate(first, second, rest));
} | @Test
public void isAnyOfFailure() {
expectFailure.whenTesting().that("x").isAnyOf("a", "b", "c");
assertFailureKeys("expected any of", "but was");
assertFailureValue("expected any of", "[a, b, c]");
} |
public static boolean shouldBackoff(long initialTimestamp, TimeUnit unitInitial, int failedAttempts,
long defaultInterval, long maxBackoffInterval) {
long initialTimestampInNano = unitInitial.toNanos(initialTimestamp);
long currentTime = System.nanoTime();
... | @Test
public void shouldBackoffTest() {
// gives false
assertFalse(Backoff.shouldBackoff(0L, TimeUnit.NANOSECONDS, 0));
long currentTimestamp = System.nanoTime();
// gives true
assertTrue(Backoff.shouldBackoff(currentTimestamp, TimeUnit.NANOSECONDS, 100));
} |
public static TableUpsertMetadataManager create(TableConfig tableConfig,
@Nullable PinotConfiguration instanceUpsertConfig) {
String tableNameWithType = tableConfig.getTableName();
UpsertConfig upsertConfig = tableConfig.getUpsertConfig();
Preconditions.checkArgument(upsertConfig != null, "Must provid... | @Test
public void testCreateForManagerClassWithConsistentDeletes() {
UpsertConfig upsertConfig = new UpsertConfig(UpsertConfig.Mode.FULL);
upsertConfig.setHashFunction(HashFunction.NONE);
upsertConfig.setEnableDeletedKeysCompactionConsistency(true);
_tableConfig =
new TableConfigBuilder(TableT... |
protected abstract FullHttpRequest newHandshakeRequest(); | @Test
public void testSetOriginFromCustomHeaders() {
HttpHeaders customHeaders = new DefaultHttpHeaders().set(getOriginHeaderName(), "http://example.com");
WebSocketClientHandshaker handshaker = newHandshaker(URI.create("ws://server.example.com/chat"), null,
... |
static JobVertexInputInfo computeVertexInputInfoForAllToAll(
int sourceCount,
int targetCount,
Function<Integer, Integer> numOfSubpartitionsRetriever,
boolean isDynamicGraph,
boolean isBroadcast) {
final List<ExecutionVertexInputInfo> executionVertexIn... | @Test
void testComputeVertexInputInfoForAllToAllWithDynamicGraph() {
final JobVertexInputInfo nonBroadcast =
computeVertexInputInfoForAllToAll(2, 3, ignored -> 10, true, false);
assertThat(nonBroadcast.getExecutionVertexInputInfos())
.containsExactlyInAnyOrder(
... |
@Override
public BeamSqlTable buildBeamSqlTable(Table table) {
return new BigQueryTable(table, getConversionOptions(table.getProperties()));
} | @Test
public void testSelectWriteDispositionMethodEmpty() {
Table table =
fakeTableWithProperties(
"hello",
"{ "
+ WRITE_DISPOSITION_PROPERTY
+ ": "
+ "\""
+ WriteDisposition.WRITE_EMPTY.toString()
+ "\... |
public static boolean isBase64(CharSequence base64) {
if (base64 == null || base64.length() < 2) {
return false;
}
final byte[] bytes = StrUtil.utf8Bytes(base64);
if (bytes.length != base64.length()) {
// 如果长度不相等,说明存在双字节字符,肯定不是Base64,直接返回false
return false;
}
return isBase64(bytes);
} | @Test
public void isBase64Test(){
assertTrue(Base64.isBase64(Base64.encode(RandomUtil.randomString(1000))));
} |
public static <T> T convertWithCheck(Type type, Object value, T defaultValue, boolean quietly) {
final ConverterRegistry registry = ConverterRegistry.getInstance();
try {
return registry.convert(type, value, defaultValue);
} catch (Exception e) {
if (quietly) {
return defaultValue;
}
throw e;
}
... | @Test
public void toLongFromNumberWithFormatTest() {
final NumberWithFormat value = new NumberWithFormat(1678285713935L, null);
final Long aLong = Convert.convertWithCheck(Long.class, value, null, false);
assertEquals(new Long(1678285713935L), aLong);
} |
@Override
public Deserializer getDeserializer(String type) throws HessianProtocolException {
// 如果类型在过滤列表, 说明是jdk自带类, 直接委托父类处理
if (StringUtils.isEmpty(type) || ClassFilter.filterExcludeClass(type)) {
return super.getDeserializer(type);
}
// 如果是数组类型, 且在name过滤列表, 说明jdk类, ... | @Test
public void getDeserializer() throws Exception {
} |
@Udf(description = "Returns the hyperbolic tangent of an INT value")
public Double tanh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic tangent of."
) final Integer value
) {
return tanh(value == null ? null : val... | @Test
public void shouldHandleMoreThanPositive2Pi() {
assertThat(udf.tanh(9.1), closeTo(0.9999999750614947, 0.000000000000001));
assertThat(udf.tanh(6.3), closeTo(0.9999932559922726, 0.000000000000001));
assertThat(udf.tanh(7), closeTo(0.9999983369439447, 0.000000000000001));
assertThat(udf.tanh(7L), ... |
public static <T> CloseableIterator<T> from(Iterator<T> iterator) {
// early fail
requireNonNull(iterator);
checkArgument(!(iterator instanceof AutoCloseable), "This method does not support creating a CloseableIterator from an Iterator which is Closeable");
return new RegularIteratorWrapper<>(iterator);... | @Test(expected = IllegalArgumentException.class)
public void from_iterator_throws_IAE_if_arg_is_a_AutoCloseable() {
CloseableIterator.from(new CloseableIt());
} |
@Override
public void execute(ComputationStep.Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void changed_event_if_qp_has_been_updated() {
QualityProfile qp1 = qp(QP_NAME_1, LANGUAGE_KEY_1, BEFORE_DATE);
QualityProfile qp2 = qp(QP_NAME_1, LANGUAGE_KEY_1, AFTER_DATE);
qProfileStatusRepository.register(qp2.getQpKey(), UPDATED);
mockQualityProfileMeasures(treeRootHolder.getRoot(), a... |
public void inputWatermarkStatus(
WatermarkStatus watermarkStatus, int channelIndex, DataOutput<?> output)
throws Exception {
// Shared input channel is only enabled in batch jobs, which do not have watermark status
// events.
Preconditions.checkState(!isInputChannelShare... | @Test
void testMultipleInputWatermarkStatusToggling() throws Exception {
StatusWatermarkOutput valveOutput = new StatusWatermarkOutput();
StatusWatermarkValve valve = new StatusWatermarkValve(2);
// this also implicitly verifies that all input channels start as active
valve.inputWat... |
public void fillMaxSpeed(Graph graph, EncodingManager em) {
// In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info,
// but now we have and can fill the country-dependent max_speed value where missing.
EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(... | @Test
public void testCityGermany() {
ReaderWay way = new ReaderWay(0L);
way.setTag("country", Country.DEU);
way.setTag("highway", "primary");
EdgeIteratorState edge = createEdge(way).set(urbanDensity, CITY);
calc.fillMaxSpeed(graph, em);
assertEquals(50, edge.get(max... |
@Override
public V getNow(V valueIfAbsent) {
// if there is an explicit value set, we use that
if (result != null) {
return (V) result;
}
// if there already is a deserialized value set, use it.
if (deserializedValue != VOID) {
return (V) deserialized... | @Test
public void getNow_whenDoneReturnValue() {
invocationFuture.complete(response);
assertTrue(delegatingFuture.isDone());
assertEquals(DESERIALIZED_VALUE, delegatingFuture.getNow(DESERIALIZED_DEFAULT_VALUE));
} |
public static Storage getStorageType(String hiveSdLocation) {
if (hiveSdLocation.startsWith(StorageType.S3.name().toLowerCase())) {
return new S3Storage();
} else if (hiveSdLocation.startsWith(StorageType.OSS.name().toLowerCase())) {
return new OSSStorage();
} else if (hi... | @Test
void testStorageType() {
STORAGE_MAP
.entrySet()
.forEach(
storageMapEntry -> {
Class<? extends Storage> expectedStorageClass =
storageMapEntry.getValue();
... |
public static String SHA512(String data) {
return SHA512(data.getBytes());
} | @Test
public void testSHA512() throws Exception {
String biezhiSHA512 = "cf3b5d0ed88f7945edf687d730b9b7d8e7817c5dcff1b1907c77a8bf6ae8d85fd8e1c7973ef5a6391df6cfb647f891c19ccf3a7f21ecdc7ca18322131aba5cc6";
Assert.assertEquals(
biezhiSHA512,
EncryptKit.SHA512("biezhi")
... |
@Override
public <T> ListenableFuture<PluginExecutionResult<T>> executeAsync(
PluginExecutorConfig<T> executorConfig) {
// Executes the core plugin logic within the thread pool.
return FluentFuture.from(
pluginExecutionThreadPool.submit(
() -> {
executionSto... | @Test
public void executeAsync_whenFailedWithPluginExecutionException_returnsFailedResult()
throws ExecutionException, InterruptedException {
PluginExecutorConfig<String> executorConfig =
PluginExecutorConfig.<String>builder()
.setMatchedPlugin(FAKE_MATCHING_RESULT)
.setPlugi... |
@Override
public void accept(MetadataShellState state) {
String fullGlob = glob.startsWith("/") ? glob :
state.workingDirectory() + "/" + glob;
List<String> globComponents =
CommandUtils.stripDotPathComponents(CommandUtils.splitPath(fullGlob));
MetadataNode root = sta... | @Test
public void testNotFoundGlob() {
InfoConsumer consumer = new InfoConsumer();
GlobVisitor visitor = new GlobVisitor("epsilon", consumer);
visitor.accept(DATA);
assertEquals(Optional.empty(), consumer.infos);
} |
public void setUuids(Set<String> uuids) {
requireNonNull(uuids, "Uuids cannot be null");
checkState(this.uuids == null, "Uuids have already been initialized");
this.uuids = new HashSet<>(uuids);
} | @Test
public void fail_with_ISE_when_setting_uuids_twice() {
assertThatThrownBy(() -> {
sut.setUuids(newHashSet("ABCD"));
sut.setUuids(newHashSet("EFGH"));
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Uuids have already been initialized");
} |
@Override
public void setViewActivity(View view, Activity activity) {
} | @Test
public void setViewActivity() {
View view = new View(mApplication);
mSensorsAPI.setViewActivity(view, new EmptyActivity());
Object tag = view.getTag(R.id.sensors_analytics_tag_view_activity);
Assert.assertNull(tag);
} |
private RemotingCommand getBrokerHaStatus(ChannelHandlerContext ctx, RemotingCommand request) {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
HARuntimeInfo runtimeInfo = this.brokerController.getMessageStore().getHARuntimeInfo();
if (runtimeInfo != null) {
... | @Test
public void testGetBrokerHaStatus() throws RemotingCommandException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_HA_STATUS,null);
RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request);
assertThat(response.getC... |
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetLongSchemaForLongClass() {
assertThat(
UdfUtil.getSchemaFromType(Long.class),
equalTo(ParamTypes.LONG)
);
} |
public ClientAuth getClientAuth() {
String clientAuth = getString(SSL_CLIENT_AUTHENTICATION_CONFIG);
if (originals().containsKey(SSL_CLIENT_AUTH_CONFIG)) {
if (originals().containsKey(SSL_CLIENT_AUTHENTICATION_CONFIG)) {
log.warn(
"The {} configuration is deprecated. Since a value has... | @Test
public void shouldUseClientAuthIfNoClientAuthenticationProvidedNone() {
// Given:
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.put(KsqlRestConfig.SSL_CLIENT_AUTH_CONFIG,
false)
.build());
// When:
final ClientAuth clientAut... |
public Iterator<TrainTestFold<T>> split(Dataset<T> dataset, boolean shuffle) {
int nsamples = dataset.size();
if (nsamples == 0) {
throw new IllegalArgumentException("empty input data");
}
if (nsplits > nsamples) {
throw new IllegalArgumentException("cannot have n... | @Test
public void testKFolderKDoesNotDivideN() {
int n = 52;
int nsplits = 10;
Dataset<MockOutput> data = getData(n);
int expectTestSize = n/nsplits;
int expectTrainSize = n-expectTestSize;
KFoldSplitter<MockOutput> kf = new KFoldSplitter<>(nsplits, 3);
Iterat... |
void prepareAndDumpMetadata(String taskId) {
Map<String, String> metadata = new LinkedHashMap<>();
metadata.put("projectKey", moduleHierarchy.root().key());
metadata.put("serverUrl", server.getPublicRootUrl());
metadata.put("serverVersion", server.getVersion());
properties.branch().ifPresent(branch... | @Test
public void dump_public_url_if_defined_for_branches() throws IOException {
when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
when(branchConfiguration.branchType()).thenReturn(BRANCH);
when(branchConfiguration.branchName()).thenReturn("branch-6.7");
ReportPublisher und... |
@Override
protected String buildUndoSQL() {
TableRecords beforeImage = sqlUndoLog.getBeforeImage();
List<Row> beforeImageRows = beforeImage.getRows();
if (CollectionUtils.isEmpty(beforeImageRows)) {
// TODO
throw new ShouldNeverHappenException("Invalid UNDO LOG");
... | @Test
public void buildUndoSQL() {
String sql = executor.buildUndoSQL().toLowerCase();
Assertions.assertNotNull(sql);
Assertions.assertTrue(sql.contains("update"));
Assertions.assertTrue(sql.contains("id"));
Assertions.assertTrue(sql.contains("age"));
} |
@Override
public String getPath() {
var fullPath = request.getRequestURI();
// it shouldn't be null, but in case it is, it's better to return empty string
if (fullPath == null) {
return Pac4jConstants.EMPTY_STRING;
}
// very strange use case
if (fullPath.s... | @Test
public void testGetPathFullpathContext() {
when(request.getRequestURI()).thenReturn(CTX_PATH);
when(request.getContextPath()).thenReturn(CTX);
WebContext context = new JEEContext(request, response);
assertEquals(PATH, context.getPath());
} |
@VisibleForTesting
Properties getTemplateBindings(String userName) {
Properties k8sProperties = new Properties();
// k8s template properties
k8sProperties.put("zeppelin.k8s.interpreter.user", String.valueOf(userName).trim());
k8sProperties.put("zeppelin.k8s.interpreter.namespace", getInterpreterNames... | @Test
void testSparkPodResourcesMemoryOverhead() {
// given
Properties properties = new Properties();
properties.put("spark.driver.memory", "1g");
properties.put("spark.driver.memoryOverhead", "256m");
properties.put("spark.driver.cores", "5");
Map<String, String> envs = new HashMap<>();
e... |
@Override
public void deleteLevel(Long id) {
// 校验存在
validateLevelExists(id);
// 校验分组下是否有用户
validateLevelHasUser(id);
// 删除
memberLevelMapper.deleteById(id);
} | @Test
public void testDeleteLevel_success() {
// mock 数据
MemberLevelDO dbLevel = randomPojo(MemberLevelDO.class);
memberlevelMapper.insert(dbLevel);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbLevel.getId();
// 调用
levelService.deleteLevel(id);
// 校验数据不存在了... |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void prefixConverterSmoke() {
String pattern = "%prefix(%logger) %message";
pl.setPattern(pattern);
pl.start();
String val = pl.doLayout(makeLoggingEvent("hello", null));
assertEquals("logger=" + logger.getName() + " hello", val);
} |
public static void scale(File srcImageFile, File destImageFile, float scale) {
BufferedImage image = null;
try {
image = read(srcImageFile);
scale(image, destImageFile, scale);
} finally {
flush(image);
}
} | @Test
@Disabled
public void scaleByWidthAndHeightTest() {
ImgUtil.scale(FileUtil.file("f:/test/aaa.jpg"), FileUtil.file("f:/test/aaa_result.jpg"), 100, 400, Color.BLUE);
} |
public void recordMetric(long time, String command,
String user, long delta) {
RollingWindow window = getRollingWindow(command, user);
window.incAt(time, delta);
} | @Test
public void testTotal() throws Exception {
Configuration config = new Configuration();
config.setInt(DFSConfigKeys.NNTOP_BUCKETS_PER_WINDOW_KEY, 1);
config.setInt(DFSConfigKeys.NNTOP_NUM_USERS_KEY, N_TOP_USERS);
int period = 10;
RollingWindowManager rollingWindowManager =
new Rolling... |
@Override
public VersioningConfiguration getConfiguration(final Path file) throws BackgroundException {
final Path bucket = containerService.getContainer(file);
if(cache.contains(bucket)) {
return cache.get(bucket);
}
try {
final S3BucketVersioningStatus statu... | @Test
public void testGetConfigurationEnabled() throws Exception {
final VersioningConfiguration configuration
= new S3VersioningFeature(session, new S3AccessControlListFeature(session)).getConfiguration(new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.... |
@Override
public HandlerStatus onWrite() {
compactOrClear(dst);
try {
for (; ; ) {
if (packet == null) {
packet = src.get();
if (packet == null) {
// everything is processed, so we are done
... | @Test
public void whenNotEnoughSpace() {
final Packet packet = new Packet(serializationService.toBytes(new byte[2000]));
ByteBuffer dst = ByteBuffer.allocate(1000);
dst.flip();
PacketSupplier src = new PacketSupplier();
src.queue.add(packet);
encoder.dst(dst);
... |
protected void setUpJettyOptions( Node node ) {
Map<String, String> jettyOptions = parseJettyOptions( node );
if ( jettyOptions != null && jettyOptions.size() > 0 ) {
for ( Entry<String, String> jettyOption : jettyOptions.entrySet() ) {
System.setProperty( jettyOption.getKey(), jettyOption.getVal... | @Test
public void testDoNotSetUpJettyOptionsAsSystemParameters_WhenNoOptionsNode() throws KettleXMLException {
Node configNode = getConfigNode( getConfigWithNoOptionsNode() );
slServerConfig.setUpJettyOptions( configNode );
assertFalse( "There should not be any jetty option but it is here: " + EXPECTED... |
public static int gt0(int value, String name) {
return (int) gt0((long) value, name);
} | @Test(expected = IllegalArgumentException.class)
public void checkGTZeroLessThanZero() {
Check.gt0(-1, "test");
} |
private Impulse() {} | @Test
@Category({ValidatesRunner.class, UsesImpulse.class})
public void testImpulse() {
PCollection<Integer> result =
p.apply(Impulse.create())
.apply(
FlatMapElements.into(TypeDescriptors.integers())
.via(impulse -> Arrays.asList(1, 2, 3)));
PAssert.t... |
public void close() {
close(Long.MAX_VALUE, false);
} | @Test
public void shouldThrowOnNegativeTimeoutForClose() throws Exception {
prepareStreams();
prepareStreamThread(streamThreadOne, 1);
prepareStreamThread(streamThreadTwo, 2);
prepareTerminableThread(streamThreadOne);
try (final KafkaStreams streams = new KafkaStreams(getBui... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.