focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
protected final <T> void convertAndProcessManyJobs(Function<List<T>, List<T>> itemSupplier, Function<T, Job> toJobFunction, Consumer<Integer> amountOfProcessedJobsConsumer) {
int amountOfProcessedJobs = 0;
List<T> items = getItemsToProcess(itemSupplier, null);
while (!items.isEmpty()) {
... | @Test
void convertAndProcessManyJobsDoesNotSaveNullItems() {
// GIVEN
List<Object> items = asList(null, null);
Function<Object, List<Job>> toJobFunction = x -> asList(null, null);
// WHEN
task.convertAndProcessManyJobs(items, toJobFunction, System.out::println);
// ... |
public void tryResetPopRetryTopic(final List<MessageExt> msgs, String consumerGroup) {
String popRetryPrefix = MixAll.RETRY_GROUP_TOPIC_PREFIX + consumerGroup + "_";
for (MessageExt msg : msgs) {
if (msg.getTopic().startsWith(popRetryPrefix)) {
String normalTopic = KeyBuilder... | @Test
public void testTryResetPopRetryTopic() {
TopicRouteData topicRouteData = new TopicRouteData();
topicRouteData.getBrokerDatas().add(createBrokerData());
MessageExt messageExt = createMessageExt();
List<MessageExt> msgs = new ArrayList<>();
messageExt.setTopic(MixAll.RET... |
boolean eosEnabled() {
return StreamsConfigUtils.eosEnabled(processingMode);
} | @Test
public void shouldNotHaveEosEnabledIfEosDisabled() {
assertThat(nonEosStreamsProducer.eosEnabled(), is(false));
} |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from... | @Test
public void shouldAllowNonStringKeyColumn() {
// Given:
final CreateStream statement = new CreateStream(
SOME_NAME,
TableElements.of(tableElement("k", new Type(SqlTypes.INTEGER), KEY_CONSTRAINT)),
false,
true,
withProperties,
false
);
// When:
... |
public static boolean shutdownThread(Thread thread) {
return shutdownThread(thread, SHUTDOWN_WAIT_MS);
} | @Test (timeout = 3000)
public void testShutdownThread() {
Thread thread = new Thread(sampleRunnable);
thread.start();
boolean ret = ShutdownThreadsHelper.shutdownThread(thread);
boolean isTerminated = !thread.isAlive();
assertEquals("Incorrect return value", ret, isTerminated);
assertTrue("Thr... |
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception {
LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation);
MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con... | @Test
public void shouldSerialize_CaseInsensitiveString_whenUsedInConfigAttributeValue() {//for instance FetchTask uses PathFromAncestor which has CaseInsensitiveString
CruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("uppest", "upper", "downer", "downest");
cruiseConfig.initializeServ... |
public Component buildProject(ScannerReport.Component project, String scmBasePath) {
this.rootComponent = project;
this.scmBasePath = trimToNull(scmBasePath);
Node root = createProjectHierarchy(project);
return buildComponent(root, "", "");
} | @Test
void project_description_is_loaded_from_db_if_not_on_main_branch() {
String reportDescription = randomAlphabetic(5);
ScannerReport.Component reportProject = newBuilder()
.setType(PROJECT)
.setDescription(reportDescription)
.build();
Component root = newUnderTest(SOME_PROJECT_ATTRI... |
public String getUserName() {
return "cruise";
} | @Test
void shouldReturnCruiseAsUser() {
assertThat(dependencyMaterial.getUserName()).isEqualTo("cruise");
} |
public static IpAddress valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new IpAddress(Version.INET, bytes);
} | @Test
public void testEqualityIPv6() {
new EqualsTester()
.addEqualityGroup(
IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8888"),
IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8888"))
.addEqualityGroup(
IpAddress.valueO... |
public void watchDataChange(final String key,
final BiConsumer<String, String> updateHandler,
final Consumer<String> deleteHandler) {
Watch.Listener listener = watch(updateHandler, deleteHandler);
if (!watchCache.containsKey(key)) {
... | @Test
public void testWatchDataChange() {
BiConsumer<String, String> updateHandler = mock(BiConsumer.class);
Consumer<String> deleteHandler = mock(Consumer.class);
etcdClient.watchDataChange(WATCH_DATA_CHANGE_KEY, updateHandler, deleteHandler);
etcdClient.watchClose(WATCH_DATA_CHANGE... |
@Override
public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys, EntryProcessor<K, V, T> entryProcessor,
Object... arguments) {
return cache.invokeAll(keys, entryProcessor, arguments);
} | @Test
public void testInvokeAll() {
cache.put(23, "value-23");
cache.put(42, "value-42");
cache.put(65, "value-65");
Set<Integer> keys = new HashSet<>(asList(23, 65, 88));
Map<Integer, EntryProcessorResult<String>> resultMap = adapter.invokeAll(keys, new ICacheReplaceEntryPr... |
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
String path = ((HttpServletRequest) req).getRequestURI().replaceFirst(((HttpServletRequest) req).getContextPath(), "");
MAX_AGE_BY_PATH.entrySet().stream()
.filter(m -> pat... | @Test
public void max_age_is_set_to_one_year_on_css() throws Exception {
HttpServletRequest request = newRequest("/css/sonar.css");
underTest.doFilter(request, response, chain);
verify(response).addHeader("Cache-Control", format("max-age=%s", 31_536_000));
} |
@Override
public void handlerDiscoveryUpstreamData(final DiscoverySyncData discoverySyncData) {
super.getWasmExtern(METHOD_NAME)
.map(handlerDiscoveryUpstreamData -> {
// WASI cannot easily pass Java objects like JNI, here we pass Long as arg
// then w... | @Test
public void handlerDiscoveryUpstreamDataTest() {
discoveryUpstreamDataHandler = mock(DiscoveryUpstreamDataHandler.class);
discoveryUpstreamDataHandler.handlerDiscoveryUpstreamData(discoverySyncData);
testWasmPluginDiscoveryHandler.handlerDiscoveryUpstreamData(discoverySyncData);
... |
public void write(byte[] b, int off, int len) throws IOException {
requireOpened();
if (len > 0) {
stream.write(b, off, len);
}
} | @Test
void writeAfterCloseShouldThrowException() {
assertThatExceptionOfType(IOException.class)
.isThrownBy(
() -> {
final RefCountedFileWithStream fileUnderTest =
getClosedRefCountedFileWithContent(
... |
@Udf(description = "Splits a string into an array of substrings based on a delimiter.")
public List<String> split(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The delimiter to spli... | @Test
public void shouldReturnOriginalStringOnNotFoundDelimiter() {
assertThat(splitUdf.split("", "."), contains(""));
assertThat(splitUdf.split("x-y", "."), contains("x-y"));
} |
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {... | @Test
public void testSplitStringWithDelimiterAndEnclosureNullRemoveEnclosure() {
String mask = "Hello%s world";
String[] chunks = {"Hello", " world"};
String stringToSplit = String.format( mask, DELIMITER1 );
String[] result = Const.splitString( stringToSplit, DELIMITER1, null, true );
assertSpl... |
public static Builder in(Table table) {
return new Builder(table);
} | @TestTemplate
public void testNoSnapshot() {
// a table has no snapshot when it just gets created and no data is loaded yet
// if not handled properly, NPE will be thrown in collect()
Iterable<DataFile> files = FindFiles.in(table).collect();
// verify an empty collection of data file is returned
... |
SSLContext build() throws IOException {
try {
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(null);
if (hasCertificateFile()) {
keystore.setKeyEntry("cert", privateKey(privateKeyFile), new char[0], certificates(certificateFile));
... | @Test
void successfully_constructs_sslcontext_when_no_builder_parameter_given() {
SSLContext sslContext = Assertions.assertDoesNotThrow(() -> new SslContextBuilder().build());
assertEquals("TLSv1.3", sslContext.getProtocol());
} |
@Override
public UseDefaultInsertColumnsToken generateSQLToken(final InsertStatementContext insertStatementContext) {
String tableName = Optional.ofNullable(insertStatementContext.getSqlStatement().getTable()).map(optional -> optional.getTableName().getIdentifier().getValue()).orElse("");
Optional<U... | @Test
void assertGenerateSQLTokenFromPreviousSQLTokens() {
generator.setPreviousSQLTokens(EncryptGeneratorFixtureBuilder.getPreviousSQLTokens());
assertThat(generator.generateSQLToken(EncryptGeneratorFixtureBuilder.createInsertStatementContext(Collections.emptyList())).toString(),
is... |
@Override
public String getName() {
return FUNCTION_NAME;
} | @Test
public void testMultiplicationTransformFunction() {
ExpressionContext expression = RequestContextUtils.getExpression(
String.format("mult(%s,%s,%s,%s,%s)", INT_SV_COLUMN, LONG_SV_COLUMN, FLOAT_SV_COLUMN, DOUBLE_SV_COLUMN,
STRING_SV_COLUMN));
TransformFunction transformFunction = Tran... |
static BlockStmt getTextIndexNormalizationVariableDeclaration(final String variableName,
final TextIndexNormalization textIndexNormalization) {
if (textIndexNormalization.getInlineTable() == null && textIndexNormalization.getTableLocator() != nul... | @Test
void getTextIndexNormalizationVariableDeclaration() throws IOException {
String variableName = "variableName";
BlockStmt retrieved =
KiePMMLTextIndexNormalizationFactory.getTextIndexNormalizationVariableDeclaration(variableName,
... |
@Override
public FileConfigDO getFileConfig(Long id) {
return fileConfigMapper.selectById(id);
} | @Test
public void testGetFileConfig() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false);
fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbFileConfig.getId();
// 调用,并断言
assertPojoEquals(dbFileConfig, f... |
@Override
public Set<SystemScope> getAll() {
return repository.getAll();
} | @Test
public void getAll() {
assertThat(service.getAll(), equalTo(allScopes));
} |
@Override
public Integer doCall() throws Exception {
CommandLineHelper
.loadProperties(p -> {
for (String k : p.stringPropertyNames()) {
String v = p.getProperty(k);
printer().printf("%s = %s%n", k, v);
}... | @Test
public void shouldListUserConfig() throws Exception {
UserConfigHelper.createUserConfig("""
camel-version=latest
kamelets-version=greatest
foo=bar
""");
ConfigList command = new ConfigList(new CamelJBangMain().withPrinter(printer... |
public static boolean matchesSelector(LabelSelector labelSelector, HasMetadata cr) {
if (labelSelector != null && labelSelector.getMatchLabels() != null) {
if (cr.getMetadata().getLabels() != null) {
return cr.getMetadata().getLabels().entrySet().containsAll(labelSelector.getMatchLab... | @Test
public void testMatchesSelector() {
Pod testResource = new PodBuilder()
.withNewMetadata()
.withName("test-pod")
.endMetadata()
.withNewSpec()
.endSpec()
.build();
// Resources without any la... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldFailOnPersistentQueryLimitClauseTable() {
// Given:
final SingleStatementContext stmt
= givenQuery("CREATE TABLE X AS SELECT * FROM TEST1 LIMIT 5;");
// Then:
Exception exception = assertThrows(KsqlException.class, () -> {
builder.buildStatement(stmt);
})... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, CALLBACK_PATH);
if (provider != null) {
handleProvider(request, response, provider);
}
} | @Test
public void do_filter_with_context() {
when(request.getContextPath()).thenReturn("/sonarqube");
when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
when(threadLocalUserSession.hasSe... |
@Override
public void deregisterInstance(String serviceName, String ip, int port) throws NacosException {
deregisterInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);
} | @Test
void testDeregisterInstance2() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
String ip = "1.1.1.1";
int port = 10000;
//when
client.deregisterInstance(serviceName, groupName, ip, port);
//then
... |
@Override
public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc,
boolean addFieldName, boolean addCr ) {
String retval = "";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
... | @Test
public void testGetFieldDefinition() {
assertEquals( "FOO TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) );
assertEquals( "TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, false, false ) );
... |
@Override public Span annotate(String value) {
return annotate(clock.currentTimeMicroseconds(), value);
} | @Test void annotate() {
span.annotate("foo");
span.flush();
assertThat(spans.get(0).containsAnnotation("foo"))
.isTrue();
} |
public static boolean matricesSame(int[][] m1, int[][] m2) {
if (m1.length != m2.length) {
return false;
} else {
var answer = false;
for (var i = 0; i < m1.length; i++) {
if (arraysSame(m1[i], m2[i])) {
answer = true;
} else {
answer = false;
brea... | @Test
void matricesSameTest() {
var matrix1 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}};
var matrix2 = new int[][]{{1, 4, 2, 6}, {5, 8, 6, 7}};
assertTrue(ArrayUtilityMethods.matricesSame(matrix1, matrix2));
} |
@Override
public V get(K key) {
return map.get(key);
} | @Test
public void testGet() {
map.put(42, "foobar");
String result = adapter.get(42);
assertEquals("foobar", result);
} |
public String getFilepath() {
return filepath;
} | @Test
public void testConstructorMessage() {
try {
throw new KettleFileNotFoundException( errorMessage );
} catch ( KettleFileNotFoundException e ) {
assertEquals( null, e.getCause() );
assertTrue( e.getMessage().contains( errorMessage ) );
assertEquals( null, e.getFilepath() );
}
... |
public static <E> Set<E> createHashSet(int expectedMapSize) {
final int initialCapacity = (int) (expectedMapSize / HASHSET_DEFAULT_LOAD_FACTOR) + 1;
return new HashSet<>(initialCapacity, HASHSET_DEFAULT_LOAD_FACTOR);
} | @Test
public void testCreateHashSet() {
Set set = createHashSet(5);
assertInstanceOf(HashSet.class, set);
} |
public String getProgress(final boolean running, final long size, final long transferred) {
return this.getProgress(System.currentTimeMillis(), running, size, transferred);
} | @Test
public void testProgressRemaining3() {
final long start = System.currentTimeMillis();
Speedometer m = new Speedometer(start, true);
assertEquals("900.0 KB (900,000 bytes) of 1.0 MB (90%, 450.0 KB/sec, 1 seconds remaining)",
m.getProgress(start + 2000L, true, 1000000L, 9... |
@PostMapping("/save.json")
@AuthAction(AuthService.PrivilegeType.WRITE_RULE)
public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) {
String app = reqVo.getApp();
if (StringUtil.isBlank(app)) {
return Result.ofFail(-1, "app can't be null or empty");
}... | @Test
public void testUpdateApi() throws Exception {
String path = "/gateway/api/save.json";
// Add one entity to memory repository for update
ApiDefinitionEntity addEntity = new ApiDefinitionEntity();
addEntity.setApp(TEST_APP);
addEntity.setIp(TEST_IP);
addEntity.s... |
public static Date parse(String date, ParsePosition pos) throws ParseException {
Exception fail = null;
try {
int offset = pos.getIndex();
// extract year
int year = parseInt(date, offset, offset += 4);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract... | @Test
@SuppressWarnings("UndefinedEquals")
public void testDateParseSpecialTimezone() throws ParseException {
String dateStr = "2018-06-25T00:02:00-02:58";
Date date = ISO8601Utils.parse(dateStr, new ParsePosition(0));
GregorianCalendar calendar = createUtcCalendar();
calendar.set(2018, Calendar.JUN... |
@Override protected void propagationField(String keyName, String value) {
attachments.put(keyName, value);
} | @Test void propagationField() {
request.propagationField("b3", "d");
assertThat(attachments).containsEntry("b3", "d");
} |
public void run(String[] args) {
if (!parseArguments(args)) {
showOptions();
return;
}
if (command == null) {
System.out.println("Error: Command is empty");
System.out.println();
showOptions();
return;
}
if ... | @Test
public void testUnknownOption() {
Main main = new Main();
assertDoesNotThrow(() -> main.run("-c encrypt -xxx foo".split(" ")));
} |
@Override
public Result apply(ApplyNode applyNode, Captures captures, Context context)
{
if (applyNode.getMayParticipateInAntiJoin()) {
return Result.empty();
}
Assignments subqueryAssignments = applyNode.getSubqueryAssignments();
if (subqueryAssignments.size() != 1)... | @Test
public void testFiresForInPredicate()
{
tester().assertThat(new TransformUncorrelatedInPredicateSubqueryToDistinctInnerJoin())
.on(p -> p.apply(
assignment(
p.variable("x"),
inSubquery(p.variabl... |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldApplyFirstMigration() throws Exception {
// Given:
command = PARSER.parse("-n");
createMigrationFile(1, NAME, migrationsDir, COMMAND);
// extra migration to ensure only the first is applied
createMigrationFile(3, NAME, migrationsDir, COMMAND);
when(versionQueryResult.ge... |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldThrowIfCleanupPolicyConfigPresentInCreateStreamAs() {
// Given:
givenStatement("CREATE STREAM x WITH (kafka_topic='topic', partitions=1, cleanup_policy='whatever') AS SELECT * FROM SOURCE;");
// When:
final Exception e = assertThrows(
KsqlException.class,
() ->... |
@Override
public void process(ConfigChangedEvent event) {
if (event.getChangeType() == ConfigChangeType.DELETED) {
receiveConfigInfo("");
return;
}
receiveConfigInfo(event.getContent());
} | @Test
void process() {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route");
StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf("")));
meshAppRuleListener.register(standardMeshRuleRouter);
ConfigChangedEvent... |
@VisibleForTesting
static long fromDuration(Duration duration, TimeUnit unit) {
return unit.convert(duration.toNanos(), TimeUnit.NANOSECONDS);
} | @Test
public void fromDuration() {
assertThat(TimerResultParser.fromDuration(Duration.ofNanos(5L), TimeUnit.NANOSECONDS))
.isEqualTo(5L);
assertThat(
TimerResultParser.fromDuration(
Duration.of(5L, ChronoUnit.MICROS), TimeUnit.MICROSECONDS))
.isEqualTo(5L);
asse... |
@VisibleForTesting
protected RunnerApi.Pipeline resolveArtifacts(RunnerApi.Pipeline pipeline) {
RunnerApi.Pipeline.Builder pipelineBuilder = pipeline.toBuilder();
RunnerApi.Components.Builder componentsBuilder = pipelineBuilder.getComponentsBuilder();
componentsBuilder.clearEnvironments();
for (Map.En... | @Test
public void testResolveArtifacts() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
DataflowRunner runner = DataflowRunner.fromOptions(options);
String stagingLocation = options.getStagingLocation().replaceFirst("/$", "");
RunnerApi.ArtifactInformation fooLocalArtif... |
public static <T extends Enum<T>> Validator enumValues(final Class<T> enumClass) {
final String[] enumValues = EnumSet.allOf(enumClass)
.stream()
.map(Object::toString)
.toArray(String[]::new);
final String[] validValues = Arrays.copyOf(enumValues, enumValues.length + 1);
validValue... | @Test
public void shouldFailIfValueNotInEnum() {
// Given:
final Validator validator = ConfigValidators.enumValues(TestEnum.class);
// When:
final Exception e = assertThrows(
ConfigException.class,
() -> validator.ensureValid("propName", "NotValid")
);
// Then:
assertThat... |
@Override
public int hashCode() {
int result = major;
result = 31 * result + minor;
return result;
} | @Test
public void hashCodeTest() {
assertEquals(Version.UNKNOWN.hashCode(), Version.UNKNOWN.hashCode());
assertTrue(Version.UNKNOWN.hashCode() != Version.of(4, 0).hashCode());
} |
public static List<Event> computeEventDiff(final Params params) {
final List<Event> events = new ArrayList<>();
emitPerNodeDiffEvents(createBaselineParams(params), events);
emitWholeClusterDiffEvent(createBaselineParams(params), events);
emitDerivedBucketSpaceStatesDiffEvents(params, ev... | @Test
void cluster_down_event_without_reason_annotation_emits_generic_down_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3");
final List<Event> ... |
@Override
public CompletableFuture<Void> heartbeatFromJobManager(
ResourceID resourceID, AllocatedSlotReport allocatedSlotReport) {
return jobManagerHeartbeatManager.requestHeartbeat(resourceID, allocatedSlotReport);
} | @Test
void testJobManagerBecomesUnreachableTriggersDisconnect() throws Exception {
final ResourceID jmResourceId = ResourceID.generate();
runJobManagerHeartbeatTest(
jmResourceId,
failedRpcEnabledHeartbeatServices,
jobMasterGatewayBuilder ->
... |
@Override
public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {
if (args.isEmpty()) {
printHelp(out);
return 0;
}
OutputStream output = out;
if (args.size() > 1) {
output = Util.fileOrStdout(args.get(args.size() - 1), out);
arg... | @Test
void fileDoesNotExist() throws Exception {
assertThrows(FileNotFoundException.class, () -> {
File output = new File(INPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(new File(INPUT_DIR, "/doNotExist").getAbsolutePath(), output.getAbsolutePath());
new ConcatTool().run(... |
private int transitionToObserver(final CommandLine cmd)
throws IOException {
String[] argv = cmd.getArgs();
if (argv.length != 1) {
errOut.println("transitionToObserver: incorrect number of arguments");
printUsage(errOut, "-transitionToObserver", USAGE_DFS_MERGED);
return -1;
}
... | @Test
public void testTransitionToObserver() throws Exception {
assertEquals(0, runTool("-transitionToObserver", "nn1"));
Mockito.verify(mockProtocol).transitionToObserver(anyReqInfo());
} |
@Override
public Collection<CommittableWithLineage<CommT>> commit(
boolean fullyReceived, Committer<CommT> committer)
throws IOException, InterruptedException {
Collection<CommitRequestImpl<CommT>> requests = getPendingRequests(fullyReceived);
requests.forEach(CommitRequestIm... | @Test
void testCommit() throws IOException, InterruptedException {
final CheckpointCommittableManagerImpl<Integer> checkpointCommittables =
new CheckpointCommittableManagerImpl<>(1, 1, 1L, METRIC_GROUP);
checkpointCommittables.upsertSummary(new CommittableSummary<>(1, 1, 1L, 1, 0, 0)... |
public List<ErasureCodingPolicy> loadPolicy(String policyFilePath) {
try {
File policyFile = getPolicyFile(policyFilePath);
if (!policyFile.exists()) {
LOG.warn("Not found any EC policy file");
return Collections.emptyList();
}
return loadECPolicies(policyFile);
} catch (... | @Test
public void testNullECSchemaOptionValue() throws Exception {
PrintWriter out = new PrintWriter(new FileWriter(POLICY_FILE));
out.println("<?xml version=\"1.0\"?>");
out.println("<configuration>");
out.println("<layoutversion>1</layoutversion>");
out.println("<schemas>");
out.println(" <... |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void testNopExeptionHandler() {
pl.setPattern("%nopex %m%n");
pl.start();
String val = pl.doLayout(le);
assertThat(val, not(containsString("java.lang.Exception: Bogus exception")));
} |
public static boolean checkOtherParams(String otherParams) {
return !StringUtils.isEmpty(otherParams) && !JSONUtils.checkJsonValid(otherParams);
} | @Test
public void testCheckOtherParams() {
Assertions.assertFalse(CheckUtils.checkOtherParams(null));
Assertions.assertFalse(CheckUtils.checkOtherParams(""));
Assertions.assertTrue(CheckUtils.checkOtherParams("xxx"));
Assertions.assertFalse(CheckUtils.checkOtherParams("{}"));
... |
@Override
public DescribeShareGroupsResult describeShareGroups(final Collection<String> groupIds,
final DescribeShareGroupsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, ShareGroupDescription> future =
DescribeShareGroupsHandl... | @Test
public void testDescribeMultipleShareGroups() {
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
env.kafkaClient().prepareResponse(prepareFindCoordinatorResponse(Errors.NONE, env.... |
@Override
public double read() {
return gaugeSource.read();
} | @Test
public void whenLongProbe() {
metricsRegistry.registerStaticProbe(this, "foo", MANDATORY,
(LongProbeFunction) o -> 10);
DoubleGauge gauge = metricsRegistry.newDoubleGauge("foo");
double actual = gauge.read();
assertEquals(10, actual, 0.1);
} |
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) {
return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName);
} | @Test(expected = IllegalArgumentException.class)
public void of_withWrongParts() {
ScheduledTaskHandler.of("urn:hzScheduledTaskHandler:-\u00000\u0000Scheduler");
} |
public String nextNonCliCommand() {
String line;
do {
line = terminal.readLine();
} while (maybeHandleCliSpecificCommands(line));
return line;
} | @Test
public void shouldExecuteCliCommands() {
// Given:
when(lineSupplier.get())
.thenReturn(CLI_CMD_NAME)
.thenReturn("not a CLI command;");
// When:
console.nextNonCliCommand();
// Then:
verify(cliCommand).execute(eq(ImmutableList.of()), any());
} |
public Value parse(String json) {
return this.delegate.parse(json);
} | @Test
public void testOrdinaryInteger() throws Exception {
final JsonParser parser = new JsonParser();
final Value msgpackValue = parser.parse("12345");
assertTrue(msgpackValue.getValueType().isNumberType());
assertTrue(msgpackValue.getValueType().isIntegerType());
assertFals... |
public MessageType convert(Schema avroSchema) {
if (!avroSchema.getType().equals(Schema.Type.RECORD)) {
throw new IllegalArgumentException("Avro schema must be a record.");
}
return new MessageType(avroSchema.getFullName(), convertFields(avroSchema.getFields(), ""));
} | @Test
public void testParquetInt96DefaultFail() throws Exception {
Schema schema = Schema.createRecord("myrecord", null, null, false);
MessageType parquetSchemaWithInt96 =
MessageTypeParser.parseMessageType("message myrecord {\n required int96 int96_field;\n}\n");
assertThrows(
"INT96 i... |
public String retrieveBucketStats(ClientParameters.SelectionType type, String id, BucketId bucketId, String bucketSpace) throws BucketStatsException {
String documentSelection = createDocumentSelection(type, id);
StatBucketMessage msg = new StatBucketMessage(bucketId, bucketSpace, documentSelection);
... | @Test
void testRetrieveBucketStats() throws BucketStatsException {
String docId = "id:ns:type::another";
String bucketInfo = "I like turtles!";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId(docId));
StatBucketReply reply = new StatBucketReply();
reply.setRes... |
@Override
public void deletePost(Long id) {
// 校验是否存在
validatePostExists(id);
// 删除部门
postMapper.deleteById(id);
} | @Test
public void testValidatePost_notFoundForDelete() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> postService.deletePost(id), POST_NOT_FOUND);
} |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateDiscountActivity(DiscountActivityUpdateReqVO updateReqVO) {
// 校验存在
DiscountActivityDO discountActivity = validateDiscountActivityExists(updateReqVO.getId());
if (discountActivity.getStatus().equals(CommonStatusEnu... | @Test
public void testUpdateDiscountActivity_success() {
// mock 数据(商品)
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class);
discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条存在的数据
// mock 数据(活动)
DiscountProductDO dbDiscountProduct01 = ... |
public String getString(HazelcastProperty property) {
String value = properties.getProperty(property.getName());
if (value != null) {
return value;
}
value = property.getSystemProperty();
if (value != null) {
return value;
}
HazelcastProp... | @Test
public void setProperty_inheritActualValueOfParentProperty() {
config.setProperty(ClusterProperty.IO_THREAD_COUNT.getName(), "1");
HazelcastProperties properties = new HazelcastProperties(config);
String inputIOThreadCount = properties.getString(ClusterProperty.IO_INPUT_THREAD_COUNT);... |
public static Area getArea(Integer id) {
return areas.get(id);
} | @Test
public void testGetArea() {
// 调用:北京
Area area = AreaUtils.getArea(110100);
// 断言
assertEquals(area.getId(), 110100);
assertEquals(area.getName(), "北京市");
assertEquals(area.getType(), AreaTypeEnum.CITY.getType());
assertEquals(area.getParent().getId(), 1... |
@Override
public void start() {
boolean isTelemetryActivated = config.getBoolean(SONAR_TELEMETRY_ENABLE.getKey())
.orElseThrow(() -> new IllegalStateException(String.format("Setting '%s' must be provided.", SONAR_TELEMETRY_URL.getKey())));
boolean hasOptOut = internalProperties.read(I_PROP_OPT_OUT).isPr... | @Test
void write_sequence_as_one_if_not_previously_present() {
initTelemetrySettingsToDefaultValues();
when(lockManager.tryLock(any(), anyInt())).thenReturn(true);
settings.setProperty("sonar.telemetry.frequencyInSeconds", "1");
mockDataJsonWriterDoingSomething();
underTest.start();
verify(i... |
public static String v6ipProcess(String netAddress) {
int part;
String subAddress;
boolean isAsterisk = isAsterisk(netAddress);
boolean isMinus = isMinus(netAddress);
if (isAsterisk && isMinus) {
part = 6;
int lastColon = netAddress.lastIndexOf(':');
... | @Test
public void testV6ipProcess() {
String remoteAddr = "5::7:6:1-200:*";
Assert.assertEquals(AclUtils.v6ipProcess(remoteAddr), "0005:0000:0000:0000:0007:0006");
remoteAddr = "5::7:6:1-200";
Assert.assertEquals(AclUtils.v6ipProcess(remoteAddr), "0005:0000:0000:0000:0000:0007:0006"... |
@Override
@NonNull public CharSequence getKeyboardName() {
return mKeyboardName;
} | @Test
public void testKeyboardPopupCharacterStringConstructor() throws Exception {
AnyPopupKeyboard keyboard =
new AnyPopupKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
"ûūùú",
SIMPLE_KeyboardDimens,
... |
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) {
List<Object> valuesInOrder =
schema.getFields().stream()
.map(
field -> {
try {
org.apache.avro.Schema.Field avroField =
rec... | @Test
public void testToBeamRow_projection() {
long testId = 123L;
// recordSchema is a projection of FLAT_TYPE schema
org.apache.avro.Schema recordSchema =
org.apache.avro.SchemaBuilder.record("__root__").fields().optionalLong("id").endRecord();
GenericData.Record record = new GenericData.Rec... |
@Override
public void add(T item) {
final int sizeAtTimeOfAdd;
synchronized (items) {
items.add(item);
sizeAtTimeOfAdd = items.size();
}
/*
WARNING: It is possible that the item that was just added to the list
has been processed by an ... | @Test
public void eventTrigger() {
TestAccumulator accumulator = new TestAccumulator();
accumulator.add(new TestItem("a"));
accumulator.add(new TestItem("b"));
accumulator.add(new TestItem("c"));
accumulator.add(new TestItem("d"));
assertTrue("should not have fired ye... |
Collection<AzureAddress> getAddresses() {
LOGGER.finest("Fetching OAuth Access Token");
final String accessToken = fetchAccessToken();
LOGGER.finest("Fetching instances for subscription '%s' and resourceGroup '%s'",
subscriptionId, resourceGroup);
Collection<AzureAddress>... | @Test
public void getAddressesCurrentSubscriptionCurrentResourceGroupCurrentScaleSetNoTag() {
// given
given(azureComputeApi.instances(SUBSCRIPTION_ID, RESOURCE_GROUP, SCALE_SET, null, ACCESS_TOKEN)).willReturn(ADDRESSES);
AzureConfig azureConfig = AzureConfig.builder().setInstanceMetadataA... |
public void setContract(@Nullable Produce contract)
{
this.contract = contract;
setStoredContract(contract);
handleContractState();
} | @Test
public void cabbageContractCabbageDeadAndCabbageDiseased()
{
// Get the two allotment patches
final FarmingPatch patch1 = farmingGuildPatches.get(Varbits.FARMING_4773);
final FarmingPatch patch2 = farmingGuildPatches.get(Varbits.FARMING_4774);
assertNotNull(patch1);
assertNotNull(patch2);
// Speci... |
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),... | @Test
public void shouldParseInsertIntoStatement() {
// When:
List<CommandParser.ParsedCommand> commands = parse("INSERT INTO FOO SELECT * FROM BAR;");
// Then:
assertThat(commands.size(), is(1));
assertThat(commands.get(0).getStatement().isPresent(), is (false));
assertThat(commands.get(0).g... |
public Searcher searcher() {
return new Searcher();
} | @Test
void require_that_not_works_when_k_is_2() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
feature("a").inSet("1"),
feature("b").inSet("1"),
... |
public boolean setNewAuthor(DefaultIssue issue, @Nullable String newAuthorLogin, IssueChangeContext context) {
if (isNullOrEmpty(newAuthorLogin)) {
return false;
}
checkState(issue.authorLogin() == null, "It's not possible to update the author with this method, please use setAuthorLogin()");
issue... | @Test
void set_new_author() {
boolean updated = underTest.setNewAuthor(issue, "simon", context);
assertThat(updated).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get("author");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("simon");
assertThat(issue.mus... |
boolean isModified(Namespace namespace) {
Release release = releaseService.findLatestActiveRelease(namespace);
List<Item> items = itemService.findItemsWithoutOrdered(namespace.getId());
if (release == null) {
return hasNormalItems(items);
}
Map<String, String> releasedConfiguration = GSON.fr... | @Test
public void testParentNamespaceNotReleased() {
long childNamespaceId = 1, parentNamespaceId = 2;
Namespace childNamespace = createNamespace(childNamespaceId);
Namespace parentNamespace = createNamespace(parentNamespaceId);
Release childRelease = createRelease("{\"k1\":\"v3\", \"k2\":\"v2\"}");
... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertDate() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(LocalTimeType.LOCAL_DATE_TYPE)
.build();
BasicTypeDefine typeDefine = DmdbTypeConverter.INSTANCE.reconvert... |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate templa... | @Test
public void testRestLiAttachmentsParamResourceExpectNotPresent()
{
//This test makes sure that a resource method that expects attachments, but none are present in the request,
//is given a null for the RestLiAttachmentReader.
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerRe... |
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
if (!ExternalParser.check("gdalinfo")) {
return;
}
// first set up and run GDAL
// pr... | @Test
public void testParseMetadata() {
assumeTrue(canRun());
final String expectedNcInst =
"NCAR (National Center for Atmospheric Research, Boulder, CO, USA)";
final String expectedModelNameEnglish = "NCAR CCSM";
final String expectedProgramId = "Source file unknown ... |
private static Schema optional(Schema original) {
// null is first in the union because Parquet's default is always null
return Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), original));
} | @Test
public void testUnknownTwoLevelListOfLists() throws Exception {
// This tests the case where we don't detect a 2-level list by the repeated
// group's name, but it must be 2-level because the repeated group doesn't
// contain an optional or repeated element as required for 3-level lists
Schema l... |
@Udf(description = "Converts a TIMESTAMP value into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'"
+ " The system default time zone is used when no time zone is explicitly ... | @Test
public void testTimeZoneInUniversalTime() {
// Given:
final Timestamp timestamp = new Timestamp(1534353043000L);
// When:
final String universalTime = udf.formatTimestamp(timestamp,
"yyyy-MM-dd HH:mm:ss zz", "UTC");
// Then:
assertThat(universalTime, is("2018-08-15 17:10:43 UTC... |
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
final Method resourceMethod = resourceInfo.getResourceMethod();
final Class resourceClass = resourceInfo.getResourceClass();
if ((resourceMethod != null && (resourceMethod.isAnnotationPresent(SupportedSearch... | @Test
public void configureRegistersResponseFilterIfAnnotationIsPresentOnBoth() throws Exception {
final Class clazz = TestResourceWithClassAnnotation.class;
when(resourceInfo.getResourceClass()).thenReturn(clazz);
final Method method = TestResourceWithMethodAnnotation.class.getMethod("metho... |
public static UArrayType create(UType componentType) {
return new AutoValue_UArrayType(componentType);
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(
UArrayType.create(UClassType.create("java.lang.String")));
SerializableTester.reserializeAndAssert(UArrayType.create(UPrimitiveType.INT));
SerializableTester.reserializeAndAssert(
UArrayType.create(UArrayType.crea... |
public static Read read() {
return new Read(null, "", new Scan());
} | @Test
public void testReadingSplitAtFractionExhaustive() throws Exception {
final String table = tmpTable.getName();
final int numRows = 7;
createAndWriteData(table, numRows);
HBaseIO.Read read = HBaseIO.read().withConfiguration(conf).withTableId(table);
HBaseSource source =
new HBaseSour... |
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor(
DoFn<InputT, OutputT> fn) {
return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn);
} | @Test
public void testSplittableDoFnWithAllMethods() throws Exception {
MockFn fn = mock(MockFn.class);
DoFnInvoker<String, String> invoker = DoFnInvokers.invokerFor(fn);
final SomeRestrictionTracker tracker = mock(SomeRestrictionTracker.class);
final SomeRestrictionCoder coder = mock(SomeRestrictionC... |
public static @CheckForNull String getActionUrl(String itUrl, Action action) {
String urlName = action.getUrlName();
if (urlName == null) return null; // Should not be displayed
try {
if (new URI(urlName).isAbsolute()) {
return urlName;
}
} ca... | @Test
public void testGetActionUrl_unparseable() {
assertNull(Functions.getActionUrl(null, createMockAction("http://example.net/stuff?something=^woohoo")));
} |
@VisibleForTesting
int persistNextQueues(final Instant currentTime) {
final int slot = messagesCache.getNextSlotToPersist();
List<String> queuesToPersist;
int queuesPersisted = 0;
do {
queuesToPersist = getQueuesTimer.record(
() -> messagesCache.getQueuesToPersist(slot, currentTime.m... | @Test
void testPersistNextQueuesNoQueues() {
messagePersister.persistNextQueues(Instant.now());
verify(accountsManager, never()).getByAccountIdentifier(any(UUID.class));
} |
@Override
public String buildContext() {
final PluginHandleDO after = (PluginHandleDO) getAfter();
if (Objects.isNull(getBefore())) {
return String.format("the plugin-handle [%s] is %s", after.getField(), StringUtils.lowerCase(getType().getType().toString()));
}
return St... | @Test
public void createPluginHandleBuildContextTest() {
PluginHandleChangedEvent pluginChangedEvent = new PluginHandleChangedEvent(pluginHandleDO, null,
EventTypeEnum.PLUGIN_HANDLE_CREATE, "test-operator");
String context = String.format("the plugin-handle [%s] is %s", pluginHandleD... |
@Override public Future<RecordMetadata> send(ProducerRecord<K, V> record) {
return this.send(record, null);
} | @Test void should_add_parent_trace_when_context_injected_on_headers() {
ProducerRecord<String, String> record = new ProducerRecord<>(TEST_TOPIC, TEST_KEY, TEST_VALUE);
tracingProducer.injector.inject(parent, new KafkaProducerRequest(record));
tracingProducer.send(record);
mockProducer.completeNext();
... |
@Override
public List<FileEntriesLayer> createLayers() throws IOException {
// Add dependencies layers.
List<FileEntriesLayer> layers =
JarLayers.getDependenciesLayers(jarPath, ProcessingMode.packaged);
// Add layer for jar.
FileEntriesLayer jarLayer =
FileEntriesLayer.builder()
... | @Test
public void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException {
Path standardJar = Paths.get(Resources.getResource(STANDARD_SINGLE_DEPENDENCY_JAR).toURI());
StandardPackagedProcessor standardPackagedModeProcessor =
new StandardPackagedProcessor(standardJar, JAR_JAVA_VERSION);
... |
public static ReadRows readRows() {
return new AutoValue_JdbcIO_ReadRows.Builder()
.setFetchSize(DEFAULT_FETCH_SIZE)
.setOutputParallelization(true)
.setStatementPreparator(ignored -> {})
.build();
} | @Test
public void testReadRowsWithDataSourceConfiguration() {
PCollection<Row> rows =
pipeline.apply(
JdbcIO.readRows()
.withDataSourceConfiguration(DATA_SOURCE_CONFIGURATION)
.withQuery(String.format("select name,id from %s where name = ?", READ_TABLE_NAME))
... |
@Override
public Executor getExecutor(URL url) {
String name =
url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME));
int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS);
int threads = url.getParameter(THREADS_KEY,... | @Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + ALIVE_KEY
+ "=1000&" + QUEUES_KEY
+ "... |
public static Optional<ScalablePushRegistry> create(
final LogicalSchema logicalSchema,
final Supplier<List<PersistentQueryMetadata>> allPersistentQueries,
final boolean isTable,
final Map<String, Object> streamsProperties,
final Map<String, Object> consumerProperties,
final String s... | @Test
public void shouldCreate() {
// When:
final Optional<ScalablePushRegistry> registry =
ScalablePushRegistry.create(SCHEMA, Collections::emptyList, false,
ImmutableMap.of(StreamsConfig.APPLICATION_SERVER_CONFIG, "http://localhost:8088"),
ImmutableMap.of(), SOURCE_APP_ID, ks... |
static DateTime determineRotationPeriodAnchor(@Nullable DateTime lastAnchor, Period period) {
final Period normalized = period.normalizedStandard();
int years = normalized.getYears();
int months = normalized.getMonths();
int weeks = normalized.getWeeks();
int days = normalized.ge... | @Test
public void anchorCalculationShouldWorkWhenLastAnchorIsNotUTC() {
final DateTime initialTime = new DateTime(2020, 7, 31, 14, 48, 35, 0, DateTimeZone.UTC);
final InstantMillisProvider clock = new InstantMillisProvider(initialTime);
DateTimeUtils.setCurrentMillisProvider(clock);
... |
@Override
public boolean applyFilterToCamelHeaders(String headerName, Object headerValue, Exchange exchange) {
boolean answer = super.applyFilterToCamelHeaders(headerName, headerValue, exchange);
// using rest producer then headers are mapping to uri and query parameters using {key} syntax
/... | @Test
public void shouldDecideOnApplingHeaderFilterToTemplateTokens() {
final HttpRestHeaderFilterStrategy strategy = new HttpRestHeaderFilterStrategy(
"{uriToken1}{uriToken2}",
"q1=%7BqueryToken1%7D%26q2=%7BqueryToken2%3F%7D%26");
assertTrue(strategy.applyFilterToCa... |
public static RetryRegistry of(Configuration configuration, CompositeCustomizer<RetryConfigCustomizer> customizer) {
CommonRetryConfigurationProperties retryConfiguration = CommonsConfigurationRetryConfiguration.of(configuration);
Map<String, RetryConfig> retryConfigMap = retryConfiguration.getInstances... | @Test
public void testRetryRegistryFromPropertiesFile() throws ConfigurationException {
Configuration config = CommonsConfigurationUtil.getConfiguration(PropertiesConfiguration.class, TestConstants.RESILIENCE_CONFIG_PROPERTIES_FILE_NAME);
RetryRegistry registry = CommonsConfigurationRetryRegistry.o... |
public void writeUshort(int value) throws IOException {
if (value < 0 || value > 0xFFFF) {
throw new ExceptionWithContext("Unsigned short value out of range: %d", value);
}
write(value);
write(value >> 8);
} | @Test
public void testWriteUshort() throws IOException {
writer.writeUshort(0);
writer.writeUshort(0x1122);
writer.writeUshort(0x8899);
writer.writeUshort(0xFFFF);
expectData(0x00, 0x00,
0x22, 0x11,
0x99, 0x88,
0xFF, 0... |
@Override
protected void initChannel(Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
addPushMessageHandlers(pipeline);
} | @Test
void testInitChannel() throws Exception {
initializer.initChannel(channel);
assertNotNull(channel.pipeline().context(HttpServerCodec.class));
assertNotNull(channel.pipeline().context(HttpObjectAggregator.class));
assertNotNull(channel.pipeline().get("mockHandler"));
} |
public void awaitFutures(Collection<TopicPartition> topicPartitions) {
futuresFor(topicPartitions).forEach(future -> {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
log.error("Encountered an error while awaiting an errant reco... | @Test
public void testGetFutures() {
initializeReporter(true);
Collection<TopicPartition> topicPartitions = new ArrayList<>();
assertTrue(reporter.futures.isEmpty());
for (int i = 0; i < 4; i++) {
TopicPartition topicPartition = new TopicPartition("topic", i);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.