focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String getPath(ApplicationId id) {
return getPath(id, false);
} | @Test
void testGetPathApplicationIdString() {
assertEquals("/proxy/application_6384623_0005",
ProxyUriUtils.getPath(BuilderUtils.newApplicationId(6384623l, 5), null));
assertEquals("/proxy/application_6384623_0005/static/app",
ProxyUriUtils.getPath(BuilderUtils.newApplicationId(6384623l, 5), "... |
public synchronized <K, V> KStream<K, V> stream(final String topic) {
return stream(Collections.singleton(topic));
} | @Test
public void shouldThrowWhenSubscribedToATopicWithSetAndUnsetResetPolicies() {
builder.stream("topic", Consumed.with(AutoOffsetReset.EARLIEST));
builder.stream("topic");
assertThrows(TopologyException.class, builder::build);
} |
@GET
@Path("/{connector}/tasks-config")
@Operation(deprecated = true, summary = "Get the configuration of all tasks for the specified connector")
public Map<ConnectorTaskId, Map<String, String>> getTasksConfig(
final @PathParam("connector") String connector) throws Throwable {
log.warn("... | @Test
public void testGetTasksConfig() throws Throwable {
final ConnectorTaskId connectorTask0 = new ConnectorTaskId(CONNECTOR_NAME, 0);
final Map<String, String> connectorTask0Configs = new HashMap<>();
connectorTask0Configs.put("connector-task0-config0", "123");
connectorTask0Confi... |
@Override
public void start() {
this.all = registry.meter(name(getName(), "all"));
this.trace = registry.meter(name(getName(), "trace"));
this.debug = registry.meter(name(getName(), "debug"));
this.info = registry.meter(name(getName(), "info"));
this.warn = registry.meter(nam... | @Test
public void usesRegistryFromProperty() {
SharedMetricRegistries.add("something_else", registry);
System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else");
final InstrumentedAppender shared = new InstrumentedAppender();
shared.start();
when(event... |
@Udf
public String rpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldReturnNullForNegativeLengthString() {
final String result = udf.rpad("foo", -1, "bar");
assertThat(result, is(nullValue()));
} |
public static <T, K> AggregateOperation1<T, Map<K, List<T>>, Map<K, List<T>>> groupingBy(
FunctionEx<? super T, ? extends K> keyFn
) {
checkSerializable(keyFn, "keyFn");
return groupingBy(keyFn, toList());
} | @Test
public void when_groupingBy_withSameKey() {
Entry<String, Integer> entryA = entry("a", 1);
validateOpWithoutDeduct(
groupingBy(entryKey()),
identity(),
entryA,
entryA,
asMap("a", singletonList(entryA)),
... |
public static Optional<DynamicTableSink> getDynamicTableSink(
ContextResolvedTable contextResolvedTable,
LogicalTableModify tableModify,
CatalogManager catalogManager) {
final FlinkContext context = ShortcutUtils.unwrapContext(tableModify.getCluster());
CatalogBaseTa... | @Test
public void testGetDynamicTableSink() {
// create a table with connector = test-update-delete
Map<String, String> options = new HashMap<>();
options.put("connector", "test-update-delete");
CatalogTable catalogTable = createTestCatalogTable(options);
ObjectIdentifier tab... |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Retain Key Ordering cannot be altered")
public void testMergeDifferentRetainKeyOrdering() {
FunctionConfig functionConfig = createFunctionConfig();
FunctionConfig newFunctionConfig = createUpdatedFunctionCo... |
@Override
public Long createNotifyTemplate(NotifyTemplateSaveReqVO createReqVO) {
// 校验站内信编码是否重复
validateNotifyTemplateCodeDuplicate(null, createReqVO.getCode());
// 插入
NotifyTemplateDO notifyTemplate = BeanUtils.toBean(createReqVO, NotifyTemplateDO.class);
notifyTemplate.se... | @Test
public void testCreateNotifyTemplate_success() {
// 准备参数
NotifyTemplateSaveReqVO reqVO = randomPojo(NotifyTemplateSaveReqVO.class,
o -> o.setStatus(randomCommonStatus()))
.setId(null); // 防止 id 被赋值
// 调用
Long notifyTemplateId = notifyTemplateSer... |
@Override
public Predicate<FileInfo> get() {
long currentTimeMS = System.currentTimeMillis();
Interval interval = Interval.between(currentTimeMS, currentTimeMS + 1);
return FileInfo -> {
try {
return interval.intersect(mInterval.add(mGetter.apply(FileInfo))).isValid();
} catch (Runtime... | @Test
public void testTimePredicateFactories() {
FileFilter filter = FileFilter.newBuilder().setName("unmodifiedFor").setValue("1s").build();
long timestamp = System.currentTimeMillis();
FileInfo info = new FileInfo();
info.setLastModificationTimeMs(timestamp);
assertFalse(FilePredicate.create(fi... |
public FEELFnResult<List> invoke(@ParameterName( "list" ) Object list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
// spec requires us to return a new list
final List<Object> result = new ArrayLi... | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(flattenFunction.invoke(null), InvalidParametersEvent.class);
} |
@Override
public DescribeConfigsResult describeConfigs(Collection<ConfigResource> configResources, final DescribeConfigsOptions options) {
// Partition the requested config resources based on which broker they must be sent to with the
// null broker being used for config resources which can be obtai... | @Test
public void testDescribeClientMetricsConfigs() throws Exception {
ConfigResource resource = new ConfigResource(ConfigResource.Type.CLIENT_METRICS, "sub1");
ConfigResource resource1 = new ConfigResource(ConfigResource.Type.CLIENT_METRICS, "sub2");
try (AdminClientUnitTestEnv env = mockC... |
@Override
public void subscribe(Subscriber<? super T>[] subscribers) {
if (!validate(subscribers)) {
return;
}
@SuppressWarnings("unchecked")
Subscriber<? super T>[] newSubscribers = new Subscriber[subscribers.length];
for (int i = 0; i < subscribers.length; i++) {
AutoDisposingSubscr... | @Test
public void autoDispose_withProvider() {
TestSubscriber<Integer> firstSubscriber = new TestSubscriber<>();
TestSubscriber<Integer> secondSubscriber = new TestSubscriber<>();
PublishProcessor<Integer> source = PublishProcessor.create();
CompletableSubject scope = CompletableSubject.create();
... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldThrowInconsistentValueSchemaTypeExceptionWithOverrideSchema() {
// Given:
final SchemaAndId schemaAndId = SchemaAndId.schemaAndId(SCHEMA.value(), AVRO_SCHEMA, 1);
givenStatement("CREATE STREAM source (id int key, f1 varchar) "
+ "WITH ("
+ "kafka_topic='expectedName... |
public Certificate getCertificate(Long id) {
Optional<Certificate> cert = certificateRepository.findById(id);
if (!cert.isPresent()) {
throw new NotFoundException("Could not find certificate with id: " + id);
}
return cert.get();
} | @Test
public void certificateNotFound() {
Optional<Certificate> certificateOptional = Optional.empty();
when(certificateRepositoryMock.findById(anyLong())).thenReturn(certificateOptional);
assertThrows(NotFoundException.class, () -> {
certificateServiceMock.getCertificate(anyLon... |
public static byte[] bytes(ByteBuffer buf)
{
byte[] d = new byte[buf.limit()];
buf.get(d);
return d;
} | @Test
public void testBytes()
{
byte[] array = new byte[10];
ByteBuffer buffer = ByteBuffer.wrap(array);
byte[] bytes = Utils.bytes(buffer);
assertThat(bytes, is(array));
} |
public void createIndex(DBObject keys, DBObject options) {
delegate.createIndex(new BasicDBObject(keys.toMap()), toIndexOptions(options));
} | @Test
void createIndexWithOptions() {
final var collection = jacksonCollection("simple", Simple.class);
collection.createIndex(new BasicDBObject("name", 1), new BasicDBObject("sparse", true).append("unique", true));
assertThat(mongoCollection("simple").listIndexes()).containsExactlyInAnyOrde... |
@Override
public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) {
traceIfNecessary(grpcRequest, true);
String type = grpcRequest.getMetadata().getType();
long startTime = System.nanoTime();
//server is on starting.
if (!Applicati... | @Test
void testRequestContentError() {
ApplicationUtils.setStarted(true);
Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler);
Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true);
StreamObserver<Payload> s... |
public VplsConfig getVplsWithName(String name) {
return vplss().stream()
.filter(vpls -> vpls.name().equals(name))
.findFirst()
.orElse(null);
} | @Test
public void getVplsWithName() {
assertNotNull("Configuration for VPLS not found",
vplsAppConfig.getVplsWithName(VPLS1));
assertNull("Unexpected configuration for VPLS found",
vplsAppConfig.getVplsWithName(VPLS2));
} |
void handleLostAll() {
log.debug("Closing lost active tasks as zombies.");
closeRunningTasksDirty();
removeLostActiveTasksFromStateUpdaterAndPendingTasksToInit();
if (processingMode == EXACTLY_ONCE_V2) {
activeTaskCreator.reInitializeThreadProducer();
}
} | @Test
public void shouldReInitializeThreadProducerOnHandleLostAllIfEosV2Enabled() {
final TaskManager taskManager = setUpTaskManager(ProcessingMode.EXACTLY_ONCE_V2, false);
taskManager.handleLostAll();
verify(activeTaskCreator).reInitializeThreadProducer();
} |
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof ExpiryPolicy)) {
return false;
}
var policy = (ExpiryPolicy) o;
return Objects.equals(creation, policy.getExpiryForCreation())
&& Objects.equals(update, policy.getExpiryForUpdate... | @Test
public void equals() {
assertThat(eternal.equals(eternal)).isTrue();
} |
@Override
public final ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler) {
replace(getContextOrDie(oldHandler), newName, newHandler);
return this;
} | @Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testReplaceAndForwardOutbound() throws Exception {
final BufferedTestHandler handler1 = new BufferedTestHandler();
final BufferedTestHandler handler2 = new BufferedTestHandler();
setUp(handler1);
self.event... |
@Override
public ListOffsetsResult listOffsets(Map<TopicPartition, OffsetSpec> topicPartitionOffsets,
ListOffsetsOptions options) {
AdminApiFuture.SimpleAdminApiFuture<TopicPartition, ListOffsetsResultInfo> future =
ListOffsetsHandler.newFuture(topicParti... | @Test
public void testListOffsetsRetriableErrors() throws Exception {
Node node0 = new Node(0, "localhost", 8120);
Node node1 = new Node(1, "localhost", 8121);
List<Node> nodes = asList(node0, node1);
List<PartitionInfo> pInfos = new ArrayList<>();
pInfos.add(new PartitionIn... |
@Override
public Serializer<T> serializer() {
final Serializer<T> serializer = delegate.serializer();
return (topic, data) -> serializer.serialize(this.topic, data);
} | @Test
public void shouldUseDelegateSerializerWithStaticTopic() {
// When:
final byte[] serialized = staticSerde.serializer().serialize(SOURCE_TOPIC, SOME_OBJECT);
// Then:
verify(delegateS).serialize(STATIC_TOPIC, SOME_OBJECT);
assertThat(serialized, is(SOME_BYTES));
verifyNoMoreInteractions(... |
public static HttpClient newConnection() {
return new HttpClientConnect(new HttpConnectionProvider(ConnectionProvider.newConnection()));
} | @Test
public void testSharedNameResolver_NotSharedClientNoConnectionPool() throws InterruptedException {
doTestSharedNameResolver(HttpClient.newConnection(), false);
} |
@Override
public int getMaxParallelism() {
return this.maxParallelism;
} | @Test
void setAutoMax() {
DefaultVertexParallelismInfo info =
new DefaultVertexParallelismInfo(
1, ExecutionConfig.PARALLELISM_AUTO_MAX, ALWAYS_VALID);
assertThat(info.getMaxParallelism())
.isEqualTo(KeyGroupRangeAssignment.UPPER_BOUND_MAX_PAR... |
@Override
public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) {
Objects.requireNonNull(intentOperationContext);
Optional<IntentData> toUninstall = intentOperationContext.toUninstall();
Optional<IntentData> toInstall = intentOperationContext.toInstall();
... | @Test
public void testGroupExistError() {
// group exists, retry by using add to exist
intentInstallCoordinator = new TestIntentInstallCoordinator();
installer.intentInstallCoordinator = intentInstallCoordinator;
errors = ImmutableList.of(GROUPEXISTS);
installer.flowObjective... |
@VisibleForTesting
static String getActualColumnName(String rawTableName, String columnName, @Nullable Map<String, String> columnNameMap,
boolean ignoreCase) {
if ("*".equals(columnName)) {
return columnName;
}
String columnNameToCheck = trimTableName(rawTableName, columnName, ignoreCase);
... | @Test
public void testGetActualColumnNameCaseSensitive() {
Map<String, String> columnNameMap = new HashMap<>();
columnNameMap.put("student_name", "student_name");
String actualColumnName =
BaseSingleStageBrokerRequestHandler.getActualColumnName("mytable", "mytable.student_name", columnNameMap,
... |
public static List<Transformation<?>> optimize(List<Transformation<?>> transformations) {
final Map<Transformation<?>, Set<Transformation<?>>> outputMap =
buildOutputMap(transformations);
final LinkedHashSet<Transformation<?>> chainedTransformations = new LinkedHashSet<>();
fina... | @Test
void testMultipleChainedOperators() {
ExternalPythonKeyedProcessOperator<?> keyedProcessOperator1 =
createKeyedProcessOperator(
"f1", new RowTypeInfo(Types.INT(), Types.INT()), Types.STRING());
ExternalPythonProcessOperator<?, ?> processOperator1 =
... |
@VisibleForTesting
static SwitchGenerationCase checkSwitchGenerationCase(Type type, List<RowExpression> values)
{
if (values.size() > 32) {
// 32 is chosen because
// * SET_CONTAINS performs worst when smaller than but close to power of 2
// * Benchmark shows performa... | @Test
public void testDate()
{
List<RowExpression> values = new ArrayList<>();
values.add(constant(1L, DATE));
values.add(constant(2L, DATE));
values.add(constant(3L, DATE));
assertEquals(checkSwitchGenerationCase(DATE, values), DIRECT_SWITCH);
for (long i = 4; i... |
@Override
public Set<GrokPattern> bulkLoad(Collection<String> patternIds) {
return patternIds.stream()
.map(store::get)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
} | @Test
public void bulkLoad() throws Exception {
GrokPattern pattern1 = service.save(GrokPattern.create("NAME1", ".*"));
GrokPattern pattern2 = service.save(GrokPattern.create("NAME2", ".*"));
GrokPattern pattern3 = service.save(GrokPattern.create("NAME3", ".*"));
assertThat(service.... |
public static L4ModificationInstruction modTcpDst(TpPort port) {
checkNotNull(port, "Dst TCP port cannot be null");
return new ModTransportPortInstruction(L4SubType.TCP_DST, port);
} | @Test
public void testModTcpDstMethod() {
final Instruction instruction = Instructions.modTcpDst(tpPort1);
final L4ModificationInstruction.ModTransportPortInstruction modTransportPortInstruction =
checkAndConvert(instruction, Instruction.Type.L4MODIFICATION,
... |
public static Details create(String template, Object... args) {
return Details.builder()
.status(MaestroRuntimeException.Code.INTERNAL_ERROR)
.message(String.format(template, args))
.build();
} | @Test
public void testCreateWithStackTrace() {
Exception exception = new Exception(new Exception(new Exception("test")));
Details details = Details.create(exception, false, "test-msg");
assertEquals(MaestroRuntimeException.Code.INTERNAL_ERROR, details.getStatus());
assertEquals("test-msg", details.get... |
public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
if (index + substring.length() > str.length()) {
return false;
}
for (int i = 0; i < substring.length(); i++) {
if (str.charAt(index + i) != substring.charAt(i)) {
... | @Test
public void testSubstringMatchWithPositive() {
assertFalse(StringUtil.substringMatch("", 4770, ""));
} |
@Override
protected ExecuteContext doAfter(ExecuteContext context) {
final Object object = context.getObject();
if (object instanceof LoadBalancerCacheManager) {
GraceContext.INSTANCE.getGraceShutDownManager().setLoadBalancerCacheManager(object);
}
return context;
} | @Test
public void testCacheManager() {
final SpringCacheManagerInterceptor springCacheManagerInterceptor = new SpringCacheManagerInterceptor();
final LoadBalancerCacheManager cacheManager = Mockito.mock(LoadBalancerCacheManager.class);
final ExecuteContext executeContext = ExecuteContext
... |
@Transactional
@ApolloAuditLog(type = OpType.CREATE, name = "App.create")
public App createAppAndAddRolePermission(
App app, Set<String> admins
) {
App createdApp = this.createAppInLocal(app);
publisher.publishEvent(new AppCreationEvent(createdApp));
if (!CollectionUtils.isEmpty(admins)) {
... | @Test
void createAppAndAddRolePermissionButOwnerNotExists() {
Mockito.when(userService.findByUserId(Mockito.any()))
.thenReturn(null);
assertThrows(
BadRequestException.class,
() -> appService.createAppAndAddRolePermission(new App(), Collections.emptySet())
);
} |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testReservedSpdySynReplyFrameBits() throws Exception {
short type = 2;
byte flags = 0;
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type,... |
public static String findBsn(List<Container> categorieList){
return findValue(categorieList, CATEGORIE_IDENTIFICATIENUMMERS, ELEMENT_BURGERSERVICENUMMER);
} | @Test
public void testFindBsn() {
assertThat(CategorieUtil.findBsn(createFullCategories()), is("burgerservicenummer"));
} |
public boolean isTransferSupported() {
requireNotStale();
return Optional.ofNullable(getPrimaryDevice().getCapabilities())
.map(Device.DeviceCapabilities::transfer)
.orElse(false);
} | @Test
void testIsTransferSupported() {
final Device transferCapablePrimaryDevice = mock(Device.class);
final Device nonTransferCapablePrimaryDevice = mock(Device.class);
final Device transferCapableLinkedDevice = mock(Device.class);
final DeviceCapabilities transferCapabilities = mock(DeviceCapabilit... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void atLiteralDate() {
String inputExpression = "@\"2016-07-29\"";
BaseNode bool = parse(inputExpression);
assertThat(bool).isInstanceOf(AtLiteralNode.class);
assertThat(bool.getResultType()).isEqualTo(BuiltInType.DATE);
assertLocation(inputExpression, bool);
} |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testGreaterThanEquals() {
UnboundPredicate<Integer> expected =
org.apache.iceberg.expressions.Expressions.greaterThanOrEqual("field1", 1);
Optional<org.apache.iceberg.expressions.Expression> actual =
FlinkFilters.convert(resolve(Expressions.$("field1").isGreaterOrEqual(Expre... |
public ProtocolBuilder corethreads(Integer corethreads) {
this.corethreads = corethreads;
return getThis();
} | @Test
void corethreads() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.corethreads(10);
Assertions.assertEquals(10, builder.build().getCorethreads());
} |
@Override
public DescribeTopicsResult describeTopics(final TopicCollection topics, DescribeTopicsOptions options) {
if (topics instanceof TopicIdCollection)
return DescribeTopicsResult.ofTopicIds(handleDescribeTopicsByIds(((TopicIdCollection) topics).topicIds(), options));
else if (topic... | @Test
public void testDescribeTopicPartitionsApiWithoutAuthorizedOps() throws ExecutionException, InterruptedException {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
String topicName0 = "test-0";
Uuid... |
public Optional<Projection> createProjection(final ProjectionSegment projectionSegment) {
if (projectionSegment instanceof ShorthandProjectionSegment) {
return Optional.of(createProjection((ShorthandProjectionSegment) projectionSegment));
}
if (projectionSegment instanceof ColumnProj... | @Test
void assertCreateProjectionWhenProjectionSegmentInstanceOfAggregationDistinctProjectionSegmentAndAggregationTypeIsAvg() {
AggregationDistinctProjectionSegment aggregationDistinctProjectionSegment = new AggregationDistinctProjectionSegment(0, 10, AggregationType.AVG, "(1)", "distinctExpression");
... |
public void writeIntLenenc(final long value) {
if (value < 0xfb) {
byteBuf.writeByte((int) value);
return;
}
if (value < Math.pow(2D, 16D)) {
byteBuf.writeByte(0xfc);
byteBuf.writeShortLE((int) value);
return;
}
if (valu... | @Test
void assertWriteIntLenencWithTwoBytes() {
new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).writeIntLenenc(Double.valueOf(Math.pow(2D, 16D)).longValue() - 1L);
verify(byteBuf).writeByte(0xfc);
verify(byteBuf).writeShortLE(Double.valueOf(Math.pow(2D, 16D)).intValue() - 1);
} |
public static GeneratedResources getGeneratedResourcesObject(String generatedResourcesString) throws JsonProcessingException {
return objectMapper.readValue(generatedResourcesString, GeneratedResources.class);
} | @Test
void getGeneratedResourcesObjectFromFile() throws Exception {
String fileName = "IndexFile.test_json";
URL resource = Thread.currentThread().getContextClassLoader().getResource(fileName);
assert resource != null;
IndexFile indexFile = new IndexFile(new File(resource.toURI()));
... |
@Override
protected Object getTargetObject(boolean key) {
Object targetObject;
if (key) {
// keyData is never null
if (keyData.isPortable() || keyData.isJson() || keyData.isCompact()) {
targetObject = keyData;
} else {
targetObject ... | @Test
public void testGetTargetObject_givenValueIsDataAndPortable_whenKeyFlagIsFalse_thenReturnValueData() {
Data key = serializationService.toData("indexedKey");
Data value = serializationService.toData(new PortableEmployee(30, "peter"));
QueryableEntry entry = createEntry(key, value, newEx... |
@ApiOperation(value = "Get Edge Events (getEdgeEvents)",
notes = "Returns a page of edge events for the requested edge. " +
PAGE_DATA_PARAMETERS)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping(value = "/edge/{edgeId}/events")
public PageData<EdgeEvent> getEdgeEvent... | @Test
public void testGetEdgeEvents() throws Exception {
Edge edge = constructEdge("TestEdge", "default");
edge = doPost("/api/edge", edge, Edge.class);
final EdgeId edgeId = edge.getId();
awaitForEdgeTemplateRootRuleChainToAssignToEdge(edgeId);
// simulate edge activation... |
@Override
public ServiceRecord resolve(String path) throws PathNotFoundException,
NoRecordException, InvalidRecordException, IOException {
// Read the entire file into byte array, should be small metadata
Long size = fs.getFileStatus(formatDataPath(path)).getLen();
byte[] bytes = new byte[size.intV... | @Test
public void testResolve() throws IOException {
ServiceRecord record = createRecord("0");
registry.bind("test/registryTestNode", record, 1);
Assert.assertTrue(fs.exists(new Path("test/registryTestNode/_record")));
System.out.println("Read record that exists");
ServiceRecord readRecord = regi... |
static public FileSize valueOf(String fileSizeStr) {
Matcher matcher = FILE_SIZE_PATTERN.matcher(fileSizeStr);
long coefficient;
if (matcher.matches()) {
String lenStr = matcher.group(DOUBLE_GROUP);
String unitStr = matcher.group(UNIT_GROUP);
long lenValue = Long.valueOf(lenStr);
i... | @Test
public void testValueOf() {
{
FileSize fs = FileSize.valueOf("8");
assertEquals(8, fs.getSize());
}
{
FileSize fs = FileSize.valueOf("8 kbs");
assertEquals(8*KB_CO, fs.getSize());
}
{
FileSize fs = FileSize.valueOf("8 kb");
assertEquals(8*KB_CO, fs... |
@RequestMapping("/push/state")
public ObjectNode pushState(@RequestParam(required = false) boolean detail,
@RequestParam(required = false) boolean reset) {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
int failedPushCount = MetricsMonitor.getFailedPushMonitor().get();
i... | @Test
void testPushState() {
MetricsMonitor.resetPush();
ObjectNode objectNode = operatorController.pushState(true, true);
assertTrue(objectNode.toString().contains("succeed\":0"));
} |
public <T> void unregister(MeshRuleListener subscriber) {
meshRuleDispatcher.unregister(subscriber);
} | @Test
void unregister() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
StandardMeshRuleRouter standardMeshRuleRouter1 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
StandardMeshRuleRouter standardMeshRuleRouter2 = Mockito.spy(new StandardMesh... |
void release() {
synchronized (allBuffers) {
while (!allBuffers.isEmpty()) {
allBuffers.poll().f0.recycleBuffer();
}
}
} | @Test
void testRelease() {
SubpartitionDiskCacheManager subpartitionDiskCacheManager =
new SubpartitionDiskCacheManager();
Buffer buffer = BufferBuilderTestUtils.buildSomeBuffer();
subpartitionDiskCacheManager.append(buffer);
List<Tuple2<Buffer, Integer>> bufferAndInd... |
public ConfigTransformerResult transform(Map<String, String> configs) {
Map<String, Map<String, Set<String>>> keysByProvider = new HashMap<>();
Map<String, Map<String, Map<String, String>>> lookupsByProvider = new HashMap<>();
// Collect the variables from the given configs that need transforma... | @Test
public void testReplaceVariableWithTTL() {
ConfigTransformerResult result = configTransformer.transform(Collections.singletonMap(MY_KEY, "${test:testPath:testKeyWithTTL}"));
Map<String, String> data = result.data();
Map<String, Long> ttls = result.ttls();
assertEquals(TEST_RESU... |
public static String getFullElapsedTime(final long delta) {
if (delta < Duration.ofSeconds(1).toMillis()) {
return String.format("%d %s", delta, delta == 1 ? LocaleUtils.getLocalizedString("global.millisecond") : LocaleUtils.getLocalizedString("global.milliseconds"));
} else if (delta < Dura... | @Test
public void testElapsedTimeInDays() throws Exception {
assertThat(StringUtils.getFullElapsedTime(Duration.ofDays(1)), is("1 day"));
assertThat(StringUtils.getFullElapsedTime(Duration.ofDays(1).plus(Duration.ofHours(1)).plus(Duration.ofMinutes(1)).plus(Duration.ofSeconds(1)).plus(Duration.ofMil... |
@SneakyThrows({InterruptedException.class, ExecutionException.class})
@Override
public List<String> getChildrenKeys(final String key) {
String prefix = key + PATH_SEPARATOR;
ByteSequence prefixByteSequence = ByteSequence.from(prefix, StandardCharsets.UTF_8);
GetOption getOption = GetOpti... | @Test
void assertGetChildrenKeysWhenThrowInterruptedException() throws ExecutionException, InterruptedException {
doThrow(InterruptedException.class).when(getFuture).get();
try {
repository.getChildrenKeys("/key/key1");
// CHECKSTYLE:OFF
} catch (final Exception ex) {... |
public static Properties getProperties(File file) throws AnalysisException {
try (BufferedReader utf8Reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
return getProperties(utf8Reader);
} catch (IOException | IllegalArgumentException e) {
throw new Analysi... | @Test
public void getProperties_should_support_folding_in_headerValue() throws IOException {
String payload = "Metadata-Version: 2\r\n"
+ " .2\r\n"
+ "Description: My value\r\n"
+ " contains a \r\n"
+ " : co... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testQuantifiedComparisonExpression()
{
analyze("SELECT * FROM t1 WHERE t1.a <= ALL (VALUES 10, 20)");
assertFails(MULTIPLE_FIELDS_FROM_SUBQUERY, "SELECT * FROM t1 WHERE t1.a = ANY (SELECT 1, 2)");
assertFails(TYPE_MISMATCH, "SELECT * FROM t1 WHERE t1.a = SOME (VALUES ('... |
ImmutableList<PayloadDefinition> validatePayloads(List<PayloadDefinition> payloads) {
for (PayloadDefinition p : payloads) {
checkArgument(p.hasName(), "Parsed payload does not have a name.");
checkArgument(
p.getInterpretationEnvironment()
!= PayloadGeneratorConfig.Interpretatio... | @Test
public void validatePayloads_withCallbackPayloadWithoutUrlToken_throwsException()
throws IOException {
PayloadDefinition p =
goodCallbackDefinition.setPayloadString(StringValue.of("my payload")).build();
Throwable thrown =
assertThrows(
IllegalArgumentException.class, ... |
@Override
public double quantile(double p) {
if (p < 0.0 || p > 1.0) {
throw new IllegalArgumentException("Invalid p: " + p);
}
return 2 * Gamma.inverseRegularizedIncompleteGamma(0.5 * nu, p);
} | @Test
public void testQuantile() {
System.out.println("quantile");
ChiSquareDistribution instance = new ChiSquareDistribution(20);
instance.rand();
assertEquals(0.0, instance.quantile(0), 1E-7);
assertEquals(12.44261, instance.quantile(0.1), 1E-5);
assertEquals(14.578... |
@Override
public OptimizeTableStatement getSqlStatement() {
return (OptimizeTableStatement) super.getSqlStatement();
} | @Test
void assertNewInstance() {
MySQLOptimizeTableStatement sqlStatement = new MySQLOptimizeTableStatement();
sqlStatement.getTables().add(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("tbl_1"))));
OptimizeTableStatementContext actual = new OptimizeTableStatementCont... |
@Override
protected Future<KafkaMirrorMakerStatus> createOrUpdate(Reconciliation reconciliation, KafkaMirrorMaker assemblyResource) {
String namespace = reconciliation.namespace();
KafkaMirrorMakerCluster mirror;
KafkaMirrorMakerStatus kafkaMirrorMakerStatus = new KafkaMirrorMakerStatus();
... | @Test
public void testUpdateCluster(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
CrdOperator<KubernetesClient, KafkaMirrorMaker, KafkaMirrorMakerList> mockMirrorOps = supplier.mirrorMakerOperator;
DeploymentOperator mockDcOps = suppli... |
public static HttpServletResponse createRumResponseWrapper(HttpServletRequest httpRequest,
HttpServletResponse httpResponse, String requestName) {
if (HtmlInjectorServletResponseWrapper.acceptsRequest(httpRequest)) {
final HtmlToInject htmlToInject = new RumInjector(httpRequest, requestName);
return new Html... | @Test
public void testCreateRumResponseWrapper() throws IOException {
final String requestName = "test GET";
final HttpServletRequest httpRequest = createNiceMock(HttpServletRequest.class);
final HttpServletResponse httpResponse = createNiceMock(HttpServletResponse.class);
expect(httpRequest.getHeader("accept... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseStringListWithExtraDelimitersAndReturnString() {
String str = "[1, 2, 3,,,]";
SchemaAndValue result = Values.parseString(str);
assertEquals(Type.STRING, result.schema().type());
assertEquals(str, result.value());
} |
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) {
GuardedByExpression expr = BINDER.visit(exp, context);
checkGuardedBy(expr != null, String.valueOf(exp));
checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp);
return expr;
} | @Test
public void otherClass() {
assertThat(
bind(
"Test",
"Other.lock",
forSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"class Other {",
" static final O... |
public ProcResult fetchResultByFilter(HashMap<String, Expr> filter, ArrayList<OrderByPair> orderByPairs,
LimitElement limitElement) throws AnalysisException {
Preconditions.checkNotNull(db);
Preconditions.checkNotNull(schemaChangeHandler);
List<List<Com... | @Test
public void testFetchResultByFilterNull() throws AnalysisException {
BaseProcResult result = (BaseProcResult) optimizeProcDir.fetchResultByFilter(null, null, null);
List<List<String>> rows = result.getRows();
List<String> list1 = rows.get(0);
Assert.assertEquals(list1.size(), O... |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestExcept... | @Test(dataProvider = "multiplexerConfigurations")
public void testHandleSingleRequest(MultiplexerRunMode multiplexerRunMode) throws Exception
{
SynchronousRequestHandler mockHandler = createMockHandler();
MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(mockHandler, multiplexerRunMode);
Req... |
public abstract SubClusterId getApplicationHomeSubCluster(ApplicationId appId) throws Exception; | @Test
public void testGetHomeSubClusterForApp() throws YarnException {
for (int i = 0; i < numApps; i++) {
ApplicationId appId = ApplicationId.newInstance(clusterTs, i);
SubClusterId expectedSC = stateStoreTestUtil.queryApplicationHomeSC(appId);
SubClusterId cachedPC = facade.getApplicationHomeS... |
public static double getUTCTimestampWithMilliseconds() {
return getUTCTimestampWithMilliseconds(System.currentTimeMillis());
} | @Test
public void testGetUTCTimestampWithMilliseconds() {
assertTrue(Tools.getUTCTimestampWithMilliseconds() > 0.0d);
assertTrue(Tools.getUTCTimestampWithMilliseconds(Instant.now().toEpochMilli()) > 0.0d);
} |
public static String getAddress(ECKeyPair ecKeyPair) {
return getAddress(ecKeyPair.getPublicKey());
} | @Test
public void testGetAddressZeroPaddedAddress() {
String publicKey =
"0xa1b31be4d58a7ddd24b135db0da56a90fb5382077ae26b250e1dc9cd6232ce22"
+ "70f4c995428bc76aa78e522316e95d7834d725efc9ca754d043233af6ca90113";
assertEquals(Keys.getAddress(publicKey), ("01c52... |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
if (stream == null) {
throw new NullPointerException("null stream");
}
Throwable t;
boolean alive =... | @Test
public void testForkParserDoesntPreventShutdown() throws Exception {
ExecutorService service = Executors.newFixedThreadPool(1);
CountDownLatch cdl = new CountDownLatch(1);
service.submit(() -> {
try (ForkParser parser = new ForkParser(ForkParserTest.class.getClassLoader(),
... |
public void addFirst(T event) throws RejectedExecutionException {
lock.lock();
try {
if (closed) throw new RejectedExecutionException("Can't accept an event because the accumulator is closed.");
K key = event.key();
Deque<T> queue = queues.get(key);
if (q... | @Test
public void testAddFirst() {
EventAccumulator<Integer, MockEvent> accumulator = new EventAccumulator<>();
List<MockEvent> events = Arrays.asList(
new MockEvent(1, 0),
new MockEvent(1, 1),
new MockEvent(1, 2)
);
events.forEach(accumulator::a... |
static Map<Integer, List<Integer>> parseReplicaAssignment(String replicaAssignmentList) {
String[] partitionList = replicaAssignmentList.split(",");
Map<Integer, List<Integer>> ret = new LinkedHashMap<>();
for (int i = 0; i < partitionList.length; i++) {
List<Integer> brokerList = Ar... | @Test
public void testParseAssignmentPartitionsOfDifferentSize() {
assertThrows(AdminOperationException.class, () -> TopicCommand.parseReplicaAssignment("5:4:3,2:1"));
} |
@PUT
@Path("{id}/add_router_interface")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addRouterInterface(@PathParam("id") String id, InputStream input) throws IOException {
log.trace(String.format(MESSAGE_ROUTER_IFACE, "UPDATE " + id));
Stri... | @Test
public void testAddRouterInterfaceWithAdditionOperation() {
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
mockOpenstackRouterAdminService.addRouterInterface(anyObject());
replay(mockOpenstackRouterAdminService);
f... |
public boolean matches(final String keyWord) {
return p.matcher(keyWord).matches();
} | @Test
public void matches() {
Assertions.assertTrue(keyWordMatch.matches("name"));
Assertions.assertTrue(keyWordMatch.matches("test"));
Assertions.assertFalse(keyWordMatch.matches("dsaer"));
} |
public static ExpressionEvaluator compileExpression(
String expression,
List<String> argumentNames,
List<Class<?>> argumentClasses,
Class<?> returnClass) {
ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator();
expressionEvaluator.setParamete... | @Test
public void testJaninoStringCompare() throws InvocationTargetException {
String expression = "String.valueOf(\"metadata_table\").equals(__table_name__)";
List<String> columnNames = Arrays.asList("__table_name__");
List<Class<?>> paramTypes = Arrays.asList(String.class);
List<Ob... |
public static BundleDistribution bundleProcessingThreadDistribution(
String shortId, MetricName name) {
return new BundleProcessingThreadDistribution(shortId, name);
} | @Test
public void testAccurateBundleDistributionReportsValueFirstTimeWithoutMutations()
throws Exception {
Map<String, ByteString> report = new HashMap<>();
BundleDistribution bundleDistribution =
Metrics.bundleProcessingThreadDistribution(TEST_ID, TEST_NAME);
bundleDistribution.updateInterm... |
@Override
public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap,
String serviceInterface) {
if (!shouldHandle(invokers)) {
return invokers;
}
List<Object> targetInvokers;
if (routerConfig.isUseRequest... | @Test
public void testGetTargetInvokersByFlowRules() {
// initialize the routing rule
RuleInitializationUtils.initFlowMatchRule();
List<Object> invokers = new ArrayList<>();
ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0");
invokers.add(invoker1);
ApacheI... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
try {
if(new DeepboxFindFeature(session, fileid).find(folder)) {
throw new ConflictException(folder.getAbsolute());
}
final Folder upload = new Folder(... | @Test
public void testBookkeeping() throws Exception {
final DeepboxIdProvider nodeid = new DeepboxIdProvider(session);
final DeepboxDirectoryFeature directory = new DeepboxDirectoryFeature(session, nodeid);
final Path parent = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/Bookk... |
public void clearOptionsData() {
getControls();
if ( optionsParameterTree != null ) {
optionsParameterTree.getRootChildren().removeAll();
}
} | @Test
public void testClearOptionsData() throws Exception {
} |
@Override
public int getWorkerMaxCount() {
return workerThreadCount;
} | @Test
public void getWorkerMaxCount_returns_1_when_there_is_no_WorkerCountProvider() {
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION).getWorkerMaxCount()).isOne();
} |
public Collection<String> getAllClientsSubscribeService(Service service) {
return subscriberIndexes.containsKey(service) ? subscriberIndexes.get(service) : new ConcurrentHashSet<>();
} | @Test
void testGetAllClientsSubscribeService() {
Collection<String> allClientsSubscribeService = clientServiceIndexesManager.getAllClientsSubscribeService(service);
assertNotNull(allClientsSubscribeService);
assertEquals(1, allClientsSubscribeService.size());
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
String highwayValue = way.getTag("highway");
if (skipEmergency && "service".equals(highwayValue) && "emergency_access".equals(way.getTag("service")))
return;
int ... | @Test
public void testAccess() {
ReaderWay way = new ReaderWay(1);
way.setTag("highway", "primary");
EdgeIntAccess edgeIntAccess = ArrayEdgeIntAccess.createFromBytes(em.getBytesForFlags());
int edgeId = 0;
parser.handleWayTags(edgeId, edgeIntAccess, way, null);
assert... |
@Override
public PluginRuntime getPluginRuntime() {
return new PluginRuntime(getId())
.addInfo("executeTimeOut", executeTimeOut + "ms");
} | @Test
public void testGetRuntime() {
Assert.assertNotNull(plugin.getPluginRuntime());
} |
@Override
public int read() throws IOException {
if (mPosition == mLength) { // at end of file
return -1;
}
updateStreamIfNeeded();
int res = mUfsInStream.get().read();
if (res == -1) {
return -1;
}
mPosition++;
Metrics.BYTES_READ_FROM_UFS.inc(1);
return res;
} | @Test
public void readOutOfBound() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, CHUNK_SIZE);
try (FileInStream inStream = getStream(ufsPath)) {
byte[] res = new byte[CHUNK_SIZE * 2];
assertEquals(CHUNK_SIZE, inStream.read(res));
assertTrue... |
@Nullable
public static Field findPropertyField(Class<?> clazz, String fieldName) {
Field field;
try {
field = clazz.getField(fieldName);
} catch (NoSuchFieldException e) {
return null;
}
if (!Modifier.isPublic(field.getModifiers()) || Modifier.isStat... | @Test
public void when_findPropertyField_private_then_returnsNull() {
assertNull(findPropertyField(JavaFields.class, "privateField"));
} |
public List<Document> export(final String collectionName,
final List<String> exportedFieldNames,
final int limit,
final Bson dbFilter,
final List<Sort> sorts,
... | @Test
void testExportWorksCorrectlyWithSelectivePermissions() {
insertTestData();
simulateUserThatCanSeeOnlyOneDoc("0000000000000000000000c7");
final List<Document> exportedDocuments = toTest.export(TEST_COLLECTION_NAME,
List.of("name"),
10,
F... |
@Override
public Long createPost(PostSaveReqVO createReqVO) {
// 校验正确性
validatePostForCreateOrUpdate(null, createReqVO.getName(), createReqVO.getCode());
// 插入岗位
PostDO post = BeanUtils.toBean(createReqVO, PostDO.class);
postMapper.insert(post);
return post.getId();
... | @Test
public void testValidatePost_nameDuplicateForCreate() {
// mock 数据
PostDO postDO = randomPostDO();
postMapper.insert(postDO);// @Sql: 先插入出一条存在的数据
// 准备参数
PostSaveReqVO reqVO = randomPojo(PostSaveReqVO.class,
// 模拟 name 重复
o -> o.setName(postDO.ge... |
public int calculateBufferSize(long totalBufferSizeInBytes, int totalBuffers) {
checkArgument(totalBufferSizeInBytes >= 0, "Size of buffer should be non negative");
checkArgument(totalBuffers > 0, "Number of buffers should be positive");
// Since the result value is always limited by max buffer... | @Test
void testNegativeTotalSize() {
BufferSizeEMA calculator = new BufferSizeEMA(100, 200, 2);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> calculator.calculateBufferSize(-1, 1));
} |
public abstract void execute(Map<String, List<String>> parameters,
String body,
PrintWriter output) throws Exception; | @SuppressWarnings("deprecation")
@Test
void throwsExceptionWhenCallingExecuteWithoutThePostBody() throws Exception {
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
task.execute(Collections.emptyMap(), new PrintWriter(new OutputStreamWriter(System.out, UTF... |
public static Collection<String> parseTableExpressionWithoutSchema(final ShardingSphereDatabase database, final List<String> tableNames) {
ShardingSphereSchema schema = database.getSchema(database.getName());
Set<String> allTableNames = null == schema ? Collections.emptySet() : new HashSet<>(schema.getA... | @Test
void assertParseTableExpressionWithoutSchema() {
Map<String, ShardingSphereSchema> schemas = Collections.singletonMap("sharding_db", mockedPublicSchema());
ShardingSphereDatabase database = new ShardingSphereDatabase("sharding_db", TypedSPILoader.getService(DatabaseType.class, "FIXTURE"), null... |
@Nullable
public synchronized Beacon track(@NonNull Beacon beacon) {
Beacon trackedBeacon = null;
if (beacon.isMultiFrameBeacon() || beacon.getServiceUuid() != -1) {
trackedBeacon = trackGattBeacon(beacon);
}
else {
trackedBeacon = beacon;
}
re... | @Test
public void gattBeaconFieldsGetUpdated() {
Beacon beacon = getGattBeacon();
Beacon extraDataBeacon = getGattBeaconExtraData();
Beacon repeatBeacon = getGattBeacon();
repeatBeacon.setRssi(-100);
ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();
track... |
public static TransactionWitness redeemP2WSH(Script witnessScript, TransactionSignature... signatures) {
List<byte[]> pushes = new ArrayList<>(signatures.length + 2);
pushes.add(new byte[] {});
for (TransactionSignature signature : signatures)
pushes.add(signature.encodeToBitcoin());... | @Test
public void testRedeemP2WSH() throws SignatureDecodeException {
ECKey.ECDSASignature ecdsaSignature1 = TransactionSignature.decodeFromDER(ByteUtils.parseHex("3045022100c3d84f7bf41c7eda3b23bbbccebde842a451c1a0aca39df706a3ff2fe78b1e0a02206e2e3c23559798b02302ad6fa5ddbbe87af5cc7d3b9f86b88588253770ab9f79")... |
public Concept lowestCommonAncestor(String v, String w) {
Concept vnode = getConcept(v);
Concept wnode = getConcept(w);
return lowestCommonAncestor(vnode, wnode);
} | @Test
public void testLowestCommonAncestor() {
System.out.println("lowestCommonAncestor");
Concept result = taxonomy.lowestCommonAncestor("A", "B");
assertEquals(a, result);
result = taxonomy.lowestCommonAncestor("E", "B");
assertEquals(taxonomy.getRoot(), result);
} |
public Blade watchEnvChange(boolean watchEnvChange) {
this.environment.set(BladeConst.ENV_KEY_APP_WATCH_ENV, watchEnvChange);
return this;
} | @Test
public void testWatchEnvChange() {
Environment environment = Blade.create().watchEnvChange(false).environment();
assertEquals(Boolean.FALSE, environment.getBooleanOrNull(ENV_KEY_APP_WATCH_ENV));
} |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testConsumerGroupOffsetDeleteWithPendingTransactionalOffsets() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
ConsumerGroup group = context.groupMetadataManager.getOrMaybeCreatePersistedConsumerGroup(
"foo",
... |
static String strip(final String line) {
return new Parser(line).parse();
} | @Test
public void shouldCorrectHandleEscapedDoubleQuotes() {
// Given:
final String line = "\"this isn''t a comment -- the first quote isn''t closed\" -- comment";
final String line2 = "\"\"\"this isn''t a comment -- the first quote isn''t closed\" -- comment";
// Then:
assertThat(CommentStripper... |
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder,
AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl,
Long idleTime) {
Configuration config = Securi... | @Test
public void testIntKeysTextToXMLValues() {
Integer key = 12345;
String keyContentType = "application/x-java-object;type=java.lang.Integer";
String value = "<foo>bar</foo>";
putInCache("default", key, keyContentType, value, TEXT_PLAIN_TYPE);
RestResponse response = get("default", ... |
public double[] decodeFloat8Array(final byte[] parameterBytes, final boolean isBinary) {
ShardingSpherePreconditions.checkState(!isBinary, () -> new UnsupportedSQLOperationException("binary mode"));
String parameterValue = new String(parameterBytes, StandardCharsets.UTF_8);
Collection<String> pa... | @Test
void assertParseFloat8ArrayNormalTextMode() {
double[] actual = DECODER.decodeFloat8Array(FLOAT_ARRAY_STR.getBytes(), false);
assertThat(actual.length, is(2));
assertThat(Double.compare(actual[0], 11.1D), is(0));
assertThat(Double.compare(actual[1], 12.1D), is(0));
} |
@Override
public void emit(OutboundPacket packet) {
DeviceId devId = packet.sendThrough();
String scheme = devId.toString().split(":")[0];
if (!scheme.equals(this.id().scheme())) {
throw new IllegalArgumentException(
"Don't know how to handle Device with sche... | @Test(expected = IllegalArgumentException.class)
public void wrongScheme() {
sw.setRole(RoleState.MASTER);
OutboundPacket schemeFailPkt = outPacket(DID_WRONG, TR, null);
provider.emit(schemeFailPkt);
assertEquals("message sent incorrectly", 0, sw.sent.size());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.