focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Nonnull
public static <T> Traverser<T> traverseIterable(@Nonnull Iterable<? extends T> iterable) {
return traverseIterator(iterable.iterator());
} | @Test(expected = NullPointerException.class)
public void when_traverseIterableWithNull_then_failure() {
Traverser<Integer> trav = traverseIterable(asList(1, null));
trav.next();
trav.next();
} |
@Override
public void gauge(final String key, final Object value) {
this.metrics.gauge(this.threadContext, this.getSymbol(key), Rubyfier.deep(this.threadContext.getRuntime(), value));
} | @Test
public void testGauge() {
doTestGauge("test");
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testReadCommittedAbortMarkerWithNoData() {
buildFetcher(OffsetResetStrategy.EARLIEST, new StringDeserializer(),
new StringDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long producerId = 1L;... |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testBatchPipelineFailsIfException() throws Exception {
Pipeline p = TestPipeline.create(options);
PCollection<Integer> pc = p.apply(Create.of(1, 2, 3));
PAssert.that(pc).containsInAnyOrder(1, 2, 3);
DataflowPipelineJob mockJob = Mockito.mock(DataflowPipelineJob.class);
when(mock... |
@Override
public Session start(SessionContext context) {
throw new UnsupportedOperationException("Sessions are disabled.");
} | @Test(expected = UnsupportedOperationException.class)
public void testStart() {
mgr.start(null);
} |
public void expand(String key, long value, RangeHandler rangeHandler, EdgeHandler edgeHandler) {
if (value < lowerBound || value > upperBound) {
// Value outside bounds -> expand to nothing.
return;
}
int maxLevels = value > 0 ? maxPositiveLevels : maxNegativeLevels;
... | @Test
void requireThatMinRangeIsExpandedWithArity8() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(8);
expander.expand("key", -9223372036854775808L, range -> fail(),
(edge, value) -> {
assertEquals(PredicateHash.hash64("key=-92233720368547... |
public static SqlToJavaTypeConverter sqlToJavaConverter() {
return SQL_TO_JAVA_CONVERTER;
} | @Test
public void shouldGetJavaTypesForAllSqlTypes() {
for (final Entry<SqlBaseType, Class<?>> entry : SQL_TO_JAVA.entrySet()) {
final SqlBaseType sqlType = entry.getKey();
final Class<?> javaType = entry.getValue();
final Class<?> result = SchemaConverters.sqlToJavaConverter().toJavaType(sqlTyp... |
@Override
public boolean databaseExists(SnowflakeIdentifier database) {
Preconditions.checkArgument(
database.type() == SnowflakeIdentifier.Type.DATABASE,
"databaseExists requires a DATABASE identifier, got '%s'",
database);
final String finalQuery = "SHOW SCHEMAS IN DATABASE IDENTIFI... | @SuppressWarnings("unchecked")
@Test
public void testDatabaseExists() throws SQLException {
when(mockResultSet.next()).thenReturn(true).thenReturn(false);
when(mockResultSet.getString("database_name")).thenReturn("DB_1");
when(mockResultSet.getString("name")).thenReturn("SCHEMA_1");
assertThat(snow... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyUnexpectedItemFailure() {
expectFailureWhenTestingThat(asList(1, 2, 3)).containsExactly(1, 2);
assertFailureValue("unexpected (1)", "3");
} |
public static Object get(Object object, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
r... | @Test
void testGetCollection1() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtils.get(Collections.emptySet(), 0);
});
} |
public Future<KafkaCluster> prepareKafkaCluster(
Kafka kafkaCr,
List<KafkaNodePool> nodePools,
Map<String, Storage> oldStorage,
Map<String, List<String>> currentPods,
KafkaVersionChange versionChange,
KafkaStatus kafkaStatus,
boolean tr... | @Test
public void testExistingClusterWithKRaft(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
KafkaStatus kafkaStatus = new KafkaStatus();
KafkaClusterCreator creator = new KafkaClusterCreator(vertx, RECONCILIATION, CO_CONFIG, KafkaMe... |
@ScalarFunction(visibility = HIDDEN)
@SqlType("array(unknown)")
public static Block arrayConstructor()
{
BlockBuilder blockBuilder = new ArrayType(UNKNOWN).createBlockBuilder(null, 0);
return blockBuilder.build();
} | @Test
public void testArrayConstructor()
{
tryEvaluateWithAll("array[" + Joiner.on(", ").join(nCopies(254, "rand()")) + "]", new ArrayType(DOUBLE));
assertNotSupported(
"array[" + Joiner.on(", ").join(nCopies(255, "rand()")) + "]",
"Too many arguments for array co... |
@Override
public void writeTo(MysqlSerializer serializer) {
// used to check
MysqlCapability capability = serializer.getCapability();
serializer.writeInt1(PACKET_OK_INDICATOR);
serializer.writeVInt(affectedRows);
serializer.writeVInt(LAST_INSERT_ID);
if (capability.i... | @Test
public void testWrite() {
MysqlOkPacket packet = new MysqlOkPacket(new QueryState());
MysqlSerializer serializer = MysqlSerializer.newInstance(capability);
packet.writeTo(serializer);
ByteBuffer buffer = serializer.toByteBuffer();
// assert OK packet indicator 0x00
... |
public void log(String remoteAddress, ContainerRequest jerseyRequest, ContainerResponse jettyResponse) {
WebsocketEvent event = new WebsocketEvent(remoteAddress, jerseyRequest, jettyResponse);
if (getFilterChainDecision(event) == FilterReply.DENY) {
return;
}
aai.appendLoopOnAppenders(event);
... | @Test
void testLogLineWithHeaders() throws InterruptedException {
WebSocketSessionContext sessionContext = mock(WebSocketSessionContext.class);
ListAppender<WebsocketEvent> listAppender = new ListAppender<>();
WebsocketRequestLoggerFactory requestLoggerFactory = new WebsocketRequestLoggerFactory();
r... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertUncompressedBytesMessageToAmqpMessageWithDataBody() throws Exception {
byte[] expectedPayload = new byte[] { 8, 16, 24, 32 };
ActiveMQBytesMessage outbound = createBytesMessage();
outbound.writeBytes(expectedPayload);
outbound.storeContent();
outb... |
public CompletionStage<Void> migrate(MigrationSet set) {
InterProcessLock lock = new InterProcessSemaphoreMutex(client.unwrap(), ZKPaths.makePath(lockPath, set.id()));
CompletionStage<Void> lockStage = lockAsync(lock, lockMax.toMillis(), TimeUnit.MILLISECONDS, executor);
return lockStage.thenCom... | @Test
public void testConcurrency2() throws Exception {
CuratorOp op1 = client.transactionOp().create().forPath("/test");
CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes());
Migration migration = () -> Arrays.asList(op1, op2);
MigrationSet migrat... |
public List<CounterRequest> getOrderedRequests() {
final List<CounterRequest> requestList = getRequests();
if (requestList.size() > 1) {
requestList.sort(COUNTER_REQUEST_COMPARATOR);
}
return requestList;
} | @Test
public void testGetOrderedRequests() {
counter.clear();
counter.addRequest("test a", 0, 0, 0, false, 1000);
counter.addRequest("test b", 1000, 500, 500, false, 1000); // supérieur
counter.addRequest("test c", 1000, 500, 500, false, 1000); // égal
counter.addRequest("test d", 100, 50, 50, false, 1000); ... |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testMergeAllowSystemChangesInternalMode() throws JsonProcessingException {
for (InternalParamMode mode : Collections.singletonList(InternalParamMode.RESERVED)) {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
String.format(
"{'tomerge':... |
@DELETE
@Path("/{connector}")
@Operation(summary = "Delete the specified connector")
public void destroyConnector(final @PathParam("connector") String connector,
final @Context HttpHeaders headers,
final @Parameter(hidden = true) @QueryParam(... | @Test
public void testDeleteConnectorNotFound() {
final ArgumentCaptor<Callback<Herder.Created<ConnectorInfo>>> cb = ArgumentCaptor.forClass(Callback.class);
expectAndCallbackException(cb, new NotFoundException("not found"))
.when(herder).deleteConnectorConfig(eq(CONNECTOR_NAME), cb.capt... |
private void urlWithParamIfGet() {
if (Method.GET.equals(method) && false == this.isRest && this.redirectCount <= 0) {
UrlQuery query = this.url.getQuery();
if (null == query) {
query = new UrlQuery();
this.url.setQuery(query);
}
// 优先使用body形式的参数,不存在使用form
if (null != this.body) {
query.pa... | @Test
@Disabled
public void urlWithParamIfGetTest(){
final UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.setScheme("https").setHost("hutool.cn");
final HttpRequest httpRequest = new HttpRequest(urlBuilder);
httpRequest.setMethod(Method.GET).execute();
} |
@Override
public void configure(JettyWebSocketServletFactory factory) {
factory.setCreator(this);
factory.setMaxBinaryMessageSize(configuration.getMaxBinaryMessageSize());
factory.setMaxTextMessageSize(configuration.getMaxTextMessageSize());
} | @Test
void testConfigure() {
JettyWebSocketServletFactory servletFactory = mock(JettyWebSocketServletFactory.class);
when(environment.jersey()).thenReturn(jerseyEnvironment);
WebSocketResourceProviderFactory<Account> factory = new WebSocketResourceProviderFactory<>(environment,
Account.class,
... |
public static boolean equivalent(
Expression left, Expression right, Types.StructType struct, boolean caseSensitive) {
return Binder.bind(struct, Expressions.rewriteNot(left), caseSensitive)
.isEquivalentTo(Binder.bind(struct, Expressions.rewriteNot(right), caseSensitive));
} | @Test
public void testAndEquivalence() {
assertThat(
ExpressionUtil.equivalent(
Expressions.and(
Expressions.lessThan("id", 34), Expressions.greaterThanOrEqual("id", 20)),
Expressions.and(
Expressions.greaterThan("id", 19L), Expre... |
@Override
public Capabilities getCapabilitiesFromResponse(String responseBody) {
return com.thoughtworks.go.plugin.access.configrepo.v2.models.Capabilities.fromJSON(responseBody).toCapabilities();
} | @Test
public void shouldReturnAllFalseCapabilities() {
assertEquals(new Capabilities(true, true, false, false), handler.getCapabilitiesFromResponse("{\"supports_pipeline_export\":\"true\",\"supports_parse_content\":\"true\"}"));
} |
public String[] getFileTypeDisplayNames( Locale locale ) {
return new String[] { "Transformations", "XML" };
} | @Test
public void testGetFileTypeDisplayNames() throws Exception {
String[] names = transFileListener.getFileTypeDisplayNames( null );
assertNotNull( names );
assertEquals( 2, names.length );
assertEquals( "Transformations", names[0] );
assertEquals( "XML", names[1] );
} |
@Override
public ResourceModel processResourceModel(ResourceModel model, Configuration config) {
// Create new resource model.
final ResourceModel.Builder resourceModelBuilder = new ResourceModel.Builder(false);
for (final Resource resource : model.getResources()) {
for (Class<?>... | @Test
public void processResourceModelDoesNotAddPrefixToResourceClassInOtherPackage() throws Exception {
final ImmutableMap<String, String> packagePrefixes = ImmutableMap.of("org.example", "/test/prefix");
when(configuration.isCloud()).thenReturn(false);
final PrefixAddingModelProcessor mode... |
@Override
public Set<Algorithm> getKeys(final Path file, final LoginCallback prompt) throws BackgroundException {
final Path container = containerService.getContainer(file);
final Set<Algorithm> keys = super.getKeys(container, prompt);
if(container.isRoot()) {
return keys;
... | @Test
public void testGetKeys_eu_west_1() throws Exception {
final KMSEncryptionFeature kms = new KMSEncryptionFeature(session, new S3LocationFeature(session), new S3AccessControlListFeature(session), new DisabledX509TrustManager(), new DefaultX509KeyManager());
assertFalse(kms.getKeys(new Path("tes... |
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenNullString_parsesNullCells() {
CSVFormat csvFormat = csvFormat().withNullString("🐼");
PCollection<String> input =
pipeline.apply(Create.of(headerLine(csvFormat), "a,1,🐼", "b,🐼,2.2", "🐼,3,3.3"));
CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvRecord(csvFormat);
... |
@Override
public double logp(int k) {
if (k < 0 || k > n) {
return Double.NEGATIVE_INFINITY;
} else {
return lfactorial(n) - lfactorial(k)
- lfactorial(n - k) + k * log(p) + (n - k) * log(1.0 - p);
}
} | @Test
public void testLogP() {
System.out.println("logP");
BinomialDistribution instance = new BinomialDistribution(100, 0.3);
instance.rand();
assertEquals(Math.log(3.234477e-16), instance.logp(0), 1E-5);
assertEquals(Math.log(1.386204e-14), instance.logp(1), 1E-5);
... |
public Map<String, Uuid> topicNameToIdView() {
return new TranslatedValueMapView<>(topicsByName, TopicImage::id);
} | @Test
public void testTopicNameToIdView() {
Map<String, Uuid> map = IMAGE1.topicNameToIdView();
assertTrue(map.containsKey("foo"));
assertEquals(FOO_UUID, map.get("foo"));
assertTrue(map.containsKey("bar"));
assertEquals(BAR_UUID, map.get("bar"));
assertFalse(map.cont... |
private List<Class<?>> scanForClassesInPackage(String packageName, Predicate<Class<?>> classFilter) {
requireValidPackageName(packageName);
requireNonNull(classFilter, "classFilter must not be null");
List<URI> rootUris = getUrisForPackage(getClassLoader(), packageName);
return findClass... | @Test
void scanForClassesInPackage() {
List<Class<?>> classes = scanner.scanForClassesInPackage("io.cucumber.core.resource.test");
assertThat(classes, containsInAnyOrder(
ExampleClass.class,
ExampleInterface.class,
OtherClass.class));
} |
public static String cut(String s, String splitChar, int index) {
if (s == null || splitChar == null || index < 0) {
return null;
}
final String[] parts = s.split(Pattern.quote(splitChar));
if (parts.length <= index) {
return null;
}
return empty... | @Test
public void testCutChecksBounds() throws Exception {
String result = SplitAndIndexExtractor.cut("foobar", " ", 1);
assertNull(result);
} |
public RuntimeOptionsBuilder parse(Class<?> clazz) {
RuntimeOptionsBuilder args = new RuntimeOptionsBuilder();
for (Class<?> classWithOptions = clazz; hasSuperClass(
classWithOptions); classWithOptions = classWithOptions.getSuperclass()) {
CucumberOptions options = requireNonNul... | @Test
void create_without_options() {
RuntimeOptions runtimeOptions = parser()
.parse(WithoutOptions.class)
.build();
assertAll(
() -> assertThat(runtimeOptions.getObjectFactoryClass(), is(nullValue())),
() -> assertThat(runtimeOptions.getFeat... |
@Override
public Collection<Integer> getOutboundPorts(EndpointQualifier endpointQualifier) {
final AdvancedNetworkConfig advancedNetworkConfig = node.getConfig().getAdvancedNetworkConfig();
if (advancedNetworkConfig.isEnabled()) {
EndpointConfig endpointConfig = advancedNetworkConfig.get... | @Test
public void testGetOutboundPorts_acceptsRange() {
networkConfig.addOutboundPortDefinition("29000-29001");
Collection<Integer> outboundPorts = serverContext.getOutboundPorts(MEMBER);
assertThat(outboundPorts).hasSize(2);
assertThat(outboundPorts).containsExactlyInAnyOrder(29000... |
@Override
public void execute(List<RegisteredMigrationStep> steps, MigrationStatusListener listener) {
Profiler globalProfiler = Profiler.create(LOGGER);
globalProfiler.startInfo(GLOBAL_START_MESSAGE, databaseMigrationState.getTotalMigrations());
boolean allStepsExecuted = false;
try {
for (Regi... | @Test
void execute_execute_the_instance_of_type_specified_in_step_in_stream_order() {
migrationContainer.add(MigrationStep1.class, MigrationStep2.class, MigrationStep3.class);
((SpringComponentContainer) migrationContainer).startComponents();
underTest.execute(asList(
registeredStepOf(1, MigrationS... |
protected void declareRuleFromAttribute(final Attribute attribute, final String parentPath,
final int attributeIndex,
final List<KiePMMLDroolsRule> rules,
final String statusToSet,
... | @Test
void declareRuleFromAttributeWithSimpleSetPredicate() {
Attribute attribute = getSimpleSetPredicateAttribute();
final String parentPath = "parent_path";
final int attributeIndex = 2;
final List<KiePMMLDroolsRule> rules = new ArrayList<>();
final String statusToSet = "st... |
public static ClusterResolver<EurekaEndpoint> fromURL(String regionName, URL serviceUrl) {
boolean isSecure = "https".equalsIgnoreCase(serviceUrl.getProtocol());
int defaultPort = isSecure ? 443 : 80;
int port = serviceUrl.getPort() == -1 ? defaultPort : serviceUrl.getPort();
return new... | @Test
public void testClusterResolverFromURL() throws Exception {
verifyEqual(
StaticClusterResolver.fromURL("regionA", new URL("http://eureka.test:8080/eureka/v2/apps")),
new DefaultEndpoint("eureka.test", 8080, false, "/eureka/v2/apps")
);
verifyEqual(
... |
@VisibleForTesting
static Map<String, Long> getStepIdToRunIdForForeachAndSubworkflowFromPreviousRuns(
WorkflowInstance instance) {
Map<String, StepType> stepIdToStepTypeForForeachAndSubworkflows =
instance.getRuntimeWorkflow().getSteps().stream()
.filter(
step ->
... | @Test
public void testGetStepIdToRunIdForForeachAndSubworkflowFromPreviousRuns() throws IOException {
WorkflowInstance sampleInstance =
loadObject(
"fixtures/instances/sample-workflow-instance-created-foreach-subworkflow-1.json",
WorkflowInstance.class);
Map<String, Long> step... |
public SaslExtensions extensions() {
return saslExtensions;
} | @Test
public void testExtensions() throws Exception {
String message = "n,,\u0001propA=valueA1, valueA2\u0001auth=Bearer 567\u0001propB=valueB\u0001\u0001";
OAuthBearerClientInitialResponse response = new OAuthBearerClientInitialResponse(message.getBytes(StandardCharsets.UTF_8));
assertEqual... |
@Override
public ResultSet getAttributes(final String catalog, final String schemaPattern, final String typeNamePattern, final String attributeNamePattern) {
return null;
} | @Test
void assertGetAttributes() {
assertNull(metaData.getAttributes("", "", "", ""));
} |
@Override
public long getPeriodMillis() {
return STATIC;
} | @Test
public void testGetPeriodMillis() {
assertEquals(STATIC, plugin.getPeriodMillis());
} |
public IndexConfig setAttributes(List<String> attributes) {
checkNotNull(attributes, "Index attributes cannot be null.");
this.attributes = new ArrayList<>(attributes.size());
for (String attribute : attributes) {
addAttribute(attribute);
}
return this;
} | @Test(expected = IllegalArgumentException.class)
public void testAttributeEmpty() {
new IndexConfig().setAttributes(Collections.singletonList(""));
} |
public static String[] parseUri(String uri) {
return doParseUri(uri, false);
} | @Test
public void testParseNoSlashUri() {
String[] out1 = CamelURIParser.parseUri("direct:start");
assertEquals("direct", out1[0]);
assertEquals("start", out1[1]);
assertNull(out1[2]);
} |
private MessageRouter getMessageRouter() {
MessageRouter messageRouter;
MessageRoutingMode messageRouteMode = conf.getMessageRoutingMode();
switch (messageRouteMode) {
case CustomPartition:
messageRouter = Objects.requireNonNull(conf.getCustomMessageRouter());
... | @Test
public void testSinglePartitionMessageRouterImplInstance() throws NoSuchFieldException, IllegalAccessException {
ProducerConfigurationData producerConfigurationData = new ProducerConfigurationData();
producerConfigurationData.setMessageRoutingMode(MessageRoutingMode.SinglePartition);
... |
public synchronized boolean saveNamespace(long timeWindow, long txGap,
FSNamesystem source) throws IOException {
if (timeWindow > 0 || txGap > 0) {
final FSImageStorageInspector inspector = storage.readAndInspectDirs(
EnumSet.of(NameNodeFile.IMAGE, NameNodeFile.IMAGE_ROLLBACK),
Start... | @Test(timeout = 60000)
public void testSupportBlockGroup() throws Exception {
final short GROUP_SIZE = (short) (testECPolicy.getNumDataUnits() +
testECPolicy.getNumParityUnits());
final int BLOCK_SIZE = 8 * 1024 * 1024;
Configuration conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.D... |
@Override
public List<ServicecombServiceInstance> getInstanceList(String serviceId) {
final List<MicroserviceInstance> microserviceInstances = getScInstances(serviceId);
final List<ServicecombServiceInstance> serviceInstances = new ArrayList<>();
for (final MicroserviceInstance microserviceI... | @Test
public void getInstanceList() {
final List<ServicecombServiceInstance> instanceList = scRegister.getInstanceList(serviceName);
Assert.assertEquals(instanceList.size(), this.instanceList.size());
} |
public static String[] nullToEmpty(String[] array) {
return edit(array, t -> null == t ? StrUtil.EMPTY : t);
} | @Test
public void nullToEmptyTest() {
String[] a = {"a", "b", "", null, " ", "c"};
String[] resultA = {"a", "b", "", "", " ", "c"};
assertArrayEquals(ArrayUtil.nullToEmpty(a), resultA);
} |
public Result fetchArtifacts(String[] uris) {
checkArgument(uris != null && uris.length > 0, "At least one URI is required.");
ArtifactUtils.createMissingParents(baseDir);
List<File> artifacts =
Arrays.stream(uris)
.map(FunctionUtils.uncheckedFunction(thi... | @Test
void testHttpFetch() throws Exception {
configuration.set(ArtifactFetchOptions.RAW_HTTP_ENABLED, true);
HttpServer httpServer = null;
try {
httpServer = startHttpServer();
File sourceFile = getFlinkClientsJar();
httpServer.createContext(
... |
@Override
public List<SimpleColumn> toColumns(
final ParsedSchema schema,
final SerdeFeatures serdeFeatures,
final boolean isKey) {
SerdeUtils.throwOnUnsupportedFeatures(serdeFeatures, format.supportedFeatures());
Schema connectSchema = connectSrTranslator.toConnectSchema(schema);
if (... | @Test
public void shouldThrowOnUnwrappedSchemaIfUnwrapSingleIsFalse() {
// Given:
when(connectSchema.type()).thenReturn(Type.INT32);
when(format.supportedFeatures()).thenReturn(Collections.singleton(SerdeFeature.UNWRAP_SINGLES));
// When:
final Exception e = assertThrows(KsqlException.class,
... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateMultiStatsWhenOnlySomeAvailable() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3", "part4");
ColumnStatisticsData data1 = new ColStatsBuilder<>(long.class).numNulls(1).numDVs(3)
.low(1L).high(3L).hll(1, 2, 3).kll(1, 2, 3).build()... |
public static boolean isNormalizedPathOutsideWorkingDir(String path) {
final String normalize = FilenameUtils.normalize(path);
final String prefix = FilenameUtils.getPrefix(normalize);
return (normalize != null && StringUtils.isBlank(prefix));
} | @Test
public void shouldReturnFalseIfGivenFolderIsAbsoluteUnderLinux() {
assertThat(FilenameUtil.isNormalizedPathOutsideWorkingDir("/tmp"), is(false));
} |
@Override
public Integer call() throws Exception {
super.call();
if (this.pluginsPath == null) {
throw new CommandLine.ParameterException(this.spec.commandLine(), "Missing required options '--plugins' " +
"or environment variable 'KESTRA_PLUGINS_PATH"
);
... | @Test
void latestVersion() throws IOException {
Path pluginsPath = Files.createTempDirectory(PluginInstallCommandTest.class.getSimpleName());
pluginsPath.toFile().deleteOnExit();
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
String[] ... |
@Override
public Set<DeviceId> getDevicesOf(NodeId nodeId) {
checkNotNull(nodeId, NODE_ID_NULL);
return store.getDevices(networkId, nodeId);
} | @Test
public void getDevicesOf() {
mastershipMgr1.setRole(NID_LOCAL, VDID1, MASTER);
mastershipMgr1.setRole(NID_LOCAL, VDID2, STANDBY);
assertEquals("should be one device:", 1, mastershipMgr1.getDevicesOf(NID_LOCAL).size());
//hand both devices to NID_LOCAL
mastershipMgr1.set... |
public Value parse(String json) {
return this.delegate.parse(json);
} | @Test
public void testOrdinaryFloat() throws Exception {
final JsonParser parser = new JsonParser();
final Value msgpackValue = parser.parse("12345.12");
assertTrue(msgpackValue.getValueType().isNumberType());
assertTrue(msgpackValue.getValueType().isFloatType());
assertFalse... |
@Override
public ExecuteContext after(ExecuteContext context) throws Exception {
if (isHasMethodLoadSpringFactories()) {
// Only if use LoadSpringFactories for injection in the high version, it is more efficient to
// have a cache in the high version and only need to inject once
... | @Test
public void doAfterLowVersion() throws Exception {
// low version test
final SpringFactoriesInterceptor lowVersionInterceptor = new SpringFactoriesInterceptor();
hasMethodLoadSpringFactoriesFiled.set(lowVersionInterceptor, Boolean.FALSE);
ExecuteContext executeContext = Execute... |
public static <
EventTypeT,
EventKeyTypeT,
ResultTypeT,
StateTypeT extends MutableState<EventTypeT, ResultTypeT>>
OrderedEventProcessor<EventTypeT, EventKeyTypeT, ResultTypeT, StateTypeT> create(
OrderedProcessingHandler<EventTypeT, EventKeyTypeT, StateTypeT, Resu... | @Test
public void testHandlingOfCheckedExceptions() throws CannotProvideCoderException {
Event[] events = {
Event.create(0, "id-1", "a"),
Event.create(1, "id-1", "b"),
Event.create(2, "id-1", StringBuilderState.BAD_VALUE),
Event.create(3, "id-1", "c"),
};
Collection<KV<String, Ord... |
@Override
public void removeGroup(String groupName) {
get(removeGroupAsync(groupName));
} | @Test
public void testRemoveGroup() {
Assertions.assertThrows(RedisException.class, () -> {
RStream<String, String> stream = redisson.getStream("test");
stream.add(StreamAddArgs.entry("0", "0"));
stream.createGroup(StreamCreateGroupArgs.name("testGroup"));
... |
public static boolean shutdownExecutorForcefully(ExecutorService executor, Duration timeout) {
return shutdownExecutorForcefully(executor, timeout, true);
} | @Test
void testShutdownExecutorForcefullyInterruptable() {
MockExecutorService executor = new MockExecutorService(5);
executor.interruptAfterNumForcefulShutdown(1);
assertThat(
ComponentClosingUtils.shutdownExecutorForcefully(
executor,... |
public Uuid defaultDir(int brokerId) {
BrokerRegistration registration = registration(brokerId);
if (registration == null) {
// throwing an exception here can break the expected error from an
// Admin call, so instead, we return UNASSIGNED, and let the fact
// that th... | @Test
public void testDefaultDir() {
ClusterControlManager clusterControl = new ClusterControlManager.Builder().
setClusterId("pjvUwj3ZTEeSVQmUiH3IJw").
setFeatureControlManager(new FeatureControlManager.Builder().build()).
setBrokerUncleanShutdownHandler((bro... |
public static Builder newBuilder() {
return new Builder();
} | @Test
void testBuilderThrowExceptionIfjarFileAndEntryPointClassNameAreBothNull() {
assertThatThrownBy(() -> PackagedProgram.newBuilder().build())
.isInstanceOf(IllegalArgumentException.class);
} |
public void write(ImageWriter writer, ImageWriterOptions options) {
if (options.metadataVersion().isScramSupported()) {
for (Entry<ScramMechanism, Map<String, ScramCredentialData>> mechanismEntry : mechanisms.entrySet()) {
for (Entry<String, ScramCredentialData> userEntry : mechanism... | @Test
public void testEmptyWithInvalidIBP() {
ImageWriterOptions imageWriterOptions = new ImageWriterOptions.Builder().
setMetadataVersion(MetadataVersion.IBP_3_4_IV0).build();
RecordListWriter writer = new RecordListWriter();
ScramImage.EMPTY.write(writer, imageWriterOptions... |
@Override
public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception {
this.config = config;
this.sourceContext = sourceContext;
this.intermediateTopicName = SourceConfigUtils.computeBatchSourceIntermediateTopicName(sourceContext.getTenant(),
sourceContext.getNamespac... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp =
"BatchSource does not implement the correct interface")
public void testPushWithoutRightSource() throws Exception {
pushConfig.put(BatchSourceConfig.BATCHSOURCE_CLASSNAME_KEY, TestDiscoveryTriggerer.class.getNam... |
@Override
public Object evaluate(final ProcessingDTO processingDTO) {
String input = (String) getFromPossibleSources(name, processingDTO)
.orElse(null);
if (input == null) {
return mapMissingTo;
}
return input.equals(value) ? 1.0 : 0.0;
} | @Test
void evaluateSameValue() {
String fieldName = "fieldName";
String fieldValue = "fieldValue";
Number mapMissingTo = null;
KiePMMLNormDiscrete kiePMMLNormContinuous = getKiePMMLNormDiscrete(fieldName, fieldValue, mapMissingTo);
ProcessingDTO processingDTO = getProcessingD... |
public static void populateGetCreatedKiePMMLMiningFieldsMethod(final ClassOrInterfaceDeclaration modelTemplate,
final List<org.dmg.pmml.MiningField> miningFields,
final List<org.dmg.pmml... | @Test
void populateGetCreatedKiePMMLMiningFieldsMethod() throws IOException {
final CompilationDTO compilationDTO = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
pmmlModel,
... |
@Override
public String getCommand() {
return "help";
} | @Test
public void getCommand() throws Exception {
Assert.assertEquals(new HelpTelnetHandler().getCommand(), "help");
} |
public static List<Validation> computeFlagsFromCSVString(String csvString,
Log log) {
List<Validation> flags = new ArrayList<>();
boolean resetFlag = false;
for (String p : csvString.split(",")) {
try {
flag... | @Test
public void testFlagsOK() {
List<DMNValidator.Validation> result = DMNValidationHelper.computeFlagsFromCSVString("VALIDATE_SCHEMA,VALIDATE_MODEL", log);
assertThat(result).isNotNull()
.hasSize(2)
.contains(DMNValidator.Validation.VALIDATE_SCHEMA, DMNValidator.Va... |
@Override
public void importData(JsonReader reader) throws IOException {
logger.info("Reading configuration for 1.0");
// this *HAS* to start as an object
reader.beginObject();
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();... | @Test
public void testImportSystemScopes() throws IOException {
SystemScope scope1 = new SystemScope();
scope1.setId(1L);
scope1.setValue("scope1");
scope1.setDescription("Scope 1");
scope1.setRestricted(true);
scope1.setDefaultScope(false);
scope1.setIcon("glass");
SystemScope scope2 = new SystemScop... |
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {
if (!(msg instanceof List)) {
ByteBuf byteBuf = Unpooled.buffer();
((LispMessage) msg).writeTo(byteBuf);
out.add(new DatagramPacket(byteBuf, ((LispMessage) msg).getSender()... | @Test
public void testEncode() throws Exception {
LispMessageEncoder encoder = new LispMessageEncoder();
MockLispMessage request = new MockLispMessage(LispType.LISP_MAP_REQUEST);
MockLispMessage reply = new MockLispMessage(LispType.LISP_MAP_REPLY);
MockLispMessage register = new Mock... |
@Override
public String build() {
if(null == this.paramValues){
this.paramValues = new ArrayList<>();
} else {
this.paramValues.clear();
}
return build(this.paramValues);
} | @Test
public void buildTest(){
Condition c1 = new Condition("user", null);
Condition c2 = new Condition("name", "!= null");
c2.setLinkOperator(LogicalOperator.OR);
Condition c3 = new Condition("group", "like %aaa");
final ConditionBuilder builder = ConditionBuilder.of(c1, c2, c3);
final String sql = build... |
public static BlockingQueue<Runnable> buildQueue(int size) {
return buildQueue(size, false);
} | @Test
public void buildQueue1() throws Exception {
BlockingQueue<Runnable> queue = ThreadPoolUtils.buildQueue(0, true);
Assert.assertEquals(queue.getClass(), SynchronousQueue.class);
queue = ThreadPoolUtils.buildQueue(-1, true);
Assert.assertEquals(queue.getClass(), PriorityBlockingQ... |
@Override
public synchronized <T extends EventListener<?>> boolean removeListener(final EventType eventType, final T eventListener) {
if (eventType == null || eventListener == null) {
return false;
}
final EventListener<?>[] listeners = this.listenerMap.get(eventType);
if... | @Test
void testRemoveListenerWithNullParameters() {
assertFalse(this.instance.removeListener(null, null));
assertFalse(this.instance.removeListener(EventType.HANDSHAKE, null));
assertFalse(this.instance.removeListener(null, ignored -> {
}));
} |
public ShardingSphereDatabase getDatabase(final String name) {
ShardingSpherePreconditions.checkNotEmpty(name, NoDatabaseSelectedException::new);
ShardingSphereMetaData metaData = getMetaDataContexts().getMetaData();
ShardingSpherePreconditions.checkState(metaData.containsDatabase(name), () -> n... | @Test
void assertDropDatabase() {
when(metaDataContexts.getMetaData().getDatabase("foo_db").getName()).thenReturn("foo_db");
when(metaDataContexts.getMetaData().containsDatabase("foo_db")).thenReturn(true);
contextManager.getMetaDataContextManager().getSchemaMetaDataManager().dropDatabase("f... |
public CreateTableCommand createTableCommand(
final KsqlStructuredDataOutputNode outputNode,
final Optional<RefinementInfo> emitStrategy
) {
Optional<WindowInfo> windowInfo =
outputNode.getKsqlTopic().getKeyFormat().getWindowInfo();
if (windowInfo.isPresent() && emitStrategy.isPresent()) ... | @Test
public void shouldThrowInCreateTableOrReplaceSource() {
// Given:
final CreateTable ddlStatement = new CreateTable(TABLE_NAME,
TableElements.of(
tableElement("COL1", new Type(BIGINT), PRIMARY_KEY_CONSTRAINT),
tableElement("COL2", new Type(SqlTypes.STRING))),
true,... |
public Builder toBuilder() {
Builder result = new Builder();
result.flags = flags;
result.traceIdHigh = traceIdHigh;
result.traceId = traceId;
return result;
} | @Test void canSetSampledNull() {
base = base.toBuilder().sampled(true).build();
TraceIdContext objects = base.toBuilder().sampled(null).build();
assertThat(objects.debug())
.isFalse();
assertThat(objects.sampled())
.isNull();
} |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testUpgradeWithIVVersions(VertxTestContext context) {
String oldKafkaVersion = KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION;
String oldInterBrokerProtocolVersion = KafkaVersionTestUtils.PREVIOUS_PROTOCOL_VERSION + "-IV0";
String oldLogMessageFormatVersion = KafkaVersionTest... |
public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions, Timer timer) {
return beginningOrEndOffset(partitions, ListOffsetsRequest.EARLIEST_TIMESTAMP, timer);
} | @Test
public void testBeginningOffsets() {
buildFetcher();
assignFromUser(singleton(tp0));
client.prepareResponse(listOffsetResponse(tp0, Errors.NONE, ListOffsetsRequest.EARLIEST_TIMESTAMP, 2L));
assertEquals(singletonMap(tp0, 2L), offsetFetcher.beginningOffsets(singleton(tp0), time.... |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testIntegerNotEq() {
boolean shouldRead =
new StrictMetricsEvaluator(SCHEMA, notEqual("id", INT_MIN_VALUE - 25)).eval(FILE);
assertThat(shouldRead).as("Should match: no values == 5").isTrue();
shouldRead = new StrictMetricsEvaluator(SCHEMA, notEqual("id", INT_MIN_VALUE - 1)).eva... |
@DELETE
@Path("/{connector}/offsets")
@Operation(summary = "Reset the offsets for the specified connector")
public Response resetConnectorOffsets(final @Parameter(hidden = true) @QueryParam("forward") Boolean forward,
final @Context HttpHeaders headers, final @PathP... | @Test
public void testResetOffsets() throws Throwable {
final ArgumentCaptor<Callback<Message>> cb = ArgumentCaptor.forClass(Callback.class);
Message msg = new Message("The offsets for this connector have been reset successfully");
doAnswer(invocation -> {
cb.getValue().onComplet... |
public static <NodeT, EdgeT> List<List<NodeT>> allPathsFromRootsToLeaves(
Network<NodeT, EdgeT> network) {
ArrayDeque<List<NodeT>> paths = new ArrayDeque<>();
// Populate the list with all roots
for (NodeT node : network.nodes()) {
if (network.inDegree(node) == 0) {
paths.add(ImmutableLi... | @Test
public void testAllPathsFromRootsToLeaves() {
// Expected paths:
// D
// A, B, C, F
// A, B, E, G
// A, B, E, G (again)
// A, B, E, H
// I, J, E, G
// I, J, E, G (again)
// I, J, E, H
// I, E, G
// I, E, G (again)
// I, E, H
// I, K, L
// M, N, L
// M,... |
@Override
public boolean add(String e) {
return get(addAsync(e));
} | @Test
public void testAddListener() {
testWithParams(redisson -> {
RLexSortedSet al = redisson.getLexSortedSet("test");
CountDownLatch latch = new CountDownLatch(1);
al.addListener(new ScoredSortedSetAddListener() {
@Override
public void on... |
@Override
public BeamSqlTable buildBeamSqlTable(Table tableDefinition) {
ObjectNode tableProperties = tableDefinition.getProperties();
try {
RowJson.RowJsonDeserializer deserializer =
RowJson.RowJsonDeserializer.forSchema(getSchemaIOProvider().configurationSchema())
.withNullBeh... | @Test
public void testBuildIOReader_withProjectionPushdown() {
TestSchemaIOTableProviderWrapper provider = new TestSchemaIOTableProviderWrapper();
BeamSqlTable beamSqlTable = provider.buildBeamSqlTable(testTable);
PCollection<Row> result =
beamSqlTable.buildIOReader(
pipeline.begin(),... |
public String marshal() {
StringBuilder result = new StringBuilder();
for (JobDataNodeEntry each : entries) {
result.append(each.marshal()).append('|');
}
if (!entries.isEmpty()) {
result.setLength(result.length() - 1);
}
return result.toString();
... | @Test
void assertMarshal() {
String actual = new JobDataNodeLine(Arrays.asList(
new JobDataNodeEntry("t_order", Arrays.asList(new DataNode("ds_0.t_order_0"), new DataNode("ds_0.t_order_1"))),
new JobDataNodeEntry("t_order_item", Arrays.asList(new DataNode("ds_0.t_order_item_0... |
@VisibleForTesting
static @Nullable TimeUnit unitSuggestedByName(String name) {
// Tuple types, especially Pair, trip us up. Skip APIs that might be from them.
// This check is somewhat redundant with the "second" check below.
// TODO(cpovirk): Skip APIs only if they're from a type that also declares a fi... | @Test
public void testUnitSuggestedByName() {
assertSeconds("sleepSec", "deadlineSeconds", "secondsTimeout", "msToS");
assertUnknown(
"second",
"getSecond",
"SECOND",
"secondDeadline",
"twoSeconds",
"THIRTY_SECONDS",
"fromSeconds",
"x",
"... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testBatchesDrainedWithOldProducerIdShouldSucceedOnSubsequentRetry() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerId... |
public String validate(final String xml) {
final Source source = new SAXSource(reader, new InputSource(IOUtils.toInputStream(xml, Charset.defaultCharset())));
return validate(source);
} | @Test
public void testInvalidXMLWithClientResolver() throws Exception {
String payload = IOUtils.toString(ClassLoader.getSystemResourceAsStream("xml/article-3.xml"),
Charset.defaultCharset());
logger.info("Validating payload: {}", payload);
// validate
String result ... |
@Override
public Set<String> getExtensionClassNames(String pluginId) {
if (currentPluginId.equals(pluginId)) {
return original.getExtensionClassNames(pluginId);
} else {
throw new IllegalAccessError(PLUGIN_PREFIX + currentPluginId + " tried to execute getExtensionClassNames f... | @Test
public void getExtensionClassNames() {
pluginManager.loadPlugins();
assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.getExtensionClassNames(OTHER_PLUGIN_ID));
assertEquals(1, wrappedPluginManager.getExtensionClassNames(THIS_PLUGIN_ID).size());
} |
public void scanResponseTable() {
final List<ResponseFuture> rfList = new LinkedList<>();
Iterator<Entry<Integer, ResponseFuture>> it = this.responseTable.entrySet().iterator();
while (it.hasNext()) {
Entry<Integer, ResponseFuture> next = it.next();
ResponseFuture rep = n... | @Test
public void testScanResponseTable() {
int dummyId = 1;
// mock timeout
ResponseFuture responseFuture = new ResponseFuture(null, dummyId, -1000, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
... |
public static List<MainModel.MainOptionModel> parseConfigurationSource(String fileName) throws IOException {
return parseConfigurationSource(new File(fileName));
} | @Test
public void testMyParser() throws Exception {
String fileName = "src/test/java/org/apache/camel/maven/packaging/MyConfiguration.java";
List<MainModel.MainOptionModel> list = PrepareCamelMainMojo.parseConfigurationSource(fileName);
assertNotNull(list);
assertEquals(39, list.siz... |
public static String htmlToPlain(final String text) {
if (text == null) {
return null;
}
CachedStringTransformationResult threadLocalCachedHtmlToPlain = cachedHtmlToPlain.get();
if(threadLocalCachedHtmlToPlain.input.equals(text))
return threadLocalCachedHtmlToPlain.output;
String output = HtmlUtils.html... | @Test
public void testHtmlToPlain_shouldRetainTrailingNonBreakingSpaces() {
String input = "<html>\n" +
" <head>\n" +
" \n" +
" </head>\n" +
" <body>\n" +
" <p>\n" +
" Zero\n" +
" </p>\n" +
" <p>\n" +
" One \n" +
" </p>\n" +
" <p>\n" +
... |
public VerificationStateEntry maybeCreateVerificationStateEntry(long producerId, int sequence, short epoch) {
VerificationStateEntry entry = verificationStates.computeIfAbsent(producerId, pid ->
new VerificationStateEntry(time.milliseconds(), sequence, epoch)
);
entry.maybeUpdateLowe... | @Test
public void testSequenceAndEpochInVerificationEntry() {
VerificationStateEntry originalEntry = stateManager.maybeCreateVerificationStateEntry(producerId, 1, epoch);
VerificationGuard originalEntryVerificationGuard = originalEntry.verificationGuard();
verifyEntry(originalEntryVerificat... |
@Override
public void filter(final T inMesg) {
try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".filter")) {
addPerfMarkTags(inMesg);
runFilters(inMesg, initRunningFilterIndex(inMesg));
}
} | @Test
void testInboundFilterChain() {
final SimpleInboundFilter inbound1 = spy(new SimpleInboundFilter(true));
final SimpleInboundFilter inbound2 = spy(new SimpleInboundFilter(false));
final ZuulFilter[] filters = new ZuulFilter[] {inbound1, inbound2};
final FilterUsageNotifier not... |
@Override
public <R> HoodieData<HoodieRecord<R>> tagLocation(
HoodieData<HoodieRecord<R>> records, HoodieEngineContext context,
HoodieTable hoodieTable) {
return HoodieJavaRDD.of(HoodieJavaRDD.getJavaRDD(records)
.mapPartitionsWithIndex(locationTagFunction(hoodieTable.getMetaClient()), true));... | @Test
public void testTagLocationAndPartitionPathUpdateDisabled() throws Exception {
final String newCommitTime = "001";
final String oldPartitionPath = "1970/01/01";
final int numRecords = 10;
List<HoodieRecord> newRecords = dataGen.generateInserts(newCommitTime, numRecords);
List<HoodieRecord> ... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void resolutionTooHigh() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/resourcepack_resolution.txt")),
CrashReportAnalyzer.Rule.RESOLUTION_TOO_HIGH);
} |
public static void addEstimateNumKeysMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
streamsMetrics,
... | @Test
public void shouldAddEstimateNumKeysMetric() {
final String name = "estimate-num-keys";
final String description =
"Estimated number of keys in the active and unflushed immutable memtables and storage";
runAndVerifyMutableMetric(
name,
description,
... |
static void enableStatisticManagementOnNodes(HazelcastClientInstanceImpl client, String cacheName,
boolean statOrMan, boolean enabled) {
Collection<Member> members = client.getClientClusterService().getMemberList();
Collection<Future> futures = new ArrayL... | @Test
public void testEnableStatisticManagementOnNodes() {
enableStatisticManagementOnNodes(client, CACHE_NAME, false, false);
} |
public static boolean getBoolean(final Map<String, Object> configs, final String key, final boolean defaultValue) {
final Object value = configs.getOrDefault(key, defaultValue);
if (value instanceof Boolean) {
return (boolean) value;
} else if (value instanceof String) {
... | @Test
public void testGetBoolean() {
String key = "test.key";
boolean defaultValue = true;
Map<String, Object> config = new HashMap<>();
config.put("some.other.key", false);
assertEquals(defaultValue, ConfigUtils.getBoolean(config, key, defaultValue));
config = new ... |
@Override
@WithSpan
public QueryResult doRun(SearchJob job, Query query, OSGeneratedQueryContext queryContext) {
if (query.searchTypes().isEmpty()) {
return QueryResult.builder()
.query(query)
.searchTypes(Collections.emptyMap())
.e... | @Test
public void executesSearchForEmptySearchTypes() {
final Query query = Query.builder()
.id("query1")
.query(ElasticsearchQueryString.of(""))
.timerange(RelativeRange.create(300))
.build();
final Search search = Search.builder().que... |
@Override
public void stop() {
if (!isStarted()) return;
try {
runner.stop();
super.stop();
}
catch (IOException ex) {
addError("server shutdown error: " + ex, ex);
}
} | @Test
public void testStopWhenNotStarted() throws Exception {
appender.stop();
assertEquals(0, runner.getStartCount());
} |
public void handleSnapshot(MetadataImage image, KRaftMigrationOperationConsumer operationConsumer) {
handleTopicsSnapshot(image.topics(), operationConsumer);
handleConfigsSnapshot(image.configs(), operationConsumer);
handleClientQuotasSnapshot(image.clientQuotas(), image.scram(), operationConsum... | @Test
public void testReconcileSnapshotEmptyZk() {
// These test clients don't return any data in their iterates, so this simulates an empty ZK
CapturingTopicMigrationClient topicClient = new CapturingTopicMigrationClient();
CapturingConfigMigrationClient configClient = new CapturingConfigM... |
public static RestSettingBuilder delete(final RestIdMatcher idMatcher) {
return single(HttpMethod.DELETE, checkNotNull(idMatcher, "ID Matcher should not be null"));
} | @Test
public void should_delete_with_matcher() throws Exception {
server.resource("targets",
delete("1").request(eq(header(HttpHeaders.IF_MATCH), "moco")).response(status(200))
);
running(server, () -> {
HttpResponse httpResponse = helper.deleteForResponseWithHea... |
@Override
public String toString() {
return "compositeResponse: " + compositeResponse;
} | @Test
public void shouldDeserializeSuccessfulJsonResponse() throws IOException {
final String json = IOUtils.toString(
this.getClass().getResourceAsStream(
"/org/apache/camel/component/salesforce/api/dto/composite_response_example_success.json"),
Stan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.