focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
protected void write(final MySQLPacketPayload payload) {
payload.writeInt4(capabilityFlags);
payload.writeInt4(maxPacketSize);
payload.writeInt1(characterSet);
payload.writeReserved(23);
payload.writeStringNul(username);
writeAuthResponse(payload);
w... | @Test
void assertWriteWithClientPluginAuthLenencClientData() {
MySQLHandshakeResponse41Packet actual = new MySQLHandshakeResponse41Packet(100, MySQLConstants.DEFAULT_CHARSET.getId(), "root");
actual.setCapabilityFlags(MySQLCapabilityFlag.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA.getValue());
act... |
@Override
public void setMaxParallelism(int maxParallelism) {
maxParallelism = normalizeAndCheckMaxParallelism(maxParallelism);
Optional<String> validationResult = rescaleMaxValidator.apply(maxParallelism);
if (validationResult.isPresent()) {
throw new IllegalArgumentException(
... | @Test
void setMaxOutOfBounds() {
DefaultVertexParallelismInfo info = new DefaultVertexParallelismInfo(1, 1, ALWAYS_VALID);
assertThatThrownBy(() -> info.setMaxParallelism(-4))
.withFailMessage("not in valid bounds")
.isInstanceOf(IllegalArgumentException.class);
... |
public static List<FieldInfo> buildSourceSchemaEntity(final LogicalSchema schema) {
final List<FieldInfo> allFields = schema.columns().stream()
.map(EntityUtil::toFieldInfo)
.collect(Collectors.toList());
if (allFields.isEmpty()) {
throw new IllegalArgumentException("Root schema should co... | @Test
public void shouldBuildCorrectStructField() {
// Given:
final LogicalSchema schema = LogicalSchema.builder()
.valueColumn(ColumnName.of("field"), SqlTypes.struct()
.field("innerField", SqlTypes.STRING)
.build())
.build();
// When:
final List<FieldInfo> fi... |
public static boolean isTimeoutException(Throwable throwable) {
return throwable instanceof SocketTimeoutException || throwable instanceof ConnectTimeoutException
|| throwable instanceof TimeoutException || throwable.getCause() instanceof TimeoutException;
} | @Test
void testIsTimeoutException() {
assertFalse(HttpUtils.isTimeoutException(new NacosRuntimeException(0)));
assertTrue(HttpUtils.isTimeoutException(new TimeoutException()));
assertTrue(HttpUtils.isTimeoutException(new SocketTimeoutException()));
assertTrue(HttpUtils.isTimeoutExcep... |
public void publishArtifacts(List<ArtifactPlan> artifactPlans, EnvironmentVariableContext environmentVariableContext) {
final File pluggableArtifactFolder = publishPluggableArtifacts(artifactPlans, environmentVariableContext);
try {
final List<ArtifactPlan> mergedPlans = artifactPlanFilter.g... | @Test
public void shouldPublishPluggableArtifactsAndUploadMetadataFileToServer() {
final ArtifactStore s3ArtifactStore = new ArtifactStore("s3", "cd.go.s3", create("access_key", false, "some-key"));
final ArtifactStore dockerArtifactStore = new ArtifactStore("docker", "cd.go.docker", create("registr... |
public byte[] encode(String val, String delimiters) {
return codecs[0].encode(val);
} | @Test
public void testEncodeChinesePersonNameGBK() {
assertArrayEquals(CHINESE_PERSON_NAME_GB18030_BYTES,
gbk().encode(CHINESE_PERSON_NAME_GB18030, PN_DELIMS));
} |
public void execute() {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
.visit(treeRootHolder.getReportTreeRoot());
} | @Test
public void dont_compute_duplicated_blocks_for_test_files() {
duplicationRepository.addDuplication(FILE_5_REF, new TextBlock(1, 1), new TextBlock(3, 3));
duplicationRepository.addDuplication(FILE_5_REF, new TextBlock(2, 2), new TextBlock(3, 3));
underTest.execute();
assertRawMeasureValue(FILE_... |
@Udf
public <T> List<T> distinct(
@UdfParameter(description = "Array of values to distinct") final List<T> input) {
if (input == null) {
return null;
}
final Set<T> distinctVals = Sets.newLinkedHashSetWithExpectedSize(input.size());
distinctVals.addAll(input);
return new ArrayList<>(di... | @SuppressWarnings("unchecked")
@Test
public void shouldDistinctArrayOfMaps() {
final Map<String, Integer> map1 = ImmutableMap.of("foo", 1, "bar", 2, "baz", 3);
final Map<String, Integer> map2 = ImmutableMap.of("foo", 10, "baz", 3);
final Map<String, Integer> map3 = ImmutableMap.of("foo", 1, "bar", 2, "b... |
@Override
public TenantPackageDO validTenantPackage(Long id) {
TenantPackageDO tenantPackage = tenantPackageMapper.selectById(id);
if (tenantPackage == null) {
throw exception(TENANT_PACKAGE_NOT_EXISTS);
}
if (tenantPackage.getStatus().equals(CommonStatusEnum.DISABLE.getS... | @Test
public void testValidTenantPackage_success() {
// mock 数据
TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class,
o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()));
tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据
// 调用
... |
public RuntimeOptionsBuilder parse(Class<?> clazz) {
RuntimeOptionsBuilder args = new RuntimeOptionsBuilder();
for (Class<?> classWithOptions = clazz; hasSuperClass(
classWithOptions); classWithOptions = classWithOptions.getSuperclass()) {
CucumberOptions options = requireNonNul... | @Test
void create_with_extra_glue() {
RuntimeOptions runtimeOptions = parser().parse(ClassWithExtraGlue.class).build();
assertThat(runtimeOptions.getGlue(),
contains(uri("classpath:/app/features/hooks"), uri("classpath:/io/cucumber/core/options")));
} |
@Override
public ShenyuContext decorator(final ShenyuContext shenyuContext, final MetaData metaData) {
String path = shenyuContext.getPath();
shenyuContext.setMethod(path);
shenyuContext.setRealUrl(path);
shenyuContext.setRpcType(RpcTypeEnum.WEB_SOCKET.getName());
shenyuConte... | @Test
public void testDecorator() {
MetaData metaData = null;
ShenyuContext shenyuContext = new ShenyuContext();
webSocketShenyuContextDecorator.decorator(shenyuContext, metaData);
Assertions.assertNull(shenyuContext.getMethod());
Assertions.assertEquals(shenyuContext.getRpcT... |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext builderContext) {
final Stacker contextStacker = builderContext.buildNodeContext(getId().toString());
return getSource().buildStream(builderContext)
.filter(
getPredicate(),
contextStacker
);
} | @Test
public void shouldApplyFilterCorrectly() {
// When:
node.buildStream(planBuildContext);
// Then:
verify(sourceNode).buildStream(planBuildContext);
verify(schemaKStream).filter(predicate, stacker);
} |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
@Timeout(5)
public void shouldNotEncounterInfiniteLoop() {
// This byte sequence gets parsed as CharacterIterator.DONE and can cause issues if
// comparisons to that character are done to check if the end of a string has been reached.
// For more information, see https://issues.apa... |
@Override
public List<FetchArtifactEnvironmentVariable> getFetchArtifactEnvironmentVariablesFromResponseBody(String responseBody) {
List<FetchArtifactEnvironmentVariable> result = DEFAULT_GSON.fromJson(responseBody, new TypeToken<List<FetchArtifactEnvironmentVariable>>() {}.getType());
return Option... | @Test
public void fetchArtifactMessage_shouldDeserializeAndAssumeEmpty() {
Assertions.assertThat(new ArtifactMessageConverterV2().getFetchArtifactEnvironmentVariablesFromResponseBody("")).isEmpty();
} |
public StringSubject factValue(String key) {
return doFactValue(key, null);
} | @Test
public void factValueIntFailNotEnoughWithKey() {
Object unused = expectFailureWhenTestingThat(fact("foo", "the foo")).factValue("foo", 5);
assertFailureKeys("for key", "index too high", "fact count was");
assertFailureValue("for key", "foo");
assertFailureValue("index too high", "5");
assert... |
public void importCounters(String[] counterNames, String[] counterKinds, long[] counterDeltas) {
final int length = counterNames.length;
if (counterKinds.length != length || counterDeltas.length != length) {
throw new AssertionError("array lengths do not match");
}
for (int i = 0; i < length; ++i)... | @Test
public void testMultipleCounters() throws Exception {
String[] names = {"sum_counter", "max_counter", "min_counter"};
String[] kinds = {"sum", "max", "min"};
long[] deltas = {100, 200, 300};
counters.importCounters(names, kinds, deltas);
Counter<Long, Long> sumCounter = getCounter("sum_count... |
@VisibleForTesting
Set<Artifact> getProjectDependencies() {
return session.getProjects().stream()
.map(MavenProject::getArtifact)
.filter(artifact -> !artifact.equals(project.getArtifact()))
.filter(artifact -> artifact.getFile() != null)
.collect(Collectors.toSet());
} | @Test
public void testGetProjectDependencies() {
MavenProject rootPomProject = mock(MavenProject.class);
MavenProject jibSubModule = mock(MavenProject.class);
MavenProject sharedLibSubModule = mock(MavenProject.class);
when(mockMavenSession.getProjects())
.thenReturn(Arrays.asList(rootPomProje... |
@Override
public void run() {
if (backgroundJobServer.isNotReadyToProcessJobs()) return;
try (PeriodicTaskRunInfo runInfo = taskStatistics.startRun(backgroundJobServerConfiguration())) {
tasks.forEach(task -> task.run(runInfo));
runInfo.markRunAsSucceeded();
} catch ... | @Test
void jobHandlerStopsBackgroundJobServerIfTooManyExceptions() {
Task mockedTask = mockTaskThatThrows(new SevereJobRunrException("Could not resolve ConcurrentJobModificationException", new UnresolvableConcurrentJobModificationException(emptyList(), null)));
JobHandler jobHandler = createJobHandl... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files.keySet()) {
if(file.isFile() || file.isSymbolicLink()) {
callback.delete(file);
try {
... | @Test(expected = NotfoundException.class)
public void testDeleteNotFound() throws Exception {
final Path test = new Path(new SFTPHomeDirectoryService(session).find(), "t", EnumSet.of(Path.Type.file));
try {
new SFTPDeleteFeature(session).delete(Collections.singletonList(test), new Disabl... |
@Override
public boolean tryToLockWebLeader() {
return webLeaderLocked.compareAndSet(false, true);
} | @Test
public void tryToLockWebLeader_returns_true_if_first_call() {
assertThat(underTest.tryToLockWebLeader()).isTrue();
// next calls return false
assertThat(underTest.tryToLockWebLeader()).isFalse();
assertThat(underTest.tryToLockWebLeader()).isFalse();
} |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldMaintainOrderOfReturnedQueries() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
// When:
final List<QueryMetadata> queries = KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"create stream foo as select * from orders;"
+ "crea... |
@Override
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (GetRepositoryNamesMeta) smi;
data = (GetRepositoryNamesData) sdi;
if ( super.init( smi, sdi ) ) {
try {
// Get the repository objects from the repository...
//
data.list = getRepositoryO... | @Test
public void testGetRepoList_transOnly_Extended() throws KettleException {
init( repoExtended, "/", true, ".*", "", Transformations, 2 );
} |
public DirectoryEntry lookUp(
File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException {
checkNotNull(path);
checkNotNull(options);
DirectoryEntry result = lookUp(workingDirectory, path, options, 0);
if (result == null) {
// an intermediate file in the path... | @Test
public void testLookup_relative() throws IOException {
assertExists(lookup("one"), "work", "one");
assertExists(lookup("one/two/three"), "two", "three");
} |
public List<Region> findRegionsByKeyRange(final byte[] startKey, final byte[] endKey) {
final StampedLock stampedLock = this.stampedLock;
final long stamp = stampedLock.readLock();
try {
final byte[] realStartKey = BytesUtil.nullToEmpty(startKey);
final NavigableMap<byte[... | @Test
public void findRegionsByKeyRangeTest() {
// case-1
{
RegionRouteTable table = new RegionRouteTable();
Region region = makeRegion(-1, null, null);
table.addOrUpdateRegion(region);
List<Region> regionList = table.findRegionsByKeyRange(KeyValueTool... |
public void validateAndMergeOutputParams(StepRuntimeSummary runtimeSummary) {
Optional<String> externalJobId = extractExternalJobId(runtimeSummary);
if (externalJobId.isPresent()) {
Optional<OutputData> outputDataOpt =
outputDataDao.getOutputDataForExternalJob(externalJobId.get(), ExternalJobTyp... | @Test
public void testUndefinedOutputParameter() {
setupOutputDataDao();
runtimeSummary = runtimeSummaryBuilder().artifacts(artifacts).build();
AssertHelper.assertThrows(
"throws validation error if output param not defined",
MaestroValidationException.class,
"Invalid output parame... |
public static String formatIso8601ForCCTray(Date date) {
if (date == null) {
return null;
}
return formatterUtc.print(date.getTime());
} | @Test
public void shouldSerializeDateForCcTray() {
Date date = new DateTime("2008-12-09T18:56:14+08:00").toDate();
assertThat(DateUtils.formatIso8601ForCCTray(date), is("2008-12-09T10:56:14Z"));
} |
@VisibleForTesting
void validateEmailUnique(Long id, String email) {
if (StrUtil.isBlank(email)) {
return;
}
AdminUserDO user = userMapper.selectByEmail(email);
if (user == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的用户
if (id == null... | @Test
public void testValidateEmailUnique_emailExistsForUpdate() {
// 准备参数
Long id = randomLongId();
String email = randomString();
// mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
// 调用,校验异常
assertServiceException(() -> userService.va... |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
... | @Test
public void testCollectFetchInitializationWithNullPosition() {
final TopicPartition topicPartition0 = new TopicPartition("topic", 0);
final SubscriptionState subscriptions = mock(SubscriptionState.class);
when(subscriptions.hasValidPosition(topicPartition0)).thenReturn(true);
w... |
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException {
ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null"));
if (null == value) {
return convertNullValue(co... | @SneakyThrows(MalformedURLException.class)
@Test
void assertConvertURLValue() throws SQLException {
String urlString = "https://shardingsphere.apache.org/";
URL url = (URL) ResultSetUtils.convertValue(urlString, URL.class);
assertThat(url, is(new URL(urlString)));
} |
public void poll(RequestFuture<?> future) {
while (!future.isDone())
poll(time.timer(Long.MAX_VALUE), future);
} | @Test
public void testMetadataFailurePropagated() {
KafkaException metadataException = new KafkaException();
metadata.fatalError(metadataException);
Exception exc = assertThrows(Exception.class, () -> consumerClient.poll(time.timer(Duration.ZERO)));
assertEquals(metadataException, ex... |
String resolveKey(String notifierDescriptorName) {
return notifierDescriptorName + ".json";
} | @Test
void resolveKeyTest() {
assertThat(notifierConfigStore.resolveKey("fake-notifier"))
.isEqualTo("fake-notifier.json");
assertThat(notifierConfigStore.resolveKey("other-notifier"))
.isEqualTo("other-notifier.json");
} |
@Override
public ActivitiesInfo getActivities(HttpServletRequest hsr, String nodeId,
String groupBy) {
try {
// Check the parameters to ensure that the parameters are not empty
Validate.checkNotNullAndNotEmpty(nodeId, "nodeId");
Validate.checkNotNullAndNotEmpty(groupBy, "groupBy");
... | @Test
public void testGetActivitiesError() throws Exception {
// nodeId is empty
LambdaTestUtils.intercept(IllegalArgumentException.class,
"'nodeId' must not be empty.",
() -> interceptor.getActivities(null, "", "DIAGNOSTIC"));
// groupBy is empty
LambdaTestUtils.intercept(IllegalArgu... |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = originalGlyphIds;
for (String feature : FEATURES_IN_ORDER)
{
if (!gsubData.isFeatureSupported(feature))
{
LOG.debug("the fe... | @Test
void testApplyTransforms_ra_e_hosshu()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(352, 108, 87, 101);
// when
List<Integer> result = gsubWorkerForBengali.applyTransforms(getGlyphIds("রুপো"));
// then
assertEquals(glyphsAfterGsub, result);
... |
public static Map<String, Object> toValueMap(ReferenceMap m, Map<String, ValueReference> parameters) {
final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.builder();
for (Map.Entry<String, Reference> entry : m.entrySet()) {
final Object value = valueOf(entry.getValue(), para... | @Test
public void toValueMapWithMissingParameter() {
final Map<String, ValueReference> parameters = Collections.emptyMap();
final ReferenceMap map = new ReferenceMap(Collections.singletonMap("param", ValueReference.createParameter("STRING")));
assertThatThrownBy(() -> ReferenceMapUtils.toVa... |
protected Session openSession() throws RepositoryException {
if (ObjectHelper.isEmpty(getJcrEndpoint().getWorkspaceName())) {
return getJcrEndpoint().getRepository().login(getJcrEndpoint().getCredentials());
} else {
return getJcrEndpoint().getRepository().login(getJcrEndpoint().... | @Test
public void testNodeTypeIsSpecified() throws Exception {
Exchange exchange = createExchangeWithBody("Test");
exchange.getIn().removeHeader("testClass"); //there is no definition of such property in nt:resource
exchange.getIn().setHeader(JcrConstants.JCR_NODE_NAME, "typedNode");
... |
@Override
public AppResponse process(Flow flow, AppSessionRequest request) {
if (appSession.getRegistrationId() == null) {
return new NokResponse();
}
Map<String, String> result = digidClient.getExistingAccount(appSession.getRegistrationId(), appSession.getLanguage());
... | @Test
void processNOKResponseTest(){
when(digidClientMock.getExistingAccount(1337L, "NL")).thenReturn(Map.of(
lowerUnderscore(STATUS), "OK"
));
AppResponse appResponse = checkExistingAccount.process(flowMock, null);
assertTrue(appResponse instanceof NokResponse);
... |
public void openFile() {
openFile( false );
} | @Test
public void testLoadLastUsedTransLocalNoRepositoryAtStartup() throws Exception {
String repositoryName = null;
String fileName = "fileName";
setLoadLastUsedJobLocalWithRepository( false, repositoryName, null, fileName, true, true );
verify( spoon ).openFile( fileName, null, false );
} |
@Override
public PageData<DashboardInfo> findDashboardsByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.toPageData(dashboardInfoRepository
.findByTenantId(
tenantId,
pageLink.getTextSearch(),
DaoUtil.toPagea... | @Test
public void testFindDashboardsByTenantId() {
UUID tenantId1 = Uuids.timeBased();
UUID tenantId2 = Uuids.timeBased();
for (int i = 0; i < 20; i++) {
createDashboard(tenantId1, i);
createDashboard(tenantId2, i * 2);
}
PageLink pageLink = new Page... |
public static <T, S> T copy(S source, T target, String... ignore) {
return copy(source, target, DEFAULT_CONVERT, ignore);
} | @Test
@SneakyThrows
public void testCrossClassLoader() {
URL clazz = new File("target/test-classes").getAbsoluteFile().toURI().toURL();
System.out.println(clazz);
URLClassLoader loader = new URLClassLoader(new URL[]{
clazz
}, ClassUtils.getDefaultClassLoader()){
... |
protected List<List<Comparable>> getTableTransInfo(long txnId) throws AnalysisException {
List<List<Comparable>> tableInfos = new ArrayList<>();
readLock();
try {
TransactionState transactionState = unprotectedGetTransactionState(txnId);
if (null == transactionState) {
... | @Test
public void testGetTableTransInfo() throws AnalysisException {
DatabaseTransactionMgr masterDbTransMgr =
masterTransMgr.getDatabaseTransactionMgr(GlobalStateMgrTestUtil.testDbId1);
Long txnId = lableToTxnId.get(GlobalStateMgrTestUtil.testTxnLable1);
List<List<Comparable... |
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
this.config = TbNodeUtils.convert(configuration, TbSendRestApiCallReplyNodeConfiguration.class);
} | @Test
public void givenDefaultConfig_whenInit_thenDoesNotThrowException() {
var configuration = new TbNodeConfiguration(JacksonUtil.valueToTree(config));
assertThatNoException().isThrownBy(() -> node.init(ctxMock, configuration));
} |
@VisibleForTesting
@CheckForNull
CharsetHandler getHandler(Dialect dialect) {
switch (dialect.getId()) {
case H2.ID:
// nothing to check
return null;
case Oracle.ID:
return new OracleCharsetHandler(sqlExecutor);
case PostgreSql.ID:
return new PostgresCharsetHand... | @Test
public void getHandler_throws_IAE_if_unsupported_db() {
Dialect unsupportedDialect = mock(Dialect.class);
when(unsupportedDialect.getId()).thenReturn("foo");
assertThatThrownBy(() -> underTest.getHandler(unsupportedDialect))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Dat... |
@Override
public ClusterInfo clusterGetClusterInfo() {
RFuture<Map<String, String>> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.CLUSTER_INFO);
Map<String, String> entries = syncFuture(f);
Properties props = new Properties();
for (Entry<String, Str... | @Test
public void testClusterGetClusterInfo() {
ClusterInfo info = connection.clusterGetClusterInfo();
assertThat(info.getSlotsFail()).isEqualTo(0);
assertThat(info.getSlotsOk()).isEqualTo(MasterSlaveConnectionManager.MAX_SLOT);
assertThat(info.getSlotsAssigned()).isEqualTo(MasterSla... |
@PostMapping("/check-token")
@PermitAll
@Operation(summary = "校验访问令牌")
@Parameter(name = "token", required = true, description = "访问令牌", example = "biu")
public CommonResult<OAuth2OpenCheckTokenRespVO> checkToken(HttpServletRequest request,
... | @Test
public void testCheckToken() {
// 准备参数
HttpServletRequest request = mockRequest("demo_client_id", "demo_client_secret");
String token = randomString();
// mock 方法
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class).setUserType(UserTypeEnum.ADMIN.ge... |
@Override
public void write(final OutputStream out) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
try {
out.write("[".getBytes(StandardCharsets.UTF_8));
write(out, buildHeader());
final BlockingRowQueue rowQueue = queryMetadata.getRowQueue();
while (!connectionClosed && queryMetadat... | @Test
public void shouldWriteAnyPendingRowsBeforeReportingException() {
// Given:
doAnswer(streamRows("Row1", "Row2", "Row3"))
.when(rowQueue).drainTo(any());
createWriter();
givenUncaughtException(new KsqlException("Server went Boom"));
// When:
writer.write(out);
// Then:
... |
@Override
public YamlShardingStrategyConfiguration swapToYamlConfiguration(final ShardingStrategyConfiguration data) {
YamlShardingStrategyConfiguration result = new YamlShardingStrategyConfiguration();
if (data instanceof StandardShardingStrategyConfiguration) {
result.setStandard(creat... | @Test
void assertSwapToYamlConfigurationForStandardShardingStrategy() {
ShardingStrategyConfiguration data = new StandardShardingStrategyConfiguration("order_id", "core_standard_fixture");
YamlShardingStrategyConfigurationSwapper swapper = new YamlShardingStrategyConfigurationSwapper();
Yaml... |
@Override
public String getContextName() {
return this.contextName;
} | @Test
public void testGetContextName() {
assertEquals(contextName, v3SnmpConfiguration.getContextName());
} |
public RegistryBuilder address(String address) {
this.address = address;
return getThis();
} | @Test
void address() {
RegistryBuilder builder = new RegistryBuilder();
builder.address("address");
Assertions.assertEquals("address", builder.build().getAddress());
} |
@Override
public FSDataOutputStream create(Path file, FsPermission permission,
boolean overwrite, int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
final FTPClient client = connect();
Path workDir = new Path(client.printWorkingDirectory());
Path abs... | @Test
public void testCreateWithoutWritePermissions() throws Exception {
BaseUser user = server.addUser("test", "password");
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "ftp:///");
configuration.set("fs.ftp.host", "localhost");
configuration.setInt("fs.ftp.... |
public static String generateSparkAppId(final SparkApplication app) {
long attemptId = ModelUtils.getAttemptId(app);
String preferredId = String.format("%s-%d", app.getMetadata().getName(), attemptId);
if (preferredId.length() > DEFAULT_ID_LENGTH_LIMIT) {
int preferredIdPrefixLength =
DEFAUL... | @Test
void sparkAppIdShouldBeDeterministicPerAppPerAttempt() {
SparkApplication mockApp1 = mock(SparkApplication.class);
SparkApplication mockApp2 = mock(SparkApplication.class);
ApplicationStatus mockStatus1 = mock(ApplicationStatus.class);
ApplicationStatus mockStatus2 = mock(ApplicationStatus.class... |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComDropDbPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_DROP_DB, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class));
} |
public byte[] encode(String val, String delimiters) {
return codecs[0].encode(val);
} | @Test
public void testEncodeKoreanPersonName() {
assertArrayEquals(KOREAN_PERSON_NAME_BYTES,
ksx1001().encode(KOREAN_PERSON_NAME, PN_DELIMS));
} |
public static Collection<AndPredicate> getAndPredicates(final ExpressionSegment expression) {
Collection<AndPredicate> result = new LinkedList<>();
extractAndPredicates(result, expression);
return result;
} | @Test
void assertExtractAndPredicatesAndCondition() {
ColumnSegment columnSegment1 = new ColumnSegment(28, 35, new IdentifierValue("order_id"));
ParameterMarkerExpressionSegment parameterMarkerExpressionSegment1 = new ParameterMarkerExpressionSegment(39, 39, 0);
ExpressionSegment leftExpress... |
@Override
public int getMaxParallelism() {
return parallelismInfo.getMaxParallelism();
} | @Test
void testFallingBackToDefaultMaxParallelism() throws Exception {
final int defaultMaxParallelism = 13;
final ExecutionJobVertex ejv =
createDynamicExecutionJobVertex(-1, -1, defaultMaxParallelism);
assertThat(ejv.getMaxParallelism()).isEqualTo(defaultMaxParallelism);
... |
public static Resumed resumed(XmlPullParser parser) throws XmlPullParserException, IOException {
ParserUtils.assertAtStartTag(parser);
long h = ParserUtils.getLongAttribute(parser, "h");
String previd = parser.getAttributeValue("", "previd");
parser.next();
ParserUtils.assertAtEn... | @Test
public void testParseResumed() throws Exception {
long handledPackets = 42;
String previousID = "zid615d9";
String resumedStanza = XMLBuilder.create("resumed")
.a("xmlns", "urn:xmpp:sm:3")
.a("h", String.valueOf(handledPackets))
.a("prev... |
static void divide(Slice dividend, int dividendScaleFactor, Slice divisor, int divisorScaleFactor, Slice quotient, Slice remainder)
{
divide(getRawLong(dividend, 0), getRawLong(dividend, 1), dividendScaleFactor, getRawLong(divisor, 0), getRawLong(divisor, 1), divisorScaleFactor, quotient, remainder);
} | @Test
public void testDivide()
{
// simple cases
assertDivideAllSigns("0", "10");
assertDivideAllSigns("5", "10");
assertDivideAllSigns("50", "100");
assertDivideAllSigns("99", "10");
assertDivideAllSigns("95", "10");
assertDivideAllSigns("91", "10");
... |
@Override
public TimestampedKeyValueStore<K, V> build() {
KeyValueStore<Bytes, byte[]> store = storeSupplier.get();
if (!(store instanceof TimestampedBytesStore)) {
if (store.persistent()) {
store = new KeyValueToTimestampedKeyValueByteStoreAdapter(store);
} e... | @Test
public void shouldHaveChangeLoggingStoreWhenLoggingEnabled() {
setUp();
final TimestampedKeyValueStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
... |
public Canvas canvas() {
Canvas canvas = new Canvas(getLowerBound(), getUpperBound());
canvas.add(this);
if (name != null) {
canvas.setTitle(name);
}
return canvas;
} | @Test
public void testScatter() throws Exception {
System.out.println("Scatter");
var canvas = ScatterPlot.of(iris, "sepallength", "sepalwidth", "class", '*').canvas();
canvas.setAxisLabels("sepallength", "sepalwidth");
canvas.window();
} |
public MessagesRequestSpec simpleQueryParamsToFullRequestSpecification(final String query,
final Set<String> streams,
final String timerangeKeyword,
... | @Test
void usesProperDefaults() {
AggregationRequestSpec aggregationRequestSpec = toTest.simpleQueryParamsToFullRequestSpecification(null,
null,
null,
List.of("http_method"),
null);
assertThat(aggregationRequestSpec).isEqualTo(new Aggr... |
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result result;
String value = getUrl().getMethodParameter(
RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString())
.trim();
if (ConfigUtils.isEmpty(value)) {
... | @Test
void testMockInvokerFromOverride_Invoke_force_throw() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY,
URL.encode(
PATH_KEY + "=" + IHelloService.class.... |
@Override
public boolean isDirectory(URI uri)
throws IOException {
try {
String prefix = normalizeToDirectoryPrefix(uri);
if (prefix.equals(DELIMITER)) {
return true;
}
ListObjectsV2Request listObjectsV2Request =
ListObjectsV2Request.builder().bucket(uri.getHost())... | @Test
public void testIsDirectory()
throws Exception {
String[] originalFiles = new String[]{"a-dir.txt", "b-dir.txt", "c-dir.txt"};
String folder = "my-files-dir";
String childFolder = "my-files-dir-child";
for (String fileName : originalFiles) {
String folderName = folder + DELIMITER + c... |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldGenerateCorrectCodeForComparisonWithNegativeNumbers() {
// Given:
final Expression expression = new ComparisonExpression(
ComparisonExpression.Type.GREATER_THAN,
COL3,
new DoubleLiteral(-10.0)
);
// When:
final String javaExpression = sqlToJavaVisit... |
public String doGetConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group,
String tenant, String tag, String isNotify, String clientIp) throws IOException, ServletException {
return doGetConfig(request, response, dataId, group, tenant, tag, isNotify, clientIp, f... | @Test
void testDoGetConfigFormalV2() throws Exception {
String dataId = "dataId1234552333V2";
String group = "group";
String tenant = "tenant";
configCacheServiceMockedStatic.when(() -> ConfigCacheService.tryConfigReadLock(GroupKey2.getKey(dataId, group, tenant)))
.th... |
public List<PartitionInfo> getTopicMetadata(String topic, boolean allowAutoTopicCreation, Timer timer) {
MetadataRequest.Builder request = new MetadataRequest.Builder(Collections.singletonList(topic), allowAutoTopicCreation);
Map<String, List<PartitionInfo>> topicMetadata = getTopicMetadata(request, tim... | @Test
public void testGetTopicMetadataOfflinePartitions() {
buildFetcher();
assignFromUser(singleton(tp0));
MetadataResponse originalResponse = newMetadataResponse(Errors.NONE); //baseline ok response
//create a response based on the above one with all partitions being leaderless
... |
@ApiOperation(value = "Delete a group", tags = { "Groups" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the group was found and has been deleted. Response-body is intentionally empty."),
@ApiResponse(code = 404, message = "Indicates the requested group... | @Test
public void testDeleteGroup() throws Exception {
try {
Group testGroup = identityService.newGroup("testgroup");
testGroup.setName("Test group");
testGroup.setType("Test type");
identityService.saveGroup(testGroup);
closeResponse(executeReque... |
public void setCalendar( int recordsFilter, GregorianCalendar startDate, GregorianCalendar endDate ) throws KettleException {
this.startDate = startDate;
this.endDate = endDate;
this.recordsFilter = recordsFilter;
if ( this.startDate == null || this.endDate == null ) {
throw new KettleException( B... | @Test
public void testSetCalendar() {
SalesforceConnection conn = mock( SalesforceConnection.class, Mockito.CALLS_REAL_METHODS );
// Test valid data
try {
conn.setCalendar( new Random().nextInt( SalesforceConnectionUtils.recordsFilterDesc.length ),
new GregorianCalendar( 2016, Calendar.JA... |
@Override
public String getPrivProtocol() {
return privProtocol;
} | @Test
public void testGetPrivProtocol() {
assertEquals(privProtocol, defaultSnmpv3Device.getPrivProtocol());
} |
public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword)
throws IOException, GeneralSecurityException
{
PrivateKey key;
try {
key = createPrivateKey(privateKeyFile, keyPassword);
} catch (OperatorCreationException | IOExcepti... | @Test
void testParsingPKCS8WithWrongPassword() throws IOException, GeneralSecurityException {
assertThrows(GeneralSecurityException.class, () -> {
PEMImporter.loadKeyStore(pemCert, privkeyWithPasswordPKCS8, "nottest");
});
} |
@Override
public List<PrivilegedOperation> bootstrap(Configuration configuration)
throws ResourceHandlerException {
conf = configuration;
cGroupsHandler
.initializeCGroupController(CGroupsHandler.CGroupController.NET_CLS);
this.tagMappingManager = createNetworkTagMappingManager(conf);
... | @Test
public void testBootstrap() {
NetworkPacketTaggingHandlerImpl handlerImpl =
createNetworkPacketTaggingHandlerImpl();
try {
handlerImpl.bootstrap(conf);
verify(cGroupsHandlerMock).initializeCGroupController(
eq(CGroupsHandler.CGroupController.NET_CLS));
verifyNoMoreIn... |
@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 testConvertTextMessageToAmqpMessageWithNoBody() throws Exception {
ActiveMQTextMessage outbound = createTextMessage();
outbound.onSend();
outbound.storeContent();
JMSMappingOutboundTransformer transformer = new JMSMappingOutboundTransformer();
EncodedMessa... |
public static Object project(Schema source, Object record, Schema target) throws SchemaProjectorException {
checkMaybeCompatible(source, target);
if (source.isOptional() && !target.isOptional()) {
if (target.defaultValue() != null) {
if (record != null) {
... | @Test
public void testStructRemoveField() {
Schema source = SchemaBuilder.struct()
.field("field", Schema.INT32_SCHEMA)
.field("field2", Schema.INT32_SCHEMA)
.build();
Struct sourceStruct = new Struct(source);
sourceStruct.put("field", 1);
... |
public static LocalRetryableExecution executeLocallyWithRetry(NodeEngine nodeEngine, Operation operation) {
if (operation.getOperationResponseHandler() != null) {
throw new IllegalArgumentException("Operation must not have a response handler set");
}
if (!operation.returnsResponse())... | @Test(expected = IllegalArgumentException.class)
public void executeLocallyWithRetryFailsWhenOperationDoesNotReturnResponse() {
final Operation op = new Operation() {
@Override
public boolean returnsResponse() {
return false;
}
};
executeLo... |
@SuppressWarnings("argument")
static Status runSqlLine(
String[] args,
@Nullable InputStream inputStream,
@Nullable OutputStream outputStream,
@Nullable OutputStream errorStream)
throws IOException {
String[] modifiedArgs = checkConnectionArgs(args);
SqlLine sqlLine = new SqlLine... | @Test
public void testSqlLine_fixedWindow() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String[] args =
buildArgs(
"CREATE EXTERNAL TABLE table_test (col_a VARCHAR, col_b TIMESTAMP) TYPE 'test';",
"INSERT INTO table_test SELECT ... |
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"})
void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas,
MigrationDecisionCallback callback) {
assert oldReplicas.length == newReplicas.leng... | @Test
public void test_SHIFT_DOWN_performedBy_MOVE() throws UnknownHostException {
final PartitionReplica[] oldReplicas = {
new PartitionReplica(new Address("localhost", 5701), uuids[0]),
new PartitionReplica(new Address("localhost", 5702), uuids[1]),
new Part... |
public static InternalRequestSignature fromHeaders(Crypto crypto, byte[] requestBody, HttpHeaders headers) {
if (headers == null) {
return null;
}
String signatureAlgorithm = headers.getHeaderString(SIGNATURE_ALGORITHM_HEADER);
String encodedSignature = headers.getHeaderStri... | @Test
public void fromHeadersShouldThrowExceptionOnInvalidSignatureAlgorithm() {
assertThrows(BadRequestException.class, () -> InternalRequestSignature.fromHeaders(crypto, REQUEST_BODY,
internalRequestHeaders(ENCODED_SIGNATURE, "doesn'texist")));
} |
public ClusterSerdes init(Environment env,
ClustersProperties clustersProperties,
int clusterIndex) {
ClustersProperties.Cluster clusterProperties = clustersProperties.getClusters().get(clusterIndex);
log.debug("Configuring serdes for cluster {}", clusterP... | @Test
void pluggedSerdesInitializedByLoader() {
ClustersProperties.SerdeConfig customSerdeConfig = new ClustersProperties.SerdeConfig();
customSerdeConfig.setName("MyPluggedSerde");
customSerdeConfig.setFilePath("/custom.jar");
customSerdeConfig.setClassName("org.test.MyPluggedSerde");
customSerde... |
@Override
protected FieldValue doGet(String fieldName, EventWithContext eventWithContext) {
final ImmutableMap.Builder<String, Object> dataModelBuilder = ImmutableMap.builder();
if (eventWithContext.messageContext().isPresent()) {
dataModelBuilder.put("source", eventWithContext.messageC... | @Test
public void templateNumberFormatting() {
final TestEvent event = new TestEvent();
final EventWithContext eventWithContext = EventWithContext.create(event, newMessage(ImmutableMap.of("count", 10241234, "avg", 1024.42)));
final FieldValue fieldValue = newTemplate("count: ${source.count}... |
static CatalogLoader createCatalogLoader(
String name, Map<String, String> properties, Configuration hadoopConf) {
String catalogImpl = properties.get(CatalogProperties.CATALOG_IMPL);
if (catalogImpl != null) {
String catalogType = properties.get(ICEBERG_CATALOG_TYPE);
Preconditions.checkArgum... | @Test
public void testCreateCatalogHadoop() {
String catalogName = "hadoopCatalog";
props.put(
FlinkCatalogFactory.ICEBERG_CATALOG_TYPE, FlinkCatalogFactory.ICEBERG_CATALOG_TYPE_HADOOP);
Catalog catalog =
FlinkCatalogFactory.createCatalogLoader(catalogName, props, new Configuration())
... |
public static IPMappingAddress ipv4MappingAddress(IpPrefix ip) {
return new IPMappingAddress(ip, MappingAddress.Type.IPV4);
} | @Test
public void testIpv4MappingAddressMethod() {
IpPrefix ip = IpPrefix.valueOf("1.2.3.4/24");
MappingAddress mappingAddress = MappingAddresses.ipv4MappingAddress(ip);
IPMappingAddress ipMappingAddress =
checkAndConvert(mappingAddress,
Mappin... |
@Override
public int curThreadNum() {
return (int)curThreadNum.sum();
} | @Test
public void testStatisticLongAdder() throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger(0);
StatisticNode statisticNode = new StatisticNode();
ExecutorService bizEs1 = new ThreadPoolExecutor(THREAD_COUNT, THREAD_COUNT,
0L, TimeUnit.MILLISECOND... |
@Override
public void save(final CallContext ctx) {
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val requestedUrl = getRequestedUrl(webContext, sessionStore);
if (WebContextHelper.isPost(webContext)) {
LOGGER.debug("requestedUrl with data: {}... | @Test
public void testSavePost() {
val context = MockWebContext.create().setFullRequestURL(PAC4J_URL).setRequestMethod("POST");
context.addRequestParameter(KEY, VALUE);
val sessionStore = new MockSessionStore();
handler.save(new CallContext(context, sessionStore));
WithConten... |
public static int check(String passwd) {
if (null == passwd) {
throw new IllegalArgumentException("password is empty");
}
int len = passwd.length();
int level = 0;
// increase points
if (countLetter(passwd, CHAR_TYPE.NUM) > 0) {
level++;
}
if (countLetter(passwd, CHAR_TYPE.SMALL_LETTER) > 0) {
... | @Test
public void strengthTest(){
String passwd = "2hAj5#mne-ix.86H";
assertEquals(13, PasswdStrength.check(passwd));
} |
@Override
public void delete(RuleDao nativeEntity) {
ruleService.delete(nativeEntity.id());
} | @Test
@MongoDBFixtures("PipelineRuleFacadeTest.json")
public void delete() throws NotFoundException {
final RuleDao ruleDao = ruleService.loadByName("debug");
assertThat(ruleService.loadAll()).hasSize(2);
facade.delete(ruleDao);
assertThatThrownBy(() -> ruleService.loadByName("d... |
@VisibleForTesting
static String toString(@Nullable TaskManagerLocation location) {
// '(unassigned)' being the default value is added to support backward-compatibility for the
// deprecated fields
return location != null ? location.getEndpoint() : "(unassigned)";
} | @Test
void testTaskManagerLocationHandling() {
final TaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation();
assertThat(JobExceptionsHandler.toString(taskManagerLocation))
.isEqualTo(
String.format(
"%s:%s",
... |
@Override
public void checkBeforeUpdate(final DropBroadcastTableRuleStatement sqlStatement) {
if (!sqlStatement.isIfExists()) {
checkBroadcastTableRuleExist(sqlStatement);
}
} | @Test
void assertCheckSQLStatementWithoutToBeDroppedRule() {
DropBroadcastTableRuleStatement sqlStatement = new DropBroadcastTableRuleStatement(false, Collections.singleton("t_address"));
BroadcastRule rule = mock(BroadcastRule.class);
when(rule.getConfiguration()).thenReturn(new BroadcastRu... |
public static Interval of(String interval, TimeRange timeRange) {
switch (timeRange.type()) {
case TimeRange.KEYWORD: return timestampInterval(interval);
case TimeRange.ABSOLUTE:
return ofAbsoluteRange(interval, (AbsoluteRange)timeRange);
case TimeRange.RELATI... | @Test
public void returnsParsedIntervalIfRelativeRangeButBelowLimit() {
final RelativeRange relativeRange = RelativeRange.create(450);
final Interval interval = ApproximatedAutoIntervalFactory.of("minute", relativeRange);
assertThat(interval).isEqualTo(TimeUnitInterval.create(TimeUnitInter... |
public static String getExtension(final URI file) {
return file == null ? null : getExtension(file.toString());
} | @Test
void shouldGetExtension() {
assertThat(FileUtils.getExtension((String)null), nullValue());
assertThat(FileUtils.getExtension(""), nullValue());
assertThat(FileUtils.getExtension("/file/hello"), nullValue());
assertThat(FileUtils.getExtension("/file/hello.txt"), is(".txt"));
... |
@Override public boolean remove(long key1, long key2) {
return super.remove0(key1, key2);
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testRemove_whenDisposed() {
hsa.dispose();
hsa.remove(1, 1);
} |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<Path>();
// At least one entry successfully parsed
boolean success = false;
// Call hook for those im... | @Test(expected = FTPInvalidListException.class)
public void test3243() throws Exception {
Path path = new Path("/SunnyD", EnumSet.of(Path.Type.directory));
assertEquals("SunnyD", path.getName());
assertEquals("/SunnyD", path.getAbsolute());
final AttributedList<Path> list = new Attri... |
public static boolean isJsonValid(String schemaText, String jsonText) throws IOException {
return isJsonValid(schemaText, jsonText, null);
} | @Test
void testValidateJsonSuccess() {
boolean valid = false;
String schemaText = null;
String jsonText = "{\"name\": \"307\", \"model\": \"Peugeot 307\", \"year\": 2003}";
try {
// Load schema from file.
schemaText = FileUtils
.readFileToString(new File("tar... |
boolean canFilterPlayer(String playerName)
{
boolean isMessageFromSelf = playerName.equals(client.getLocalPlayer().getName());
return !isMessageFromSelf &&
(config.filterFriends() || !client.isFriended(playerName, false)) &&
(config.filterFriendsChat() || !isFriendsChatMember(playerName)) &&
(config.filte... | @Test
public void testMessageFromFriendsChatIsFiltered()
{
when(client.isFriended("B0aty", false)).thenReturn(false);
when(chatFilterConfig.filterFriendsChat()).thenReturn(true);
assertTrue(chatFilterPlugin.canFilterPlayer("B0aty"));
} |
@Converter
public static Map<String, Object> toMap(final Struct struct) {
final HashMap<String, Object> fieldsToValues = new HashMap<>();
struct.schema().fields().forEach(field -> {
Object value = struct.get(field);
// recursive call if we have nested structs
if... | @Test
void testToMapNestedStruct() {
Schema detailsSchema = SchemaBuilder.struct().field("age", SchemaBuilder.INT32_SCHEMA).build();
Schema valueSchema = SchemaBuilder.struct()
.name("valueSchema")
.field("id", SchemaBuilder.INT32_SCHEMA)
.field("name... |
public String prometheusName(String recordName,
String metricName) {
String baseName = StringUtils.capitalize(recordName)
+ StringUtils.capitalize(metricName);
String[] parts = SPLIT_PATTERN.split(baseName);
String joined = String.join("_", parts).toLowerCase();
r... | @Test
public void testNamingCamelCase() {
PrometheusMetricsSink sink = new PrometheusMetricsSink();
Assert.assertEquals("rpc_time_some_metrics",
sink.prometheusName("RpcTime", "SomeMetrics"));
Assert.assertEquals("om_rpc_time_om_info_keys",
sink.prometheusName("OMRpcTime", "OMInfoKeys"))... |
@Override
public void commitJob(JobContext originalContext) throws IOException {
JobContext jobContext = TezUtil.enrichContextWithVertexId(originalContext);
JobConf jobConf = jobContext.getJobConf();
long startTime = System.currentTimeMillis();
LOG.info("Committing job {} has started", jobContext.get... | @Test
public void testSuccessfulPartitionedWrite() throws IOException {
HiveIcebergOutputCommitter committer = new HiveIcebergOutputCommitter();
Table table = table(temp.toFile().getPath(), true);
JobConf conf = jobConf(table, 1);
List<Record> expected = writeRecords(table.name(), 1, 0, true, false, c... |
@Override
public void open() {
super.open();
for (String propertyKey : properties.stringPropertyNames()) {
LOGGER.debug("propertyKey: {}", propertyKey);
String[] keyValue = propertyKey.split("\\.", 2);
if (2 == keyValue.length) {
LOGGER.debug("key: {}, value: {}", keyValue[0], keyVal... | @Test
void testColumnAliasQuery() throws IOException, InterpreterException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setPrope... |
public static void close(final AutoCloseable closeable) {
if (null == closeable) {
return;
}
try {
closeable.close();
// CHECKSTYLE:OFF
} catch (final Exception ignored) {
// CHECKSTYLE:ON
}
} | @Test
void assertCloseWithNullResource() {
assertDoesNotThrow(() -> QuietlyCloser.close(null));
} |
static String generateIndexName(String baseString) {
return generateResourceId(
baseString,
ILLEGAL_INDEX_NAME_CHARS,
REPLACE_INDEX_NAME_CHAR,
MAX_INDEX_NAME_LENGTH,
TIME_FORMAT);
} | @Test
public void testGenerateIndexNameShouldReplaceStar() {
String testBaseString = "Test*DB*Name";
String actual = generateIndexName(testBaseString);
assertThat(actual).matches("test-db-name-\\d{8}-\\d{6}-\\d{6}");
} |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldThrowOnNoneExecutableDdlStatement() {
// When:
setupKsqlEngineWithSharedRuntimeEnabled();
final KsqlStatementException e = assertThrows(
KsqlStatementException.class,
() -> KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"... |
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
AsyncByteArrayFeeder streamFeeder = streamReader.getInputFeeder();
logger.info("Decoding XMPP data.. ");
byte[] buffer = new byte[in.readableBytes()];
in.readBytes(buffer);
... | @Test
public void testDecodeNoChannel() throws Exception {
XmlStreamDecoder decoder = new XmlStreamDecoder();
List<Object> list = Lists.newArrayList();
decoder.decode(new ActiveChannelHandlerContextAdapter(),
Unpooled.buffer(), list);
assertThat(list.size(), i... |
@VisibleForTesting
static List<String> getJmResourceParams(Configuration configuration) {
JobManagerProcessSpec jobManagerProcessSpec =
JobManagerProcessUtils.processSpecFromConfigWithNewOptionToInterpretLegacyHeap(
configuration, JobManagerOptions.JVM_HEAP_MEMORY);
... | @Test
void testJmLegacyHeapOptionSetsNewJvmHeap() {
Configuration configuration = new Configuration();
MemorySize heapSize = MemorySize.ofMebiBytes(10);
configuration.set(JobManagerOptions.JOB_MANAGER_HEAP_MEMORY, heapSize);
String jvmArgsLine = BashJavaUtils.getJmResourceParams(conf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.